Whamcloud - gitweb
Branch b1_8
[fs/lustre-release.git] / lustre / obdfilter / filter.c
1 /* -*- mode: c; c-basic-offset: 8; indent-tabs-mode: nil; -*-
2  * vim:expandtab:shiftwidth=8:tabstop=8:
3  *
4  * GPL HEADER START
5  *
6  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License version 2 only,
10  * as published by the Free Software Foundation.
11  *
12  * This program is distributed in the hope that it will be useful, but
13  * WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * General Public License version 2 for more details (a copy is included
16  * in the LICENSE file that accompanied this code).
17  *
18  * You should have received a copy of the GNU General Public License
19  * version 2 along with this program; If not, see
20  * http://www.sun.com/software/products/lustre/docs/GPLv2.pdf
21  *
22  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
23  * CA 95054 USA or visit www.sun.com if you need additional information or
24  * have any questions.
25  *
26  * GPL HEADER END
27  */
28 /*
29  * Copyright  2008 Sun Microsystems, Inc. All rights reserved
30  * Use is subject to license terms.
31  */
32 /*
33  * This file is part of Lustre, http://www.lustre.org/
34  * Lustre is a trademark of Sun Microsystems, Inc.
35  *
36  * lustre/obdfilter/filter.c
37  *
38  * Author: Peter Braam <braam@clusterfs.com>
39  * Author: Andreas Dilger <adilger@clusterfs.com>
40  */
41
42 /*
43  * Invariant: Get O/R i_mutex for lookup, if needed, before any journal ops
44  *            (which need to get journal_lock, may block if journal full).
45  *
46  * Invariant: Call filter_start_transno() before any journal ops to avoid the
47  *            same deadlock problem.  We can (and want) to get rid of the
48  *            transno sem in favour of the dir/inode i_mutex to avoid single
49  *            threaded operation on the OST.
50  */
51
52 #define DEBUG_SUBSYSTEM S_FILTER
53 #ifndef AUTOCONF_INCLUDED
54 #include <linux/config.h>
55 #endif
56 #include <linux/module.h>
57 #include <linux/fs.h>
58 #include <linux/dcache.h>
59 #include <linux/init.h>
60 #include <linux/version.h>
61 #include <linux/sched.h>
62 #include <linux/mount.h>
63 #include <linux/buffer_head.h>
64
65 #include <obd_class.h>
66 #include <obd_lov.h>
67 #include <lustre_dlm.h>
68 #include <lustre_fsfilt.h>
69 #include <lprocfs_status.h>
70 #include <lustre_log.h>
71 #include <libcfs/list.h>
72 #include <lustre_disk.h>
73 #include <lustre_quota.h>
74 #include <linux/slab.h>
75 #include <lustre_param.h>
76 #include <lustre/ll_fiemap.h>
77
78 #include "filter_internal.h"
79
80 static struct lvfs_callback_ops filter_lvfs_ops;
81 cfs_mem_cache_t *ll_fmd_cachep;
82
83 static void filter_commit_cb(struct obd_device *obd, __u64 transno,
84                              void *cb_data, int error)
85 {
86         struct obd_export *exp = cb_data;
87         LASSERTF(exp->exp_obd == obd,
88                  "%s: bad export (%p), obd (%p) != exp->exp_obd (%p)\n",
89                  obd->obd_name, exp, obd, exp->exp_obd);
90         obd_transno_commit_cb(obd, transno, exp, error);
91         class_export_put(exp);
92 }
93
94 int filter_version_get_check(struct obd_export *exp,
95                              struct obd_trans_info *oti, struct inode *inode)
96 {
97         __u64 curr_version;
98
99         if (inode == NULL || oti == NULL)
100                 RETURN(0);
101
102         curr_version = fsfilt_get_version(exp->exp_obd, inode);
103         if ((__s64)curr_version == -EOPNOTSUPP)
104                 RETURN(0);
105         /* VBR: version is checked always because costs nothing */
106         if (oti->oti_pre_version != 0 &&
107             oti->oti_pre_version != curr_version) {
108                 CDEBUG(D_INODE, "Version mismatch "LPX64" != "LPX64"\n",
109                        oti->oti_pre_version, curr_version);
110                 spin_lock(&exp->exp_lock);
111                 exp->exp_vbr_failed = 1;
112                 spin_unlock(&exp->exp_lock);
113                 RETURN (-EOVERFLOW);
114         }
115         oti->oti_pre_version = curr_version;
116         RETURN(0);
117 }
118
119 /* Assumes caller has already pushed us into the kernel context. */
120 int filter_finish_transno(struct obd_export *exp, struct inode *inode,
121                           struct obd_trans_info *oti,
122                           int rc, int force_sync)
123 {
124         struct filter_obd *filter = &exp->exp_obd->u.filter;
125         struct filter_export_data *fed = &exp->exp_filter_data;
126         struct lsd_client_data *lcd = fed->fed_lcd;
127         __u64 last_rcvd;
128         loff_t off;
129         int err, log_pri = D_RPCTRACE;
130
131         /* Propagate error code. */
132         if (rc)
133                 RETURN(rc);
134
135         if (!exp->exp_obd->obd_replayable || oti == NULL)
136                 RETURN(rc);
137
138         /* we don't allocate new transnos for replayed requests */
139         spin_lock(&filter->fo_translock);
140         if (oti->oti_transno == 0) {
141                 last_rcvd = le64_to_cpu(filter->fo_fsd->lsd_last_transno) + 1;
142                 filter->fo_fsd->lsd_last_transno = cpu_to_le64(last_rcvd);
143         } else {
144                 last_rcvd = oti->oti_transno;
145                 if (last_rcvd > le64_to_cpu(filter->fo_fsd->lsd_last_transno))
146                         filter->fo_fsd->lsd_last_transno = cpu_to_le64(last_rcvd);
147         }
148         oti->oti_transno = last_rcvd;
149         if (last_rcvd <= le64_to_cpu(lcd->lcd_last_transno)) {
150                 spin_unlock(&filter->fo_translock);
151                 LBUG();
152         }
153         lcd->lcd_last_transno = cpu_to_le64(last_rcvd);
154         lcd->lcd_pre_versions[0] = cpu_to_le64(oti->oti_pre_version);
155         lcd->lcd_last_xid = cpu_to_le64(oti->oti_xid);
156         target_trans_table_update(exp, last_rcvd);
157
158         spin_unlock(&filter->fo_translock);
159
160         if (inode)
161                 fsfilt_set_version(exp->exp_obd, inode, last_rcvd);
162
163         off = fed->fed_lr_off;
164         if (off <= 0) {
165                 CERROR("%s: client idx %d is %lld\n", exp->exp_obd->obd_name,
166                        fed->fed_lr_idx, fed->fed_lr_off);
167                 err = -EINVAL;
168         } else {
169                 class_export_get(exp); /* released when the cb is called */
170                 if (!force_sync)
171                         force_sync = fsfilt_add_journal_cb(exp->exp_obd,
172                                                            last_rcvd,
173                                                            oti->oti_handle,
174                                                            filter_commit_cb,
175                                                            exp);
176
177                 err = fsfilt_write_record(exp->exp_obd, filter->fo_rcvd_filp,
178                                           lcd, sizeof(*lcd), &off,
179                                           force_sync | exp->exp_need_sync);
180                 if (force_sync)
181                         filter_commit_cb(exp->exp_obd, last_rcvd, exp, err);
182         }
183         if (err) {
184                 log_pri = D_ERROR;
185                 if (rc == 0)
186                         rc = err;
187         }
188
189         CDEBUG(log_pri, "wrote trans "LPU64" for client %s at #%d: err = %d\n",
190                last_rcvd, lcd->lcd_uuid, fed->fed_lr_idx, err);
191
192         RETURN(rc);
193 }
194
195 void f_dput(struct dentry *dentry)
196 {
197         /* Can't go inside filter_ddelete because it can block */
198         CDEBUG(D_INODE, "putting %s: %p, count = %d\n",
199                dentry->d_name.name, dentry, atomic_read(&dentry->d_count) - 1);
200         LASSERT(atomic_read(&dentry->d_count) > 0);
201
202         dput(dentry);
203 }
204
205 static void init_brw_stats(struct brw_stats *brw_stats)
206 {
207         int i;
208         for (i = 0; i < BRW_LAST; i++)
209                 spin_lock_init(&brw_stats->hist[i].oh_lock);
210 }
211
212 static int lprocfs_init_rw_stats(struct obd_device *obd,
213                                  struct lprocfs_stats **stats)
214 {
215         int num_stats;
216
217         num_stats = (sizeof(*obd->obd_type->typ_ops) / sizeof(void *)) +
218                                                         LPROC_FILTER_LAST - 1;
219         *stats = lprocfs_alloc_stats(num_stats, LPROCFS_STATS_FLAG_NOPERCPU);
220         if (*stats == NULL)
221                 return -ENOMEM;
222
223         lprocfs_init_ops_stats(LPROC_FILTER_LAST, *stats);
224         lprocfs_counter_init(*stats, LPROC_FILTER_READ_BYTES,
225                              LPROCFS_CNTR_AVGMINMAX, "read_bytes", "bytes");
226         lprocfs_counter_init(*stats, LPROC_FILTER_WRITE_BYTES,
227                              LPROCFS_CNTR_AVGMINMAX, "write_bytes", "bytes");
228
229         return(0);
230 }
231
232 /* brw_stats are 2128, ops are 3916, ldlm are 204, so 6248 bytes per client,
233    plus the procfs overhead :( */
234 static int filter_export_stats_init(struct obd_device *obd,
235                                     struct obd_export *exp,
236                                     int reconnect,
237                                     void *client_nid)
238 {
239         struct proc_dir_entry *brw_entry;
240         int rc, newnid = 0;
241         ENTRY;
242
243         if (obd_uuid_equals(&exp->exp_client_uuid, &obd->obd_uuid))
244                 /* Self-export gets no proc entry */
245                 RETURN(0);
246         rc = lprocfs_exp_setup(exp, (lnet_nid_t *)client_nid,
247                                reconnect, &newnid);
248         if (rc) {
249                 /* Mask error for already created
250                  * /proc entries */
251                 if (rc == -EALREADY)
252                         rc = 0;
253
254                 RETURN(rc);
255         }
256
257         if (newnid) {
258                 struct nid_stat *tmp = exp->exp_nid_stats;
259                 LASSERT(tmp != NULL);
260
261                 OBD_ALLOC(tmp->nid_brw_stats, sizeof(struct brw_stats));
262                 if (tmp->nid_brw_stats == NULL)
263                         RETURN(-ENOMEM);
264
265                 init_brw_stats(tmp->nid_brw_stats);
266
267                 brw_entry = create_proc_entry("brw_stats", 0644,
268                                               exp->exp_nid_stats->nid_proc);
269                 if (brw_entry == NULL)
270                        RETURN(-ENOMEM);
271
272                 brw_entry->proc_fops = &filter_per_nid_stats_fops;
273                 brw_entry->data = exp->exp_nid_stats;
274
275                 rc = lprocfs_init_rw_stats(obd, &exp->exp_nid_stats->nid_stats);
276                 if (rc)
277                         RETURN(rc);
278
279                 rc = lprocfs_register_stats(tmp->nid_proc, "stats",
280                                             tmp->nid_stats);
281                 if (rc)
282                         RETURN(rc);
283
284                 /* Always add in ldlm_stats */
285                 tmp->nid_ldlm_stats =
286                         lprocfs_alloc_stats(LDLM_LAST_OPC - LDLM_FIRST_OPC,
287                                             LPROCFS_STATS_FLAG_NOPERCPU);
288                 if (tmp->nid_ldlm_stats == NULL)
289                         return -ENOMEM;
290
291                 lprocfs_init_ldlm_stats(tmp->nid_ldlm_stats);
292
293                 rc = lprocfs_register_stats(tmp->nid_proc, "ldlm_stats",
294                                             tmp->nid_ldlm_stats);
295         }
296
297         RETURN(0);
298 }
299
300 /* VBR: to determine the delayed client the lcd should be updated for each new
301  * epoch */
302 static int filter_update_client_epoch(struct obd_export *exp)
303 {
304         struct filter_export_data *fed = &exp->exp_filter_data;
305         struct filter_obd *filter = &exp->exp_obd->u.filter;
306         struct lvfs_run_ctxt saved;
307         loff_t off = fed->fed_lr_off;
308         int rc = 0;
309
310         /* VBR: set client last_epoch to current epoch */
311         if (le32_to_cpu(fed->fed_lcd->lcd_last_epoch) >=
312                         le32_to_cpu(filter->fo_fsd->lsd_start_epoch))
313                 return rc;
314         fed->fed_lcd->lcd_last_epoch = filter->fo_fsd->lsd_start_epoch;
315         push_ctxt(&saved, &exp->exp_obd->obd_lvfs_ctxt, NULL);
316         rc = fsfilt_write_record(exp->exp_obd, filter->fo_rcvd_filp,
317                                  fed->fed_lcd, sizeof(*fed->fed_lcd), &off,
318                                  exp->exp_delayed);
319         pop_ctxt(&saved, &exp->exp_obd->obd_lvfs_ctxt, NULL);
320
321         CDEBUG(D_INFO, "update client idx %u last_epoch %#x (%#x)\n",
322                fed->fed_lr_idx, le32_to_cpu(fed->fed_lcd->lcd_last_epoch),
323                le32_to_cpu(filter->fo_fsd->lsd_start_epoch));
324
325         return rc;
326 }
327
328 /* Called after recovery is done on server */
329 static void filter_update_last_epoch(struct obd_device *obd)
330 {
331         struct ptlrpc_request *req;
332         struct filter_obd *filter = &obd->u.filter;
333         struct lr_server_data *fsd = filter->fo_fsd;
334         __u32 start_epoch;
335
336         /* Increase server epoch after recovery */
337         spin_lock(&filter->fo_translock);
338         /* VBR: increase the epoch and store it in lsd */
339         start_epoch = lr_epoch(le64_to_cpu(fsd->lsd_last_transno)) + 1;
340         fsd->lsd_last_transno = cpu_to_le64((__u64)start_epoch << LR_EPOCH_BITS);
341         fsd->lsd_start_epoch = cpu_to_le32(start_epoch);
342         spin_unlock(&filter->fo_translock);
343
344         /* go through delayed reply queue to find all exports participate in
345          * recovery and set new epoch for them */
346         list_for_each_entry(req, &obd->obd_delayed_reply_queue, rq_list) {
347                 LASSERT(!req->rq_export->exp_delayed);
348                 filter_update_client_epoch(req->rq_export);
349         }
350         filter_update_server_data(obd, filter->fo_rcvd_filp, fsd, 1);
351 }
352
353 static int filter_postrecov(struct obd_device *obd)
354 {
355         ENTRY;
356
357         if (obd->obd_fail)
358                 RETURN(0);
359
360         LASSERT(!obd->obd_recovering);
361         /* VBR: update start_epoch on server */
362         filter_update_last_epoch(obd);
363
364         RETURN(0);
365 }
366
367 /* Add client data to the FILTER.  We use a bitmap to locate a free space
368  * in the last_rcvd file if cl_idx is -1 (i.e. a new client).
369  * Otherwise, we have just read the data from the last_rcvd file and
370  * we know its offset. */
371 static int filter_client_add(struct obd_device *obd, struct obd_export *exp,
372                              int cl_idx)
373 {
374         struct filter_obd *filter = &obd->u.filter;
375         struct filter_export_data *fed = &exp->exp_filter_data;
376         unsigned long *bitmap = filter->fo_last_rcvd_slots;
377         int new_client = (cl_idx == -1);
378
379         ENTRY;
380
381         LASSERT(bitmap != NULL);
382         LASSERTF(cl_idx > -2, "%d\n", cl_idx);
383
384         /* Self-export */
385         if (strcmp(fed->fed_lcd->lcd_uuid, obd->obd_uuid.uuid) == 0)
386                 RETURN(0);
387
388         /* VBR: remove expired exports before searching for free slot */
389         if (new_client)
390                 class_disconnect_expired_exports(obd);
391
392         /* the bitmap operations can handle cl_idx > sizeof(long) * 8, so
393          * there's no need for extra complication here
394          */
395         if (new_client) {
396                 cl_idx = find_first_zero_bit(bitmap, LR_MAX_CLIENTS);
397         repeat:
398                 if (cl_idx >= LR_MAX_CLIENTS) {
399                         CERROR("no room for %u clients - fix LR_MAX_CLIENTS\n",
400                                cl_idx);
401                         RETURN(-EOVERFLOW);
402                 }
403                 if (test_and_set_bit(cl_idx, bitmap)) {
404                         cl_idx = find_next_zero_bit(bitmap, LR_MAX_CLIENTS,
405                                                     cl_idx);
406                         goto repeat;
407                 }
408         } else {
409                 if (test_and_set_bit(cl_idx, bitmap)) {
410                         CERROR("FILTER client %d: bit already set in bitmap!\n",
411                                cl_idx);
412                         LBUG();
413                 }
414         }
415
416         fed->fed_lr_idx = cl_idx;
417         fed->fed_lr_off = le32_to_cpu(filter->fo_fsd->lsd_client_start) +
418                 cl_idx * le16_to_cpu(filter->fo_fsd->lsd_client_size);
419         LASSERTF(fed->fed_lr_off > 0, "fed_lr_off = %llu\n", fed->fed_lr_off);
420
421         CDEBUG(D_INFO, "client at index %d (%llu) with UUID '%s' added\n",
422                fed->fed_lr_idx, fed->fed_lr_off, fed->fed_lcd->lcd_uuid);
423
424         if (new_client) {
425                 struct lvfs_run_ctxt saved;
426                 loff_t off = fed->fed_lr_off;
427                 void *handle;
428                 int rc;
429
430                 CDEBUG(D_INFO, "writing client lcd at idx %u (%llu) (len %u)\n",
431                        fed->fed_lr_idx,off,(unsigned int)sizeof(*fed->fed_lcd));
432
433                 push_ctxt(&saved, &obd->obd_lvfs_ctxt, NULL);
434                 /* Transaction needed to fix bug 1403 */
435                 handle = fsfilt_start(obd,
436                                       filter->fo_rcvd_filp->f_dentry->d_inode,
437                                       FSFILT_OP_SETATTR, NULL);
438                 if (IS_ERR(handle)) {
439                         rc = PTR_ERR(handle);
440                         CERROR("unable to start transaction: rc %d\n", rc);
441                 } else {
442                         fed->fed_lcd->lcd_last_epoch =
443                                               filter->fo_fsd->lsd_start_epoch;
444                         exp->exp_last_request_time = cfs_time_current_sec();
445                         rc = fsfilt_add_journal_cb(obd, 0, handle,
446                                                    target_client_add_cb, exp);
447                         if (rc == 0) {
448                                 spin_lock(&exp->exp_lock);
449                                 exp->exp_need_sync = 1;
450                                 spin_unlock(&exp->exp_lock);
451                         }
452                         rc = fsfilt_write_record(obd, filter->fo_rcvd_filp,
453                                                  fed->fed_lcd,
454                                                  sizeof(*fed->fed_lcd),
455                                                  &off, rc /* sync if no cb */);
456                         fsfilt_commit(obd,
457                                       filter->fo_rcvd_filp->f_dentry->d_inode,
458                                       handle, 0);
459                 }
460                 pop_ctxt(&saved, &obd->obd_lvfs_ctxt, NULL);
461
462                 if (rc) {
463                         CERROR("error writing %s client idx %u: rc %d\n",
464                                LAST_RCVD, fed->fed_lr_idx, rc);
465                         RETURN(rc);
466                 }
467         }
468         RETURN(0);
469 }
470
471 struct lsd_client_data zero_lcd; /* globals are implicitly zeroed */
472
473 static int filter_client_free(struct obd_export *exp)
474 {
475         struct filter_export_data *fed = &exp->exp_filter_data;
476         struct filter_obd *filter = &exp->exp_obd->u.filter;
477         struct obd_device *obd = exp->exp_obd;
478         struct lvfs_run_ctxt saved;
479         int rc;
480         loff_t off;
481         ENTRY;
482
483         if (fed->fed_lcd == NULL)
484                 RETURN(0);
485
486         /* XXX if lcd_uuid were a real obd_uuid, I could use obd_uuid_equals */
487         if (strcmp(fed->fed_lcd->lcd_uuid, obd->obd_uuid.uuid ) == 0)
488                 GOTO(free, 0);
489
490         LASSERT(filter->fo_last_rcvd_slots != NULL);
491
492         off = fed->fed_lr_off;
493
494         CDEBUG(D_INFO, "freeing client at idx %u, offset %lld with UUID '%s'\n",
495                fed->fed_lr_idx, fed->fed_lr_off, fed->fed_lcd->lcd_uuid);
496
497         /* Don't clear fed_lr_idx here as it is likely also unset.  At worst
498          * we leak a client slot that will be cleaned on the next recovery. */
499         if (off <= 0) {
500                 CERROR("%s: client idx %d has med_off %lld\n",
501                        obd->obd_name, fed->fed_lr_idx, off);
502                 GOTO(free, rc = -EINVAL);
503         }
504
505         /* Clear the bit _after_ zeroing out the client so we don't
506            race with filter_client_add and zero out new clients.*/
507         if (!test_bit(fed->fed_lr_idx, filter->fo_last_rcvd_slots)) {
508                 CERROR("FILTER client %u: bit already clear in bitmap!!\n",
509                        fed->fed_lr_idx);
510                 LBUG();
511         }
512
513         if (!(exp->exp_flags & OBD_OPT_FAILOVER)) {
514                 /* Don't force sync on disconnect if aborting recovery,
515                  * or it does num_clients * num_osts.  b=17194 */
516                 int need_sync = exp->exp_need_sync &&
517                                 !(exp->exp_flags&OBD_OPT_ABORT_RECOV);
518
519                 push_ctxt(&saved, &obd->obd_lvfs_ctxt, NULL);
520                 rc = fsfilt_write_record(obd, filter->fo_rcvd_filp, &zero_lcd,
521                                          sizeof(zero_lcd), &off, 0);
522
523                 /* Make sure the server's last_transno is up to date. Do this
524                  * after the client is freed so we know all the client's
525                  * transactions have been committed. */
526                 if (rc == 0)
527                         filter_update_server_data(obd, filter->fo_rcvd_filp,
528                                                   filter->fo_fsd, need_sync);
529                 pop_ctxt(&saved, &obd->obd_lvfs_ctxt, NULL);
530
531                 CDEBUG(rc == 0 ? D_INFO : D_ERROR,
532                        "zero out client %s at idx %u/%llu in %s %ssync rc %d\n",
533                        fed->fed_lcd->lcd_uuid, fed->fed_lr_idx, fed->fed_lr_off,
534                        LAST_RCVD, need_sync ? "" : "a", rc);
535         }
536
537         if (!test_and_clear_bit(fed->fed_lr_idx, filter->fo_last_rcvd_slots)) {
538                 CERROR("FILTER client %u: bit already clear in bitmap!!\n",
539                        fed->fed_lr_idx);
540                 LBUG();
541         }
542
543         EXIT;
544 free:
545         OBD_FREE_PTR(fed->fed_lcd);
546         fed->fed_lcd = NULL;
547
548         return 0;
549 }
550
551 /* drop fmd reference, free it if last ref. must be called with fed_lock held.*/
552 static inline void filter_fmd_put_nolock(struct filter_export_data *fed,
553                                          struct filter_mod_data *fmd)
554 {
555         LASSERT_SPIN_LOCKED(&fed->fed_lock);
556         if (--fmd->fmd_refcount == 0) {
557                 /* XXX when we have persistent reservations and the handle
558                  * is stored herein we need to drop it here. */
559                 fed->fed_mod_count--;
560                 list_del(&fmd->fmd_list);
561                 OBD_SLAB_FREE(fmd, ll_fmd_cachep, sizeof(*fmd));
562         }
563 }
564
565 /* drop fmd reference, free it if last ref */
566 void filter_fmd_put(struct obd_export *exp, struct filter_mod_data *fmd)
567 {
568         struct filter_export_data *fed;
569
570         if (fmd == NULL)
571                 return;
572
573         fed = &exp->exp_filter_data;
574         spin_lock(&fed->fed_lock);
575         filter_fmd_put_nolock(fed, fmd); /* caller reference */
576         spin_unlock(&fed->fed_lock);
577 }
578
579 /* expire entries from the end of the list if there are too many
580  * or they are too old */
581 static void filter_fmd_expire_nolock(struct filter_obd *filter,
582                                      struct filter_export_data *fed,
583                                      struct filter_mod_data *keep)
584 {
585         struct filter_mod_data *fmd, *tmp;
586
587         list_for_each_entry_safe(fmd, tmp, &fed->fed_mod_list, fmd_list) {
588                 if (fmd == keep)
589                         break;
590
591                 if (time_before(jiffies, fmd->fmd_expire) &&
592                     fed->fed_mod_count < filter->fo_fmd_max_num)
593                         break;
594
595                 list_del_init(&fmd->fmd_list);
596                 filter_fmd_put_nolock(fed, fmd); /* list reference */
597         }
598 }
599
600 void filter_fmd_expire(struct obd_export *exp)
601 {
602         spin_lock(&exp->exp_filter_data.fed_lock);
603         filter_fmd_expire_nolock(&exp->exp_obd->u.filter,
604                                  &exp->exp_filter_data, NULL);
605         spin_unlock(&exp->exp_filter_data.fed_lock);
606 }
607
608 /* find specified objid, group in export fmd list.
609  * caller must hold fed_lock and take fmd reference itself */
610 static struct filter_mod_data *filter_fmd_find_nolock(struct filter_obd *filter,
611                                                 struct filter_export_data *fed,
612                                                 obd_id objid, obd_gr group)
613 {
614         struct filter_mod_data *found = NULL, *fmd;
615
616         LASSERT_SPIN_LOCKED(&fed->fed_lock);
617
618         list_for_each_entry_reverse(fmd, &fed->fed_mod_list, fmd_list) {
619                 if (fmd->fmd_id == objid && fmd->fmd_gr == group) {
620                         found = fmd;
621                         list_del(&fmd->fmd_list);
622                         list_add_tail(&fmd->fmd_list, &fed->fed_mod_list);
623                         fmd->fmd_expire = jiffies + filter->fo_fmd_max_age;
624                         break;
625                 }
626         }
627
628         filter_fmd_expire_nolock(filter, fed, found);
629
630         return found;
631 }
632
633 /* Find fmd based on objid and group, or return NULL if not found. */
634 struct filter_mod_data *filter_fmd_find(struct obd_export *exp,
635                                         obd_id objid, obd_gr group)
636 {
637         struct filter_mod_data *fmd;
638
639         spin_lock(&exp->exp_filter_data.fed_lock);
640         fmd = filter_fmd_find_nolock(&exp->exp_obd->u.filter,
641                                      &exp->exp_filter_data, objid, group);
642         if (fmd)
643                 fmd->fmd_refcount++;    /* caller reference */
644         spin_unlock(&exp->exp_filter_data.fed_lock);
645
646         return fmd;
647 }
648
649 /* Find fmd based on objid and group, or create a new one if none is found.
650  * It is possible for this function to return NULL under memory pressure,
651  * or if objid = 0 is passed (which will only cause old entries to expire).
652  * Currently this is not fatal because any fmd state is transient and
653  * may also be freed when it gets sufficiently old. */
654 struct filter_mod_data *filter_fmd_get(struct obd_export *exp,
655                                        obd_id objid, obd_gr group)
656 {
657         struct filter_export_data *fed = &exp->exp_filter_data;
658         struct filter_mod_data *found = NULL, *fmd_new = NULL;
659
660         OBD_SLAB_ALLOC(fmd_new, ll_fmd_cachep, CFS_ALLOC_IO, sizeof(*fmd_new));
661
662         spin_lock(&fed->fed_lock);
663         found = filter_fmd_find_nolock(&exp->exp_obd->u.filter,fed,objid,group);
664         if (fmd_new) {
665                 if (found == NULL) {
666                         list_add_tail(&fmd_new->fmd_list, &fed->fed_mod_list);
667                         fmd_new->fmd_id = objid;
668                         fmd_new->fmd_gr = group;
669                         fmd_new->fmd_refcount++;   /* list reference */
670                         found = fmd_new;
671                         fed->fed_mod_count++;
672                 } else {
673                         OBD_SLAB_FREE(fmd_new, ll_fmd_cachep, sizeof(*fmd_new));
674                 }
675         }
676         if (found) {
677                 found->fmd_refcount++;          /* caller reference */
678                 found->fmd_expire = jiffies +
679                         exp->exp_obd->u.filter.fo_fmd_max_age;
680         }
681
682         spin_unlock(&fed->fed_lock);
683
684         return found;
685 }
686
687 #ifdef DO_FMD_DROP
688 /* drop fmd list reference so it will disappear when last reference is put.
689  * This isn't so critical because it would in fact only affect the one client
690  * that is doing the unlink and at worst we have an stale entry referencing
691  * an object that should never be used again. */
692 static void filter_fmd_drop(struct obd_export *exp, obd_id objid, obd_gr group)
693 {
694         struct filter_mod_data *found = NULL;
695
696         spin_lock(&exp->exp_filter_data.fed_lock);
697         found = filter_fmd_find_nolock(&exp->exp_filter_data, objid, group);
698         if (found) {
699                 list_del_init(&found->fmd_list);
700                 filter_fmd_put_nolock(&exp->exp_filter_data, found);
701         }
702         spin_unlock(&exp->exp_filter_data.fed_lock);
703 }
704 #else
705 #define filter_fmd_drop(exp, objid, group)
706 #endif
707
708 /* remove all entries from fmd list */
709 static void filter_fmd_cleanup(struct obd_export *exp)
710 {
711         struct filter_export_data *fed = &exp->exp_filter_data;
712         struct filter_mod_data *fmd = NULL, *tmp;
713
714         spin_lock(&fed->fed_lock);
715         list_for_each_entry_safe(fmd, tmp, &fed->fed_mod_list, fmd_list) {
716                 list_del_init(&fmd->fmd_list);
717                 filter_fmd_put_nolock(fed, fmd);
718         }
719         spin_unlock(&fed->fed_lock);
720 }
721
722 static int filter_init_export(struct obd_export *exp)
723 {
724         spin_lock_init(&exp->exp_filter_data.fed_lock);
725         INIT_LIST_HEAD(&exp->exp_filter_data.fed_mod_list);
726
727         spin_lock(&exp->exp_lock);
728         exp->exp_connecting = 1;
729         spin_unlock(&exp->exp_lock);
730
731         return ldlm_init_export(exp);
732 }
733
734 static int filter_free_server_data(struct filter_obd *filter)
735 {
736         OBD_FREE(filter->fo_fsd, sizeof(*filter->fo_fsd));
737         filter->fo_fsd = NULL;
738         OBD_FREE(filter->fo_last_rcvd_slots, LR_MAX_CLIENTS / 8);
739         filter->fo_last_rcvd_slots = NULL;
740         return 0;
741 }
742
743 /* assumes caller is already in kernel ctxt */
744 int filter_update_server_data(struct obd_device *obd, struct file *filp,
745                               struct lr_server_data *fsd, int force_sync)
746 {
747         loff_t off = 0;
748         int rc;
749         ENTRY;
750
751         CDEBUG(D_INODE, "server uuid      : %s\n", fsd->lsd_uuid);
752         CDEBUG(D_INODE, "server last_rcvd : "LPU64"\n",
753                le64_to_cpu(fsd->lsd_last_transno));
754         CDEBUG(D_INODE, "server last_mount: "LPU64"\n",
755                le64_to_cpu(fsd->lsd_mount_count));
756
757         fsd->lsd_compat14 = fsd->lsd_last_transno;
758         rc = fsfilt_write_record(obd, filp, fsd, sizeof(*fsd), &off,force_sync);
759         if (rc)
760                 CERROR("error writing lr_server_data: rc = %d\n", rc);
761
762         RETURN(rc);
763 }
764
765 int filter_update_last_objid(struct obd_device *obd, obd_gr group,
766                              int force_sync)
767 {
768         struct filter_obd *filter = &obd->u.filter;
769         __u64 tmp;
770         loff_t off = 0;
771         int rc;
772         ENTRY;
773
774         if (filter->fo_last_objid_files[group] == NULL) {
775                 CERROR("Object group "LPU64" not fully setup; not updating "
776                        "last_objid\n", group);
777                 RETURN(-EINVAL);
778         }
779
780         CDEBUG(D_INODE, "%s: server last_objid for group "LPU64": "LPU64"\n",
781                obd->obd_name, group, filter->fo_last_objids[group]);
782
783         tmp = cpu_to_le64(filter->fo_last_objids[group]);
784         rc = fsfilt_write_record(obd, filter->fo_last_objid_files[group],
785                                  &tmp, sizeof(tmp), &off, force_sync);
786         if (rc)
787                 CERROR("error writing group "LPU64" last objid: rc = %d\n",
788                        group, rc);
789         RETURN(rc);
790 }
791
792 /* assumes caller has already in kernel ctxt */
793 static int filter_init_server_data(struct obd_device *obd, struct file * filp)
794 {
795         struct filter_obd *filter = &obd->u.filter;
796         struct lr_server_data *fsd;
797         struct lsd_client_data *lcd = NULL;
798         struct inode *inode = filp->f_dentry->d_inode;
799         unsigned long last_rcvd_size = i_size_read(inode);
800         struct lustre_mount_info *lmi;
801         __u64 mount_count;
802         __u32 start_epoch;
803         int cl_idx;
804         loff_t off = 0;
805         int rc;
806
807         /* ensure padding in the struct is the correct size */
808         CLASSERT (offsetof(struct lr_server_data, lsd_padding) +
809                  sizeof(fsd->lsd_padding) == LR_SERVER_SIZE);
810         CLASSERT (offsetof(struct lsd_client_data, lcd_padding) +
811                  sizeof(lcd->lcd_padding) == LR_CLIENT_SIZE);
812
813         OBD_ALLOC(fsd, sizeof(*fsd));
814         if (!fsd)
815                 RETURN(-ENOMEM);
816         filter->fo_fsd = fsd;
817
818         OBD_ALLOC(filter->fo_last_rcvd_slots, LR_MAX_CLIENTS / 8);
819         if (filter->fo_last_rcvd_slots == NULL) {
820                 OBD_FREE(fsd, sizeof(*fsd));
821                 RETURN(-ENOMEM);
822         }
823
824         if (last_rcvd_size == 0) {
825                 LCONSOLE_WARN("%s: new disk, initializing\n", obd->obd_name);
826
827                 memcpy(fsd->lsd_uuid, obd->obd_uuid.uuid,sizeof(fsd->lsd_uuid));
828                 fsd->lsd_last_transno = 0;
829                 mount_count = fsd->lsd_mount_count = 0;
830                 fsd->lsd_server_size = cpu_to_le32(LR_SERVER_SIZE);
831                 fsd->lsd_client_start = cpu_to_le32(LR_CLIENT_START);
832                 fsd->lsd_client_size = cpu_to_le16(LR_CLIENT_SIZE);
833                 fsd->lsd_subdir_count = cpu_to_le16(FILTER_SUBDIR_COUNT);
834                 filter->fo_subdir_count = FILTER_SUBDIR_COUNT;
835                 fsd->lsd_feature_incompat = cpu_to_le32(OBD_INCOMPAT_OST);
836         } else {
837                 rc = fsfilt_read_record(obd, filp, fsd, sizeof(*fsd), &off);
838                 if (rc) {
839                         CDEBUG(D_INODE,"OBD filter: error reading %s: rc %d\n",
840                                LAST_RCVD, rc);
841                         GOTO(err_fsd, rc);
842                 }
843                 if (strcmp(fsd->lsd_uuid, obd->obd_uuid.uuid) != 0) {
844                         LCONSOLE_ERROR_MSG(0x134, "Trying to start OBD %s using"
845                                            " the wrong disk %s. Were the /dev/ "
846                                            "assignments rearranged?\n",
847                                            obd->obd_uuid.uuid, fsd->lsd_uuid);
848                         GOTO(err_fsd, rc = -EINVAL);
849                 }
850                 mount_count = le64_to_cpu(fsd->lsd_mount_count);
851                 filter->fo_subdir_count = le16_to_cpu(fsd->lsd_subdir_count);
852                 /* COMPAT_146 */
853                 /* Assume old last_rcvd format unless I_C_LR is set */
854                 if (!(fsd->lsd_feature_incompat &
855                       cpu_to_le32(OBD_INCOMPAT_COMMON_LR)))
856                         fsd->lsd_last_transno = fsd->lsd_compat14;
857                 /* end COMPAT_146 */
858         }
859
860         if (fsd->lsd_feature_incompat & ~cpu_to_le32(FILTER_INCOMPAT_SUPP)) {
861                 CERROR("%s: unsupported incompat filesystem feature(s) %x\n",
862                        obd->obd_name, le32_to_cpu(fsd->lsd_feature_incompat) &
863                        ~FILTER_INCOMPAT_SUPP);
864                 GOTO(err_fsd, rc = -EINVAL);
865         }
866         if (fsd->lsd_feature_rocompat & ~cpu_to_le32(FILTER_ROCOMPAT_SUPP)) {
867                 CERROR("%s: unsupported read-only filesystem feature(s) %x\n",
868                        obd->obd_name, le32_to_cpu(fsd->lsd_feature_rocompat) &
869                        ~FILTER_ROCOMPAT_SUPP);
870                 /* Do something like remount filesystem read-only */
871                 GOTO(err_fsd, rc = -EINVAL);
872         }
873
874         target_trans_table_init(obd);
875         start_epoch = le32_to_cpu(fsd->lsd_start_epoch);
876
877         CDEBUG(D_INODE, "%s: server start_epoch : %#x\n",
878                obd->obd_name, start_epoch);
879         CDEBUG(D_INODE, "%s: server last_transno : "LPX64"\n",
880                obd->obd_name, le64_to_cpu(fsd->lsd_last_transno));
881         CDEBUG(D_INODE, "%s: server mount_count: "LPU64"\n",
882                obd->obd_name, mount_count + 1);
883         CDEBUG(D_INODE, "%s: server data size: %u\n",
884                obd->obd_name, le32_to_cpu(fsd->lsd_server_size));
885         CDEBUG(D_INODE, "%s: per-client data start: %u\n",
886                obd->obd_name, le32_to_cpu(fsd->lsd_client_start));
887         CDEBUG(D_INODE, "%s: per-client data size: %u\n",
888                obd->obd_name, le32_to_cpu(fsd->lsd_client_size));
889         CDEBUG(D_INODE, "%s: server subdir_count: %u\n",
890                obd->obd_name, le16_to_cpu(fsd->lsd_subdir_count));
891         CDEBUG(D_INODE, "%s: last_rcvd clients: %lu\n", obd->obd_name,
892                last_rcvd_size <= le32_to_cpu(fsd->lsd_client_start) ? 0 :
893                (last_rcvd_size - le32_to_cpu(fsd->lsd_client_start)) /
894                 le16_to_cpu(fsd->lsd_client_size));
895
896         if (!obd->obd_replayable) {
897                 CWARN("%s: recovery support OFF\n", obd->obd_name);
898                 GOTO(out, rc = 0);
899         }
900
901         for (cl_idx = 0, off = le32_to_cpu(fsd->lsd_client_start);
902              off < last_rcvd_size; cl_idx++) {
903                 __u64 last_rcvd;
904                 struct obd_export *exp;
905                 struct filter_export_data *fed;
906
907                 if (!lcd) {
908                         OBD_ALLOC_PTR(lcd);
909                         if (!lcd)
910                                 GOTO(err_client, rc = -ENOMEM);
911                 }
912
913                 /* Don't assume off is incremented properly by
914                  * fsfilt_read_record(), in case sizeof(*lcd)
915                  * isn't the same as fsd->lsd_client_size.  */
916                 off = le32_to_cpu(fsd->lsd_client_start) +
917                         cl_idx * le16_to_cpu(fsd->lsd_client_size);
918                 rc = fsfilt_read_record(obd, filp, lcd, sizeof(*lcd), &off);
919                 if (rc) {
920                         CERROR("error reading FILT %s idx %d off %llu: rc %d\n",
921                                LAST_RCVD, cl_idx, off, rc);
922                         break; /* read error shouldn't cause startup to fail */
923                 }
924
925                 if (lcd->lcd_uuid[0] == '\0') {
926                         CDEBUG(D_INFO, "skipping zeroed client at offset %d\n",
927                                cl_idx);
928                         continue;
929                 }
930
931                 check_lcd(obd->obd_name, cl_idx, lcd);
932
933                 last_rcvd = le64_to_cpu(lcd->lcd_last_transno);
934
935                 /* These exports are cleaned up by filter_disconnect(), so they
936                  * need to be set up like real exports as filter_connect() does.
937                  */
938                 exp = class_new_export(obd, (struct obd_uuid *)lcd->lcd_uuid);
939                 CDEBUG(D_HA, "RCVRNG CLIENT uuid: %s idx: %d lr: "LPU64
940                        " srv lr: "LPU64"\n", lcd->lcd_uuid, cl_idx,
941                        last_rcvd, le64_to_cpu(fsd->lsd_last_transno));
942                 if (IS_ERR(exp)) {
943                         if (PTR_ERR(exp) == -EALREADY) {
944                                 /* export already exists, zero out this one */
945                                 CERROR("Zeroing out duplicate export due to "
946                                        "bug 10479.\n");
947                                 lcd->lcd_uuid[0] = '\0';
948                         } else {
949                                 GOTO(err_client, rc = PTR_ERR(exp));
950                         }
951                 } else {
952                         fed = &exp->exp_filter_data;
953                         fed->fed_lcd = lcd;
954                         filter_export_stats_init(obd, exp, 0, NULL);
955                         rc = filter_client_add(obd, exp, cl_idx);
956                         /* can't fail for existing client */
957                         LASSERTF(rc == 0, "rc = %d\n", rc);
958
959                         /* VBR: set export last committed */
960                         exp->exp_last_committed = last_rcvd;
961                         /* read last time from disk */
962                         exp->exp_last_request_time = target_trans_table_last_time(exp);
963
964                         spin_lock(&exp->exp_lock);
965                         exp->exp_replay_needed = 1;
966                         exp->exp_connecting = 0;
967                         exp->exp_in_recovery = 0;
968                         spin_unlock(&exp->exp_lock);
969
970                         spin_lock_bh(&obd->obd_processing_task_lock);
971                         obd->obd_recoverable_clients++;
972                         obd->obd_max_recoverable_clients++;
973                         spin_unlock_bh(&obd->obd_processing_task_lock);
974
975                         /* VBR: if epoch too old mark export as delayed,
976                          * if epoch is zero then client is pre-vbr one */
977                         if (start_epoch > le32_to_cpu(lcd->lcd_last_epoch) &&
978                             le32_to_cpu(lcd->lcd_last_epoch) != 0)
979                                 class_set_export_delayed(exp);
980
981                         lcd = NULL;
982                         class_export_put(exp);
983                 }
984
985                 /* Need to check last_rcvd even for duplicated exports. */
986                 CDEBUG(D_OTHER, "client at idx %d has last_rcvd = "LPX64"\n",
987                        cl_idx, last_rcvd);
988
989                 if (last_rcvd > le64_to_cpu(fsd->lsd_last_transno))
990                         fsd->lsd_last_transno = cpu_to_le64(last_rcvd);
991         }
992
993         if (lcd)
994                 OBD_FREE_PTR(lcd);
995
996         obd->obd_last_committed = le64_to_cpu(fsd->lsd_last_transno);
997
998         if (obd->obd_recoverable_clients) {
999                 CWARN("RECOVERY: service %s, %d recoverable clients, "
1000                       "%d delayed clients, last_rcvd "LPU64"\n",
1001                       obd->obd_name, obd->obd_recoverable_clients,
1002                       obd->obd_delayed_clients,
1003                       le64_to_cpu(fsd->lsd_last_transno));
1004                 obd->obd_next_recovery_transno = obd->obd_last_committed + 1;
1005                 obd->obd_recovering = 1;
1006                 obd->obd_recovery_start = 0;
1007                 obd->obd_recovery_end = 0;
1008         } else {
1009                 LASSERT(!obd->obd_recovering);
1010                 /* VBR: update boot epoch after recovery */
1011                 filter_update_last_epoch(obd);
1012         }
1013
1014         obd->obd_recovery_timeout = OBD_RECOVERY_TIME_SOFT;
1015         obd->obd_recovery_time_hard = OBD_RECOVERY_TIME_HARD;
1016
1017         lmi = server_find_mount_locked(obd->obd_name);
1018         if (lmi) {
1019                 struct lustre_sb_info *lsi = s2lsi(lmi->lmi_sb);
1020
1021                 if (lsi->lsi_lmd && lsi->lsi_lmd->lmd_recovery_time_soft)
1022                         obd->obd_recovery_timeout =
1023                                 lsi->lsi_lmd->lmd_recovery_time_soft;
1024
1025                 if (lsi->lsi_lmd && lsi->lsi_lmd->lmd_recovery_time_hard)
1026                         obd->obd_recovery_time_hard =
1027                                 lsi->lsi_lmd->lmd_recovery_time_hard;
1028         }
1029
1030 out:
1031         filter->fo_mount_count = mount_count + 1;
1032         fsd->lsd_mount_count = cpu_to_le64(filter->fo_mount_count);
1033
1034         /* save it, so mount count and last_transno is current */
1035         rc = filter_update_server_data(obd, filp, filter->fo_fsd, 1);
1036         if (rc)
1037                 GOTO(err_client, rc);
1038
1039         RETURN(0);
1040
1041 err_client:
1042         class_disconnect_exports(obd);
1043 err_fsd:
1044         filter_free_server_data(filter);
1045         RETURN(rc);
1046 }
1047
1048 static int filter_cleanup_groups(struct obd_device *obd)
1049 {
1050         struct filter_obd *filter = &obd->u.filter;
1051         struct file *filp;
1052         struct dentry *dentry;
1053         int i;
1054         ENTRY;
1055
1056         if (filter->fo_dentry_O_groups != NULL) {
1057                 for (i = 0; i < FILTER_GROUPS; i++) {
1058                         dentry = filter->fo_dentry_O_groups[i];
1059                         if (dentry != NULL)
1060                                 f_dput(dentry);
1061                 }
1062                 OBD_FREE(filter->fo_dentry_O_groups,
1063                          FILTER_GROUPS * sizeof(*filter->fo_dentry_O_groups));
1064                 filter->fo_dentry_O_groups = NULL;
1065         }
1066         if (filter->fo_last_objid_files != NULL) {
1067                 for (i = 0; i < FILTER_GROUPS; i++) {
1068                         filp = filter->fo_last_objid_files[i];
1069                         if (filp != NULL)
1070                                 filp_close(filp, 0);
1071                 }
1072                 OBD_FREE(filter->fo_last_objid_files,
1073                          FILTER_GROUPS * sizeof(*filter->fo_last_objid_files));
1074                 filter->fo_last_objid_files = NULL;
1075         }
1076         if (filter->fo_dentry_O_sub != NULL) {
1077                 for (i = 0; i < filter->fo_subdir_count; i++) {
1078                         dentry = filter->fo_dentry_O_sub[i];
1079                         if (dentry != NULL)
1080                                 f_dput(dentry);
1081                 }
1082                 OBD_FREE(filter->fo_dentry_O_sub,
1083                          filter->fo_subdir_count *
1084                          sizeof(*filter->fo_dentry_O_sub));
1085                 filter->fo_dentry_O_sub = NULL;
1086         }
1087         if (filter->fo_last_objids != NULL) {
1088                 OBD_FREE(filter->fo_last_objids,
1089                          FILTER_GROUPS * sizeof(*filter->fo_last_objids));
1090                 filter->fo_last_objids = NULL;
1091         }
1092         if (filter->fo_dentry_O != NULL) {
1093                 f_dput(filter->fo_dentry_O);
1094                 filter->fo_dentry_O = NULL;
1095         }
1096         RETURN(0);
1097 }
1098
1099 /* FIXME: object groups */
1100 static int filter_prep_groups(struct obd_device *obd)
1101 {
1102         struct filter_obd *filter = &obd->u.filter;
1103         struct dentry *dentry, *O_dentry;
1104         struct file *filp;
1105         int i, rc = 0, cleanup_phase = 0;
1106         ENTRY;
1107
1108         O_dentry = simple_mkdir(cfs_fs_pwd(current->fs), filter->fo_vfsmnt,
1109                                 "O", 0700, 1);
1110         CDEBUG(D_INODE, "got/created O: %p\n", O_dentry);
1111         if (IS_ERR(O_dentry)) {
1112                 rc = PTR_ERR(O_dentry);
1113                 CERROR("cannot open/create O: rc = %d\n", rc);
1114                 GOTO(cleanup, rc);
1115         }
1116         filter->fo_dentry_O = O_dentry;
1117         cleanup_phase = 1; /* O_dentry */
1118
1119         OBD_ALLOC(filter->fo_last_objids, FILTER_GROUPS * sizeof(__u64));
1120         if (filter->fo_last_objids == NULL)
1121                 GOTO(cleanup, rc = -ENOMEM);
1122         cleanup_phase = 2; /* groups */
1123
1124         OBD_ALLOC(filter->fo_dentry_O_groups, FILTER_GROUPS * sizeof(dentry));
1125         if (filter->fo_dentry_O_groups == NULL)
1126                 GOTO(cleanup, rc = -ENOMEM);
1127         OBD_ALLOC(filter->fo_last_objid_files, FILTER_GROUPS * sizeof(filp));
1128         if (filter->fo_last_objid_files == NULL)
1129                 GOTO(cleanup, rc = -ENOMEM);
1130
1131         for (i = 0; i < FILTER_GROUPS; i++) {
1132                 char name[25];
1133                 loff_t off = 0;
1134
1135                 sprintf(name, "%d", i);
1136                 dentry = simple_mkdir(O_dentry, filter->fo_vfsmnt,
1137                                       name, 0700, 1);
1138                 CDEBUG(D_INODE, "got/created O/%s: %p\n", name, dentry);
1139                 if (IS_ERR(dentry)) {
1140                         rc = PTR_ERR(dentry);
1141                         CERROR("cannot lookup/create O/%s: rc = %d\n",
1142                                name, rc);
1143                         GOTO(cleanup, rc);
1144                 }
1145                 filter->fo_dentry_O_groups[i] = dentry;
1146
1147                 sprintf(name, "O/%d/LAST_ID", i);
1148                 filp = filp_open(name, O_CREAT | O_RDWR, 0700);
1149                 if (IS_ERR(filp)) {
1150                         rc = PTR_ERR(filp);
1151                         CERROR("cannot create %s: rc = %d\n", name, rc);
1152                         GOTO(cleanup, rc);
1153                 }
1154                 filter->fo_last_objid_files[i] = filp;
1155
1156                 if (i_size_read(filp->f_dentry->d_inode) == 0) {
1157                         filter->fo_last_objids[i] = FILTER_INIT_OBJID;
1158                         rc = filter_update_last_objid(obd, i, 1);
1159                         if (rc)
1160                                 GOTO(cleanup, rc);
1161                         continue;
1162                 }
1163
1164                 rc = fsfilt_read_record(obd, filp, &filter->fo_last_objids[i],
1165                                         sizeof(__u64), &off);
1166                 if (rc) {
1167                         CDEBUG(D_INODE,"OBD filter: error reading %s: rc %d\n",
1168                                name, rc);
1169                         GOTO(cleanup, rc);
1170                 }
1171                 filter->fo_last_objids[i] =
1172                         le64_to_cpu(filter->fo_last_objids[i]);
1173                 CDEBUG(D_HA, "%s: server last_objid group %d: "LPU64"\n",
1174                        obd->obd_name, i, filter->fo_last_objids[i]);
1175         }
1176
1177         if (filter->fo_subdir_count) {
1178                 O_dentry = filter->fo_dentry_O_groups[0];
1179                 OBD_ALLOC(filter->fo_dentry_O_sub,
1180                           filter->fo_subdir_count * sizeof(dentry));
1181                 if (filter->fo_dentry_O_sub == NULL)
1182                         GOTO(cleanup, rc = -ENOMEM);
1183
1184                 for (i = 0; i < filter->fo_subdir_count; i++) {
1185                         char dir[20];
1186                         snprintf(dir, sizeof(dir), "d%u", i);
1187
1188                         dentry = simple_mkdir(O_dentry, filter->fo_vfsmnt,
1189                                               dir, 0700, 1);
1190                         CDEBUG(D_INODE, "got/created O/0/%s: %p\n", dir,dentry);
1191                         if (IS_ERR(dentry)) {
1192                                 rc = PTR_ERR(dentry);
1193                                 CERROR("can't lookup/create O/0/%s: rc = %d\n",
1194                                        dir, rc);
1195                                 GOTO(cleanup, rc);
1196                         }
1197                         filter->fo_dentry_O_sub[i] = dentry;
1198                 }
1199         }
1200         RETURN(0);
1201
1202  cleanup:
1203         filter_cleanup_groups(obd);
1204         return rc;
1205 }
1206
1207 /* setup the object store with correct subdirectories */
1208 static int filter_prep(struct obd_device *obd)
1209 {
1210         struct lvfs_run_ctxt saved;
1211         struct filter_obd *filter = &obd->u.filter;
1212         struct file *file;
1213         struct inode *inode;
1214         int rc = 0;
1215         ENTRY;
1216
1217         push_ctxt(&saved, &obd->obd_lvfs_ctxt, NULL);
1218         file = filp_open(LAST_RCVD, O_RDWR | O_CREAT | O_LARGEFILE, 0700);
1219         if (!file || IS_ERR(file)) {
1220                 rc = PTR_ERR(file);
1221                 CERROR("OBD filter: cannot open/create %s: rc = %d\n",
1222                        LAST_RCVD, rc);
1223                 GOTO(out, rc);
1224         }
1225         filter->fo_rcvd_filp = file;
1226         if (!S_ISREG(file->f_dentry->d_inode->i_mode)) {
1227                 CERROR("%s is not a regular file!: mode = %o\n", LAST_RCVD,
1228                        file->f_dentry->d_inode->i_mode);
1229                 GOTO(err_filp, rc = -ENOENT);
1230         }
1231
1232         inode = file->f_dentry->d_parent->d_inode;
1233         /* We use i_op->unlink directly in filter_vfs_unlink() */
1234         if (!inode->i_op || !inode->i_op->create || !inode->i_op->unlink) {
1235                 CERROR("%s: filesystem does not support create/unlink ops\n",
1236                        obd->obd_name);
1237                 GOTO(err_filp, rc = -EOPNOTSUPP);
1238         }
1239
1240         rc = filter_init_server_data(obd, file);
1241         if (rc) {
1242                 CERROR("cannot read %s: rc = %d\n", LAST_RCVD, rc);
1243                 GOTO(err_filp, rc);
1244         }
1245         /* open and create health check io file*/
1246         file = filp_open(HEALTH_CHECK, O_RDWR | O_CREAT, 0644);
1247         if (IS_ERR(file)) {
1248                 rc = PTR_ERR(file);
1249                 CERROR("OBD filter: cannot open/create %s rc = %d\n",
1250                        HEALTH_CHECK, rc);
1251                 GOTO(err_filp, rc);
1252         }
1253         filter->fo_obt.obt_health_check_filp = file;
1254         if (!S_ISREG(file->f_dentry->d_inode->i_mode)) {
1255                 CERROR("%s is not a regular file!: mode = %o\n", HEALTH_CHECK,
1256                        file->f_dentry->d_inode->i_mode);
1257                 GOTO(err_health_check, rc = -ENOENT);
1258         }
1259         rc = lvfs_check_io_health(obd, file);
1260         if (rc)
1261                 GOTO(err_health_check, rc);
1262
1263         rc = filter_prep_groups(obd);
1264         if (rc)
1265                 GOTO(err_server_data, rc);
1266  out:
1267         pop_ctxt(&saved, &obd->obd_lvfs_ctxt, NULL);
1268
1269         return(rc);
1270
1271  err_server_data:
1272         //class_disconnect_exports(obd, 0);
1273         filter_free_server_data(filter);
1274  err_health_check:
1275         if (filp_close(filter->fo_obt.obt_health_check_filp, 0))
1276                 CERROR("can't close %s after error\n", HEALTH_CHECK);
1277         filter->fo_obt.obt_health_check_filp = NULL;
1278  err_filp:
1279         if (filp_close(filter->fo_rcvd_filp, 0))
1280                 CERROR("can't close %s after error\n", LAST_RCVD);
1281         filter->fo_rcvd_filp = NULL;
1282         goto out;
1283 }
1284
1285 /* cleanup the filter: write last used object id to status file */
1286 static void filter_post(struct obd_device *obd)
1287 {
1288         struct lvfs_run_ctxt saved;
1289         struct filter_obd *filter = &obd->u.filter;
1290         int rc, i;
1291
1292         /* XXX: filter_update_lastobjid used to call fsync_dev.  It might be
1293          * best to start a transaction with h_sync, because we removed this
1294          * from lastobjid */
1295
1296         push_ctxt(&saved, &obd->obd_lvfs_ctxt, NULL);
1297         rc = filter_update_server_data(obd, filter->fo_rcvd_filp,
1298                                        filter->fo_fsd, 0);
1299         if (rc)
1300                 CERROR("error writing server data: rc = %d\n", rc);
1301
1302         for (i = 0; i < FILTER_GROUPS; i++) {
1303                 rc = filter_update_last_objid(obd, i, (i == FILTER_GROUPS - 1));
1304                 if (rc)
1305                         CERROR("error writing group %d lastobjid: rc = %d\n",
1306                                i, rc);
1307         }
1308
1309         rc = filp_close(filter->fo_rcvd_filp, 0);
1310         filter->fo_rcvd_filp = NULL;
1311         if (rc)
1312                 CERROR("error closing %s: rc = %d\n", LAST_RCVD, rc);
1313
1314         rc = filp_close(filter->fo_obt.obt_health_check_filp, 0);
1315         filter->fo_obt.obt_health_check_filp = NULL;
1316         if (rc)
1317                 CERROR("error closing %s: rc = %d\n", HEALTH_CHECK, rc);
1318
1319         filter_cleanup_groups(obd);
1320         filter_free_server_data(filter);
1321         pop_ctxt(&saved, &obd->obd_lvfs_ctxt, NULL);
1322 }
1323
1324 static void filter_set_last_id(struct filter_obd *filter,
1325                                obd_id id, obd_gr group)
1326 {
1327         LASSERT(filter->fo_fsd != NULL);
1328         LASSERT(group <= FILTER_GROUPS);
1329
1330         spin_lock(&filter->fo_objidlock);
1331         filter->fo_last_objids[group] = id;
1332         spin_unlock(&filter->fo_objidlock);
1333 }
1334
1335 obd_id filter_last_id(struct filter_obd *filter, obd_gr group)
1336 {
1337         obd_id id;
1338         LASSERT(filter->fo_fsd != NULL);
1339         LASSERT(group <= FILTER_GROUPS);
1340
1341         /* FIXME: object groups */
1342         spin_lock(&filter->fo_objidlock);
1343         id = filter->fo_last_objids[group];
1344         spin_unlock(&filter->fo_objidlock);
1345
1346         return id;
1347 }
1348
1349 static int filter_lock_dentry(struct obd_device *obd, struct dentry *dparent)
1350 {
1351         LOCK_INODE_MUTEX(dparent->d_inode);
1352         return 0;
1353 }
1354
1355 /* We never dget the object parent, so DON'T dput it either */
1356 struct dentry *filter_parent(struct obd_device *obd, obd_gr group, obd_id objid)
1357 {
1358         struct filter_obd *filter = &obd->u.filter;
1359         LASSERT(group < FILTER_GROUPS); /* FIXME: object groups */
1360
1361         if (group > 0 || filter->fo_subdir_count == 0)
1362                 return filter->fo_dentry_O_groups[group];
1363
1364         return filter->fo_dentry_O_sub[objid & (filter->fo_subdir_count - 1)];
1365 }
1366
1367 /* We never dget the object parent, so DON'T dput it either */
1368 struct dentry *filter_parent_lock(struct obd_device *obd, obd_gr group,
1369                                   obd_id objid)
1370 {
1371         unsigned long now = jiffies;
1372         struct dentry *dparent = filter_parent(obd, group, objid);
1373         int rc;
1374
1375         if (IS_ERR(dparent))
1376                 return dparent;
1377
1378         rc = filter_lock_dentry(obd, dparent);
1379         fsfilt_check_slow(obd, now, "parent lock");
1380         return rc ? ERR_PTR(rc) : dparent;
1381 }
1382
1383 /* We never dget the object parent, so DON'T dput it either */
1384 static void filter_parent_unlock(struct dentry *dparent)
1385 {
1386         UNLOCK_INODE_MUTEX(dparent->d_inode);
1387 }
1388
1389 /* How to get files, dentries, inodes from object id's.
1390  *
1391  * If dir_dentry is passed, the caller has already locked the parent
1392  * appropriately for this operation (normally a write lock).  If
1393  * dir_dentry is NULL, we do a read lock while we do the lookup to
1394  * avoid races with create/destroy and such changing the directory
1395  * internal to the filesystem code. */
1396 struct dentry *filter_fid2dentry(struct obd_device *obd,
1397                                  struct dentry *dir_dentry,
1398                                  obd_gr group, obd_id id)
1399 {
1400         struct dentry *dparent = dir_dentry;
1401         struct dentry *dchild;
1402         char name[32];
1403         int len;
1404         ENTRY;
1405
1406         if (OBD_FAIL_CHECK(OBD_FAIL_OST_ENOENT) &&
1407             !obd->u.filter.fo_destroy_in_progress) {
1408                 /* don't fail lookups for orphan recovery, it causes
1409                  * later LBUGs when objects still exist during precreate */
1410                 CDEBUG(D_INFO, "*** obd_fail_loc=%x ***\n",OBD_FAIL_OST_ENOENT);
1411                 RETURN(ERR_PTR(-ENOENT));
1412         }
1413
1414         if (id == 0) {
1415                 CERROR("fatal: invalid object id 0\n");
1416                 RETURN(ERR_PTR(-ESTALE));
1417         }
1418
1419         len = sprintf(name, LPU64, id);
1420         if (dir_dentry == NULL) {
1421                 dparent = filter_parent_lock(obd, group, id);
1422                 if (IS_ERR(dparent)) {
1423                         CERROR("%s: error getting object "LPU64":"LPU64
1424                                " parent: rc %ld\n", obd->obd_name,
1425                                id, group, PTR_ERR(dparent));
1426                         RETURN(dparent);
1427                 }
1428         }
1429         CDEBUG(D_INODE, "looking up object O/%.*s/%s\n",
1430                dparent->d_name.len, dparent->d_name.name, name);
1431         dchild = /*ll_*/lookup_one_len(name, dparent, len);
1432         if (dir_dentry == NULL)
1433                 filter_parent_unlock(dparent);
1434         if (IS_ERR(dchild)) {
1435                 CERROR("%s: child lookup error %ld\n", obd->obd_name,
1436                        PTR_ERR(dchild));
1437                 RETURN(dchild);
1438         }
1439
1440         if (dchild->d_inode != NULL && is_bad_inode(dchild->d_inode)) {
1441                 CERROR("%s: got bad object "LPU64" inode %lu\n",
1442                        obd->obd_name, id, dchild->d_inode->i_ino);
1443                 f_dput(dchild);
1444                 RETURN(ERR_PTR(-ENOENT));
1445         }
1446
1447         CDEBUG(D_INODE, "got child objid %s: %p, count = %d\n",
1448                name, dchild, atomic_read(&dchild->d_count));
1449
1450         LASSERT(atomic_read(&dchild->d_count) > 0);
1451
1452         RETURN(dchild);
1453 }
1454
1455 static int filter_prepare_destroy(struct obd_device *obd, obd_id objid,
1456                                   struct lustre_handle *lockh)
1457 {
1458         int flags = LDLM_AST_DISCARD_DATA, rc;
1459         struct ldlm_res_id res_id = { .name = { objid } };
1460         ldlm_policy_data_t policy = { .l_extent = { 0, OBD_OBJECT_EOF } };
1461
1462         ENTRY;
1463         /* Tell the clients that the object is gone now and that they should
1464          * throw away any cached pages. */
1465         rc = ldlm_cli_enqueue_local(obd->obd_namespace, &res_id, LDLM_EXTENT,
1466                                     &policy, LCK_PW, &flags, ldlm_blocking_ast,
1467                                     ldlm_completion_ast, NULL, NULL, 0, NULL,
1468                                     lockh);
1469
1470         if (rc != ELDLM_OK) {
1471                 lockh->cookie = 0;
1472                 CERROR("%s: failed to get lock to destroy objid "LPU64" (%d)\n",
1473                        obd->obd_name, objid, rc);
1474         }
1475         RETURN(rc);
1476 }
1477
1478 static void filter_fini_destroy(struct obd_device *obd,
1479                                 struct lustre_handle *lockh)
1480 {
1481         if (lustre_handle_is_used(lockh))
1482                 ldlm_lock_decref(lockh, LCK_PW);
1483 }
1484
1485 /* This is vfs_unlink() without down(i_sem).  If we call regular vfs_unlink()
1486  * we have 2.6 lock ordering issues with filter_commitrw_write() as it takes
1487  * i_sem before starting a handle, while filter_destroy() + vfs_unlink do the
1488  * reverse.  Caller must take i_sem before starting the transaction and we
1489  * drop it here before the inode is removed from the dentry.  bug 4180/6984 */
1490 int filter_vfs_unlink(struct inode *dir, struct dentry *dentry,
1491                       struct vfsmount *mnt)
1492 {
1493         int rc;
1494         ENTRY;
1495
1496         /* don't need dir->i_zombie for 2.4, it is for rename/unlink of dir
1497          * itself we already hold dir->i_mutex for child create/unlink ops */
1498         LASSERT(dentry->d_inode != NULL);
1499         LASSERT(TRYLOCK_INODE_MUTEX(dir) == 0);
1500         LASSERT(TRYLOCK_INODE_MUTEX(dentry->d_inode) == 0);
1501
1502
1503         /* may_delete() */
1504         if (/*!dentry->d_inode ||*/dentry->d_parent->d_inode != dir)
1505                 GOTO(out, rc = -ENOENT);
1506
1507         rc = ll_permission(dir, MAY_WRITE | MAY_EXEC, NULL);
1508         if (rc)
1509                 GOTO(out, rc);
1510
1511         if (IS_APPEND(dir))
1512                 GOTO(out, rc = -EPERM);
1513
1514         /* check_sticky() */
1515         if ((dentry->d_inode->i_uid != current->fsuid &&
1516              !cfs_capable(CFS_CAP_FOWNER)) || IS_APPEND(dentry->d_inode) ||
1517             IS_IMMUTABLE(dentry->d_inode))
1518                 GOTO(out, rc = -EPERM);
1519
1520         /* NOTE: This might need to go outside i_mutex, though it isn't clear if
1521          *       that was done because of journal_start (which is already done
1522          *       here) or some other ordering issue. */
1523         DQUOT_INIT(dir);
1524
1525         rc = ll_security_inode_unlink(dir, dentry, mnt);
1526         if (rc)
1527                 GOTO(out, rc);
1528         rc = dir->i_op->unlink(dir, dentry);
1529 out:
1530         /* need to drop i_mutex before we lose inode reference */
1531         UNLOCK_INODE_MUTEX(dentry->d_inode);
1532         if (rc == 0)
1533                 d_delete(dentry);
1534
1535         RETURN(rc);
1536 }
1537
1538 /* Caller must hold LCK_PW on parent and push us into kernel context.
1539  * Caller must hold child i_mutex, we drop it always.
1540  * Caller is also required to ensure that dchild->d_inode exists. */
1541 static int filter_destroy_internal(struct obd_device *obd, obd_id objid,
1542                                    obd_gr group, struct dentry *dparent,
1543                                    struct dentry *dchild)
1544 {
1545         struct inode *inode = dchild->d_inode;
1546         struct filter_obd *filter = &obd->u.filter;
1547         int rc;
1548
1549         if (inode->i_nlink != 1 || atomic_read(&inode->i_count) != 1) {
1550                 CERROR("destroying objid %.*s ino %lu nlink %lu count %d\n",
1551                        dchild->d_name.len, dchild->d_name.name, inode->i_ino,
1552                        (unsigned long)inode->i_nlink,
1553                        atomic_read(&inode->i_count));
1554         }
1555
1556         rc = filter_vfs_unlink(dparent->d_inode, dchild, filter->fo_vfsmnt);
1557         if (rc)
1558                 CERROR("error unlinking objid %.*s: rc %d\n",
1559                        dchild->d_name.len, dchild->d_name.name, rc);
1560         return(rc);
1561 }
1562
1563 struct filter_intent_args {
1564         struct ldlm_lock **victim;
1565         __u64 size;
1566         int *liblustre;
1567 };
1568
1569 static enum interval_iter filter_intent_cb(struct interval_node *n,
1570                                            void *args)
1571 {
1572         struct ldlm_interval *node = (struct ldlm_interval *)n;
1573         struct filter_intent_args *arg = (struct filter_intent_args*)args;
1574         __u64 size = arg->size;
1575         struct ldlm_lock **v = arg->victim;
1576         struct ldlm_lock *lck;
1577
1578         /* If the interval is lower than the current file size,
1579          * just break. */
1580         if (interval_high(n) <= size)
1581                 return INTERVAL_ITER_STOP;
1582
1583         list_for_each_entry(lck, &node->li_group, l_sl_policy) {
1584                 /* Don't send glimpse ASTs to liblustre clients.
1585                  * They aren't listening for them, and they do
1586                  * entirely synchronous I/O anyways. */
1587                 if (lck->l_export == NULL ||
1588                     lck->l_export->exp_libclient == 1)
1589                         continue;
1590
1591                 if (*arg->liblustre)
1592                         *arg->liblustre = 0;
1593
1594                 if (*v == NULL) {
1595                         *v = LDLM_LOCK_GET(lck);
1596                 } else if ((*v)->l_policy_data.l_extent.start <
1597                            lck->l_policy_data.l_extent.start) {
1598                         LDLM_LOCK_PUT(*v);
1599                         *v = LDLM_LOCK_GET(lck);
1600                 }
1601
1602                 /* the same policy group - every lock has the
1603                  * same extent, so needn't do it any more */
1604                 break;
1605         }
1606
1607         return INTERVAL_ITER_CONT;
1608 }
1609
1610 static int filter_intent_policy(struct ldlm_namespace *ns,
1611                                 struct ldlm_lock **lockp, void *req_cookie,
1612                                 ldlm_mode_t mode, int flags, void *data)
1613 {
1614         struct list_head rpc_list = LIST_HEAD_INIT(rpc_list);
1615         struct ptlrpc_request *req = req_cookie;
1616         struct ldlm_lock *lock = *lockp, *l = NULL;
1617         struct ldlm_resource *res = lock->l_resource;
1618         ldlm_processing_policy policy;
1619         struct ost_lvb *res_lvb, *reply_lvb;
1620         struct ldlm_reply *rep;
1621         ldlm_error_t err;
1622         int idx, rc, tmpflags = 0, only_liblustre = 1;
1623         struct ldlm_interval_tree *tree;
1624         struct filter_intent_args arg;
1625         __u32 repsize[3] = { [MSG_PTLRPC_BODY_OFF] = sizeof(struct ptlrpc_body),
1626                            [DLM_LOCKREPLY_OFF]   = sizeof(*rep),
1627                            [DLM_REPLY_REC_OFF]   = sizeof(*reply_lvb) };
1628         ENTRY;
1629
1630         policy = ldlm_get_processing_policy(res);
1631         LASSERT(policy != NULL);
1632         LASSERT(req != NULL);
1633
1634         rc = lustre_pack_reply(req, 3, repsize, NULL);
1635         if (rc)
1636                 RETURN(req->rq_status = rc);
1637
1638         rep = lustre_msg_buf(req->rq_repmsg, DLM_LOCKREPLY_OFF, sizeof(*rep));
1639         LASSERT(rep != NULL);
1640
1641         reply_lvb = lustre_msg_buf(req->rq_repmsg, DLM_REPLY_REC_OFF,
1642                                    sizeof(*reply_lvb));
1643         LASSERT(reply_lvb != NULL);
1644
1645         //fixup_handle_for_resent_req(req, lock, &lockh);
1646
1647         /* Call the extent policy function to see if our request can be
1648          * granted, or is blocked.
1649          * If the OST lock has LDLM_FL_HAS_INTENT set, it means a glimpse
1650          * lock, and should not be granted if the lock will be blocked.
1651          */
1652
1653         LASSERT(ns == res->lr_namespace);
1654         lock_res(res);
1655         rc = policy(lock, &tmpflags, 0, &err, &rpc_list);
1656         check_res_locked(res);
1657
1658         /* FIXME: we should change the policy function slightly, to not make
1659          * this list at all, since we just turn around and free it */
1660         while (!list_empty(&rpc_list)) {
1661                 struct ldlm_lock *wlock =
1662                         list_entry(rpc_list.next, struct ldlm_lock, l_cp_ast);
1663                 LASSERT((lock->l_flags & LDLM_FL_AST_SENT) == 0);
1664                 LASSERT(lock->l_flags & LDLM_FL_CP_REQD);
1665                 lock->l_flags &= ~LDLM_FL_CP_REQD;
1666                 list_del_init(&wlock->l_cp_ast);
1667                 LDLM_LOCK_PUT(wlock);
1668         }
1669
1670         /* The lock met with no resistance; we're finished. */
1671         if (rc == LDLM_ITER_CONTINUE) {
1672                 /* do not grant locks to the liblustre clients: they cannot
1673                  * handle ASTs robustly.  We need to do this while still
1674                  * holding ns_lock to avoid the lock remaining on the res_link
1675                  * list (and potentially being added to l_pending_list by an
1676                  * AST) when we are going to drop this lock ASAP. */
1677                 if (lock->l_export->exp_libclient ||
1678                     OBD_FAIL_TIMEOUT(OBD_FAIL_LDLM_GLIMPSE, 2)) {
1679                         ldlm_resource_unlink_lock(lock);
1680                         err = ELDLM_LOCK_ABORTED;
1681                 } else {
1682                         err = ELDLM_LOCK_REPLACED;
1683                 }
1684                 unlock_res(res);
1685                 RETURN(err);
1686         }
1687
1688         /* Do not grant any lock, but instead send GL callbacks.  The extent
1689          * policy nicely created a list of all PW locks for us.  We will choose
1690          * the highest of those which are larger than the size in the LVB, if
1691          * any, and perform a glimpse callback. */
1692         res_lvb = res->lr_lvb_data;
1693         LASSERT(res_lvb != NULL);
1694         *reply_lvb = *res_lvb;
1695
1696         /*
1697          * ->ns_lock guarantees that no new locks are granted, and,
1698          * therefore, that res->lr_lvb_data cannot increase beyond the
1699          * end of already granted lock. As a result, it is safe to
1700          * check against "stale" reply_lvb->lvb_size value without
1701          * res->lr_lvb_sem.
1702          */
1703         arg.size = reply_lvb->lvb_size;
1704         arg.victim = &l;
1705         arg.liblustre = &only_liblustre;
1706         for (idx = 0; idx < LCK_MODE_NUM; idx++) {
1707                 tree = &res->lr_itree[idx];
1708                 if (tree->lit_mode == LCK_PR)
1709                         continue;
1710
1711                 interval_iterate_reverse(tree->lit_root,
1712                                          filter_intent_cb, &arg);
1713         }
1714         unlock_res(res);
1715
1716         /* There were no PW locks beyond the size in the LVB; finished. */
1717         if (l == NULL) {
1718                 if (only_liblustre) {
1719                         /* If we discovered a liblustre client with a PW lock,
1720                          * however, the LVB may be out of date!  The LVB is
1721                          * updated only on glimpse (which we don't do for
1722                          * liblustre clients) and cancel (which the client
1723                          * obviously has not yet done).  So if it has written
1724                          * data but kept the lock, the LVB is stale and needs
1725                          * to be updated from disk.
1726                          *
1727                          * Of course, this will all disappear when we switch to
1728                          * taking liblustre locks on the OST. */
1729                         ldlm_res_lvbo_update(res, NULL, 0, 1);
1730                 }
1731                 RETURN(ELDLM_LOCK_ABORTED);
1732         }
1733
1734         /*
1735          * This check is for lock taken in filter_prepare_destroy() that does
1736          * not have l_glimpse_ast set. So the logic is: if there is a lock
1737          * with no l_glimpse_ast set, this object is being destroyed already.
1738          *
1739          * Hence, if you are grabbing DLM locks on the server, always set
1740          * non-NULL glimpse_ast (e.g., ldlm_request.c:ldlm_glimpse_ast()).
1741          */
1742         if (l->l_glimpse_ast == NULL) {
1743                 /* We are racing with unlink(); just return -ENOENT */
1744                 rep->lock_policy_res1 = -ENOENT;
1745                 goto out;
1746         }
1747
1748         LASSERTF(l->l_glimpse_ast != NULL, "l == %p", l);
1749         rc = l->l_glimpse_ast(l, NULL); /* this will update the LVB */
1750         /* Update the LVB from disk if the AST failed (this is a legal race) */
1751         /*
1752          * XXX nikita: situation when ldlm_server_glimpse_ast() failed before
1753          * sending ast is not handled. This can result in lost client writes.
1754          */
1755         if (rc != 0)
1756                 ldlm_res_lvbo_update(res, NULL, 0, 1);
1757
1758         lock_res(res);
1759         *reply_lvb = *res_lvb;
1760         unlock_res(res);
1761
1762  out:
1763         LDLM_LOCK_PUT(l);
1764
1765         RETURN(ELDLM_LOCK_ABORTED);
1766 }
1767
1768 /*
1769  * per-obd_device iobuf pool.
1770  *
1771  * To avoid memory deadlocks in low-memory setups, amount of dynamic
1772  * allocations in write-path has to be minimized (see bug 5137).
1773  *
1774  * Pages, niobuf_local's and niobuf_remote's are pre-allocated and attached to
1775  * OST threads (see ost_thread_{init,done}()).
1776  *
1777  * "iobuf's" used by filter cannot be attached to OST thread, however, because
1778  * at the OST layer there are only (potentially) multiple obd_device of type
1779  * unknown at the time of OST thread creation.
1780  *
1781  * Instead array of iobuf's is attached to struct filter_obd (->fo_iobuf_pool
1782  * field). This array has size OST_MAX_THREADS, so that each OST thread uses
1783  * it's very own iobuf.
1784  *
1785  * Functions below
1786  *
1787  *     filter_kiobuf_pool_init()
1788  *
1789  *     filter_kiobuf_pool_done()
1790  *
1791  *     filter_iobuf_get()
1792  *
1793  * operate on this array. They are "generic" in a sense that they don't depend
1794  * on actual type of iobuf's (the latter depending on Linux kernel version).
1795  */
1796
1797 /*
1798  * destroy pool created by filter_iobuf_pool_init
1799  */
1800 static void filter_iobuf_pool_done(struct filter_obd *filter)
1801 {
1802         struct filter_iobuf **pool;
1803         int i;
1804
1805         ENTRY;
1806
1807         pool = filter->fo_iobuf_pool;
1808         if (pool != NULL) {
1809                 for (i = 0; i < filter->fo_iobuf_count; ++ i) {
1810                         if (pool[i] != NULL)
1811                                 filter_free_iobuf(pool[i]);
1812                 }
1813                 OBD_FREE(pool, filter->fo_iobuf_count * sizeof pool[0]);
1814                 filter->fo_iobuf_pool = NULL;
1815         }
1816         EXIT;
1817 }
1818
1819 /*
1820  * pre-allocate pool of iobuf's to be used by filter_{prep,commit}rw_write().
1821  */
1822 static int filter_iobuf_pool_init(struct filter_obd *filter)
1823 {
1824         void **pool;
1825
1826         ENTRY;
1827
1828         OBD_ALLOC_GFP(filter->fo_iobuf_pool, OSS_THREADS_MAX * sizeof(*pool),
1829                       GFP_KERNEL);
1830         if (filter->fo_iobuf_pool == NULL)
1831                 RETURN(-ENOMEM);
1832
1833         filter->fo_iobuf_count = OSS_THREADS_MAX;
1834
1835         RETURN(0);
1836 }
1837
1838 /* Return iobuf allocated for @thread_id.  We don't know in advance how
1839  * many threads there will be so we allocate a large empty array and only
1840  * fill in those slots that are actually in use.
1841  * If we haven't allocated a pool entry for this thread before, do so now. */
1842 void *filter_iobuf_get(struct filter_obd *filter, struct obd_trans_info *oti)
1843 {
1844         int thread_id                    = (oti && oti->oti_thread) ?
1845                                            oti->oti_thread->t_id : -1;
1846         struct filter_iobuf  *pool       = NULL;
1847         struct filter_iobuf **pool_place = NULL;
1848
1849         if (thread_id >= 0) {
1850                 LASSERT(thread_id < filter->fo_iobuf_count);
1851                 pool = *(pool_place = &filter->fo_iobuf_pool[thread_id]);
1852         }
1853
1854         if (unlikely(pool == NULL)) {
1855                 pool = filter_alloc_iobuf(filter, OBD_BRW_WRITE,
1856                                           PTLRPC_MAX_BRW_PAGES);
1857                 if (pool_place != NULL)
1858                         *pool_place = pool;
1859         }
1860
1861         return pool;
1862 }
1863
1864 /* mount the file system (secretly).  lustre_cfg parameters are:
1865  * 1 = device
1866  * 2 = fstype
1867  * 3 = flags: failover=f, failout=n
1868  * 4 = mount options
1869  */
1870 int filter_common_setup(struct obd_device *obd, obd_count len, void *buf,
1871                         void *option)
1872 {
1873         struct lustre_cfg* lcfg = buf;
1874         struct filter_obd *filter = &obd->u.filter;
1875         struct vfsmount *mnt;
1876         struct lustre_mount_info *lmi;
1877         struct obd_uuid uuid;
1878         __u8 *uuid_ptr;
1879         char *str, *label;
1880         char ns_name[48];
1881 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,9)
1882         struct request_queue *q;
1883 #endif
1884         int rc;
1885         ENTRY;
1886
1887         if (lcfg->lcfg_bufcount < 3 ||
1888             LUSTRE_CFG_BUFLEN(lcfg, 1) < 1 ||
1889             LUSTRE_CFG_BUFLEN(lcfg, 2) < 1)
1890                 RETURN(-EINVAL);
1891
1892         lmi = server_get_mount(obd->obd_name);
1893         if (lmi) {
1894                 /* We already mounted in lustre_fill_super.
1895                    lcfg bufs 1, 2, 4 (device, fstype, mount opts) are ignored.*/
1896                 struct lustre_sb_info *lsi = s2lsi(lmi->lmi_sb);
1897                 mnt = lmi->lmi_mnt;
1898                 obd->obd_fsops = fsfilt_get_ops(MT_STR(lsi->lsi_ldd));
1899         } else {
1900                 /* old path - used by lctl */
1901                 CERROR("Using old MDS mount method\n");
1902                 mnt = ll_kern_mount(lustre_cfg_string(lcfg, 2),
1903                                     MS_NOATIME|MS_NODIRATIME,
1904                                     lustre_cfg_string(lcfg, 1), option);
1905                 if (IS_ERR(mnt)) {
1906                         rc = PTR_ERR(mnt);
1907                         LCONSOLE_ERROR_MSG(0x135, "Can't mount disk %s (%d)\n",
1908                                            lustre_cfg_string(lcfg, 1), rc);
1909                         RETURN(rc);
1910                 }
1911
1912                 obd->obd_fsops = fsfilt_get_ops(lustre_cfg_string(lcfg, 2));
1913         }
1914         if (IS_ERR(obd->obd_fsops))
1915                 GOTO(err_mntput, rc = PTR_ERR(obd->obd_fsops));
1916
1917         rc = filter_iobuf_pool_init(filter);
1918         if (rc != 0)
1919                 GOTO(err_ops, rc);
1920
1921         if (lvfs_check_rdonly(lvfs_sbdev(mnt->mnt_sb))) {
1922                 CERROR("%s: Underlying device is marked as read-only. "
1923                        "Setup failed\n", obd->obd_name);
1924                 GOTO(err_ops, rc = -EROFS);
1925         }
1926
1927         /* failover is the default */
1928         obd->obd_replayable = 1;
1929
1930         if (lcfg->lcfg_bufcount > 3 && LUSTRE_CFG_BUFLEN(lcfg, 3) > 0) {
1931                 str = lustre_cfg_string(lcfg, 3);
1932                 if (strchr(str, 'n')) {
1933                         CWARN("%s: recovery disabled\n", obd->obd_name);
1934                         obd->obd_replayable = 0;
1935                 }
1936         }
1937
1938         filter->fo_vfsmnt = mnt;
1939         obd->u.obt.obt_sb = mnt->mnt_sb;
1940         obd->u.obt.obt_stale_export_age = STALE_EXPORT_MAXTIME_DEFAULT;
1941         spin_lock_init(&obd->u.obt.obt_trans_table_lock);
1942
1943         filter->fo_fstype = mnt->mnt_sb->s_type->name;
1944         CDEBUG(D_SUPER, "%s: mnt = %p\n", filter->fo_fstype, mnt);
1945
1946         rc = fsfilt_setup(obd, obd->u.obt.obt_sb);
1947         if (rc)
1948                 GOTO(err_ops, rc);
1949
1950         OBD_SET_CTXT_MAGIC(&obd->obd_lvfs_ctxt);
1951         obd->obd_lvfs_ctxt.pwdmnt = mnt;
1952         obd->obd_lvfs_ctxt.pwd = mnt->mnt_root;
1953         obd->obd_lvfs_ctxt.fs = get_ds();
1954         obd->obd_lvfs_ctxt.cb_ops = filter_lvfs_ops;
1955
1956         filter->fo_destroy_in_progress = 0;
1957         sema_init(&filter->fo_create_lock, 1);
1958         spin_lock_init(&filter->fo_translock);
1959         spin_lock_init(&filter->fo_objidlock);
1960         INIT_LIST_HEAD(&filter->fo_export_list);
1961         sema_init(&filter->fo_alloc_lock, 1);
1962         init_brw_stats(&filter->fo_filter_stats);
1963         filter->fo_read_cache = 1; /* enable read-only cache by default */
1964         filter->fo_writethrough_cache = 1; /* enable writethrough cache */
1965         filter->fo_readcache_max_filesize = FILTER_MAX_CACHE_SIZE;
1966         filter->fo_fmd_max_num = FILTER_FMD_MAX_NUM_DEFAULT;
1967         filter->fo_fmd_max_age = FILTER_FMD_MAX_AGE_DEFAULT;
1968         filter->fo_syncjournal = 1; /* Sync journals on i/o by default b=19128 */
1969
1970         rc = filter_prep(obd);
1971         if (rc)
1972                 GOTO(err_ops, rc);
1973
1974         sprintf(ns_name, "filter-%s", obd->obd_uuid.uuid);
1975         obd->obd_namespace = ldlm_namespace_new(obd, ns_name, LDLM_NAMESPACE_SERVER,
1976                                                 LDLM_NAMESPACE_GREEDY);
1977         if (obd->obd_namespace == NULL)
1978                 GOTO(err_post, rc = -ENOMEM);
1979         obd->obd_namespace->ns_lvbp = obd;
1980         obd->obd_namespace->ns_lvbo = &filter_lvbo;
1981         ldlm_register_intent(obd->obd_namespace, filter_intent_policy);
1982
1983         ptlrpc_init_client(LDLM_CB_REQUEST_PORTAL, LDLM_CB_REPLY_PORTAL,
1984                            "filter_ldlm_cb_client", &obd->obd_ldlm_client);
1985
1986         rc = obd_llog_init(obd, obd, NULL);
1987         if (rc) {
1988                 CERROR("failed to setup llogging subsystems\n");
1989                 GOTO(err_post, rc);
1990         }
1991
1992         rc = lquota_setup(filter_quota_interface_ref, obd);
1993         if (rc)
1994                 GOTO(err_post, rc);
1995
1996 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,9)
1997         q = bdev_get_queue(mnt->mnt_sb->s_bdev);
1998         if (q->max_sectors < q->max_hw_sectors &&
1999             q->max_sectors < PTLRPC_MAX_BRW_SIZE >> 9)
2000                 LCONSOLE_INFO("%s: underlying device %s should be tuned "
2001                               "for larger I/O requests: max_sectors = %u "
2002                               "could be up to max_hw_sectors=%u\n",
2003                               obd->obd_name, mnt->mnt_sb->s_id,
2004                               q->max_sectors, q->max_hw_sectors);
2005 #endif
2006
2007         uuid_ptr = fsfilt_uuid(obd, obd->u.obt.obt_sb);
2008         if (uuid_ptr != NULL) {
2009                 class_uuid_unparse(uuid_ptr, &uuid);
2010                 str = uuid.uuid;
2011         } else {
2012                 str = "no UUID";
2013         }
2014
2015         label = fsfilt_get_label(obd, obd->u.obt.obt_sb);
2016
2017         if (obd->obd_recovering) {
2018                 LCONSOLE_WARN("OST %s now serving %s (%s%s%s), but will be in "
2019                               "recovery for at least %d:%.02d, or until %d "
2020                               "client%s reconnect%s.\n",
2021                               obd->obd_name, lustre_cfg_string(lcfg, 1),
2022                               label ?: "", label ? "/" : "", str,
2023                               obd->obd_recovery_timeout / 60,
2024                               obd->obd_recovery_timeout % 60,
2025                               obd->obd_recoverable_clients,
2026                               obd->obd_recoverable_clients == 1 ? "":"s",
2027                               obd->obd_recoverable_clients == 1 ? "s":"");
2028         } else {
2029                 LCONSOLE_INFO("OST %s now serving %s (%s%s%s) with recovery "
2030                               "%s\n", obd->obd_name, lustre_cfg_string(lcfg, 1),
2031                               label ?: "", label ? "/" : "", str,
2032                               obd->obd_replayable ? "enabled" : "disabled");
2033         }
2034
2035         RETURN(0);
2036
2037 err_post:
2038         filter_post(obd);
2039 err_ops:
2040         fsfilt_put_ops(obd->obd_fsops);
2041         filter_iobuf_pool_done(filter);
2042 err_mntput:
2043         server_put_mount(obd->obd_name, mnt);
2044         obd->u.obt.obt_sb = 0;
2045         return rc;
2046 }
2047
2048 static int filter_setup(struct obd_device *obd, obd_count len, void *buf)
2049 {
2050         struct lprocfs_static_vars lvars;
2051         struct lustre_cfg* lcfg = buf;
2052         unsigned long addr;
2053         struct page *page;
2054         int rc;
2055
2056         CLASSERT(offsetof(struct obd_device, u.obt) ==
2057                  offsetof(struct obd_device, u.filter.fo_obt));
2058
2059         if (!LUSTRE_CFG_BUFLEN(lcfg, 1) || !LUSTRE_CFG_BUFLEN(lcfg, 2))
2060                 RETURN(-EINVAL);
2061
2062         /* 2.6.9 selinux wants a full option page for do_kern_mount (bug6471) */
2063         OBD_PAGE_ALLOC(page, CFS_ALLOC_STD);
2064         if (!page)
2065                 RETURN(-ENOMEM);
2066         addr = (unsigned long)cfs_page_address(page);
2067         clear_page((void *)addr);
2068
2069         /* lprocfs must be setup before the filter so state can be safely added
2070          * to /proc incrementally as the filter is setup */
2071         lprocfs_filter_init_vars(&lvars);
2072         if (lprocfs_obd_setup(obd, lvars.obd_vars) == 0 &&
2073             lprocfs_alloc_obd_stats(obd, LPROC_FILTER_LAST) == 0) {
2074                 /* Init obdfilter private stats here */
2075                 lprocfs_counter_init(obd->obd_stats, LPROC_FILTER_READ_BYTES,
2076                                      LPROCFS_CNTR_AVGMINMAX,
2077                                      "read_bytes", "bytes");
2078                 lprocfs_counter_init(obd->obd_stats, LPROC_FILTER_WRITE_BYTES,
2079                                      LPROCFS_CNTR_AVGMINMAX,
2080                                      "write_bytes", "bytes");
2081                 lprocfs_counter_init(obd->obd_stats, LPROC_FILTER_GET_PAGE,
2082                                      LPROCFS_CNTR_AVGMINMAX|LPROCFS_CNTR_STDDEV,
2083                                      "get_page", "usec");
2084                 lprocfs_counter_init(obd->obd_stats, LPROC_FILTER_NO_PAGE,
2085                                      LPROCFS_CNTR_AVGMINMAX,
2086                                      "get_page failures", "num");
2087                 lprocfs_counter_init(obd->obd_stats, LPROC_FILTER_CACHE_ACCESS,
2088                                      LPROCFS_CNTR_AVGMINMAX,
2089                                      "cache_access", "pages");
2090                 lprocfs_counter_init(obd->obd_stats, LPROC_FILTER_CACHE_HIT,
2091                                      LPROCFS_CNTR_AVGMINMAX,
2092                                      "cache_hit", "pages");
2093                 lprocfs_counter_init(obd->obd_stats, LPROC_FILTER_CACHE_MISS,
2094                                      LPROCFS_CNTR_AVGMINMAX,
2095                                      "cache_miss", "pages");
2096                 lproc_filter_attach_seqstat(obd);
2097 #ifdef HAVE_DELAYED_RECOVERY
2098                 lprocfs_obd_attach_stale_exports(obd);
2099 #endif
2100                 obd->obd_proc_exports_entry = proc_mkdir("exports",
2101                                                          obd->obd_proc_entry);
2102         }
2103         if (obd->obd_proc_exports_entry)
2104                 lprocfs_add_simple(obd->obd_proc_exports_entry, "clear",
2105                                    lprocfs_nid_stats_clear_read,
2106                                    lprocfs_nid_stats_clear_write, obd, NULL);
2107
2108         memcpy((void *)addr, lustre_cfg_buf(lcfg, 4),
2109                LUSTRE_CFG_BUFLEN(lcfg, 4));
2110         rc = filter_common_setup(obd, len, buf, (void *)addr);
2111         OBD_PAGE_FREE(page);
2112
2113         if (rc) {
2114                 remove_proc_entry("clear", obd->obd_proc_exports_entry);
2115                 lprocfs_free_per_client_stats(obd);
2116                 lprocfs_free_obd_stats(obd);
2117                 lprocfs_obd_cleanup(obd);
2118         }
2119
2120         return rc;
2121 }
2122
2123 static struct llog_operations filter_mds_ost_repl_logops /* initialized below*/;
2124 static struct llog_operations filter_size_orig_logops = {
2125         lop_setup: llog_obd_origin_setup,
2126         lop_cleanup: llog_obd_origin_cleanup,
2127         lop_add: llog_obd_origin_add
2128 };
2129
2130 static int filter_llog_init(struct obd_device *obd, struct obd_device *disk_obd,
2131                             int *index)
2132 {
2133         struct filter_obd *filter = &obd->u.filter;
2134         struct llog_ctxt *ctxt;
2135         int rc;
2136         ENTRY;
2137
2138         filter->fo_lcm = llog_recov_thread_init(obd->obd_name);
2139         if (!filter->fo_lcm)
2140                 RETURN(-ENOMEM);
2141
2142         filter_mds_ost_repl_logops = llog_client_ops;
2143         filter_mds_ost_repl_logops.lop_cancel = llog_obd_repl_cancel;
2144         filter_mds_ost_repl_logops.lop_connect = llog_obd_repl_connect;
2145         filter_mds_ost_repl_logops.lop_sync = llog_obd_repl_sync;
2146
2147         rc = llog_setup(obd, LLOG_MDS_OST_REPL_CTXT, disk_obd, 0, NULL,
2148                         &filter_mds_ost_repl_logops);
2149         if (rc)
2150                 GOTO(cleanup_lcm, rc);
2151
2152         /* FIXME - assign unlink_cb for filter's recovery */
2153         ctxt = llog_get_context(obd, LLOG_MDS_OST_REPL_CTXT);
2154         ctxt->llog_proc_cb = filter_recov_log_mds_ost_cb;
2155         ctxt->loc_lcm = filter->fo_lcm;
2156         llog_ctxt_put(ctxt);
2157
2158         rc = llog_setup(obd, LLOG_SIZE_ORIG_CTXT, disk_obd, 0, NULL,
2159                         &filter_size_orig_logops);
2160         if (rc)
2161                 GOTO(cleanup_ctxt, rc);
2162         RETURN(rc);
2163 cleanup_ctxt:
2164         ctxt = llog_get_context(obd, LLOG_MDS_OST_REPL_CTXT);
2165         if (ctxt)
2166                 llog_cleanup(ctxt);
2167 cleanup_lcm:
2168         llog_recov_thread_fini(filter->fo_lcm, 1);
2169         filter->fo_lcm = NULL;
2170         return rc;
2171 }
2172
2173 static int filter_llog_finish(struct obd_device *obd, int count)
2174 {
2175         struct filter_obd *filter = &obd->u.filter;
2176         struct llog_ctxt *ctxt;
2177         int rc = 0, rc2 = 0;
2178         ENTRY;
2179
2180         ctxt = llog_get_context(obd, LLOG_MDS_OST_REPL_CTXT);
2181         if (ctxt) {
2182                 /*
2183                  * Make sure that no cached llcds left in recov_thread. We
2184                  * actually do sync in disconnect time, but disconnect may
2185                  * not come being marked rq_no_resend = 1.
2186                  */
2187                 llog_sync(ctxt, NULL);
2188
2189                 /*
2190                  * Balance class_import_get() called in llog_receptor_accept().
2191                  * This is safe to do here, as llog is already synchronized and
2192                  * its import may go.
2193                  */
2194                 mutex_down(&ctxt->loc_sem);
2195                 if (ctxt->loc_imp) {
2196                         class_import_put(ctxt->loc_imp);
2197                         ctxt->loc_imp = NULL;
2198                 }
2199                 mutex_up(&ctxt->loc_sem);
2200         }
2201
2202         if (filter->fo_lcm) {
2203                 llog_recov_thread_fini(filter->fo_lcm, obd->obd_force);
2204                 filter->fo_lcm = NULL;
2205         }
2206
2207         if (ctxt)
2208                 rc = llog_cleanup(ctxt);
2209
2210         ctxt = llog_get_context(obd, LLOG_SIZE_ORIG_CTXT);
2211         if (ctxt)
2212                 rc2 = llog_cleanup(ctxt);
2213         if (!rc)
2214                 rc = rc2;
2215
2216         RETURN(rc);
2217 }
2218
2219 static int filter_precleanup(struct obd_device *obd,
2220                              enum obd_cleanup_stage stage)
2221 {
2222         int rc = 0;
2223         ENTRY;
2224
2225         switch(stage) {
2226         case OBD_CLEANUP_EARLY:
2227                 break;
2228         case OBD_CLEANUP_EXPORTS:
2229                 target_cleanup_recovery(obd);
2230                 rc = filter_llog_finish(obd, 0);
2231                 break;
2232         case OBD_CLEANUP_SELF_EXP:
2233                 break;
2234         case OBD_CLEANUP_OBD:
2235                 break;
2236         }
2237         RETURN(rc);
2238 }
2239
2240 static int filter_cleanup(struct obd_device *obd)
2241 {
2242         struct filter_obd *filter = &obd->u.filter;
2243         ENTRY;
2244
2245         if (obd->obd_fail)
2246                 LCONSOLE_WARN("%s: shutting down for failover; client state "
2247                               "will be preserved.\n", obd->obd_name);
2248
2249         if (!list_empty(&obd->obd_exports)) {
2250                 CERROR("%s: still has clients!\n", obd->obd_name);
2251                 class_disconnect_exports(obd);
2252                 if (!list_empty(&obd->obd_exports)) {
2253                         CERROR("still has exports after forced cleanup?\n");
2254                         RETURN(-EBUSY);
2255                 }
2256         }
2257
2258        /* some exports may still be in the zombie queue, so we make sure that
2259         * all the exports have been processed, otherwise the last_rcvd slot
2260         * may not be updated on time */
2261         obd_zombie_barrier();
2262
2263         remove_proc_entry("clear", obd->obd_proc_exports_entry);
2264         lprocfs_free_per_client_stats(obd);
2265         lprocfs_free_obd_stats(obd);
2266         lprocfs_obd_cleanup(obd);
2267
2268         lquota_cleanup(filter_quota_interface_ref, obd);
2269
2270         ldlm_namespace_free(obd->obd_namespace, NULL, obd->obd_force);
2271         obd->obd_namespace = NULL;
2272
2273         if (obd->u.obt.obt_sb == NULL)
2274                 RETURN(0);
2275
2276         filter_post(obd);
2277
2278         LL_DQUOT_OFF(obd->u.obt.obt_sb, 0);
2279         shrink_dcache_sb(obd->u.obt.obt_sb);
2280
2281         server_put_mount(obd->obd_name, filter->fo_vfsmnt);
2282         obd->u.obt.obt_sb = NULL;
2283
2284         fsfilt_put_ops(obd->obd_fsops);
2285
2286         filter_iobuf_pool_done(filter);
2287
2288         LCONSOLE_INFO("OST %s has stopped.\n", obd->obd_name);
2289
2290         RETURN(0);
2291 }
2292
2293 static int filter_connect_internal(struct obd_export *exp,
2294                                    struct obd_connect_data *data)
2295 {
2296         if (!data)
2297                 RETURN(0);
2298
2299         CDEBUG(D_RPCTRACE, "%s: cli %s/%p ocd_connect_flags: "LPX64
2300                " ocd_version: %x ocd_grant: %d ocd_index: %u\n",
2301                exp->exp_obd->obd_name, exp->exp_client_uuid.uuid, exp,
2302                data->ocd_connect_flags, data->ocd_version,
2303                data->ocd_grant, data->ocd_index);
2304
2305         data->ocd_connect_flags &= OST_CONNECT_SUPPORTED;
2306         exp->exp_connect_flags = data->ocd_connect_flags;
2307         data->ocd_version = LUSTRE_VERSION_CODE;
2308
2309         /* Kindly make sure the SKIP_ORPHAN flag is from MDS. */
2310         if (!ergo(data->ocd_connect_flags & OBD_CONNECT_SKIP_ORPHAN,
2311                   data->ocd_connect_flags & OBD_CONNECT_MDS))
2312                 RETURN(-EPROTO);
2313
2314         if (exp->exp_connect_flags & OBD_CONNECT_GRANT) {
2315                 struct filter_obd *filter = &exp->exp_obd->u.filter;
2316                 struct filter_export_data *fed = &exp->exp_filter_data;
2317                 obd_size left, want;
2318
2319                 spin_lock(&exp->exp_obd->obd_osfs_lock);
2320                 left = filter_grant_space_left(exp);
2321                 want = data->ocd_grant;
2322                 filter_grant(exp, fed->fed_grant, want, left);
2323                 data->ocd_grant = fed->fed_grant;
2324                 spin_unlock(&exp->exp_obd->obd_osfs_lock);
2325
2326                 CDEBUG(D_CACHE, "%s: cli %s/%p ocd_grant: %d want: "
2327                        LPU64" left: "LPU64"\n", exp->exp_obd->obd_name,
2328                        exp->exp_client_uuid.uuid, exp,
2329                        data->ocd_grant, want, left);
2330                 
2331                 filter->fo_tot_granted_clients ++;
2332         }
2333
2334         if (data->ocd_connect_flags & OBD_CONNECT_INDEX) {
2335                 struct filter_obd *filter = &exp->exp_obd->u.filter;
2336                 struct lr_server_data *lsd = filter->fo_fsd;
2337                 int index = le32_to_cpu(lsd->lsd_ost_index);
2338
2339                 if (!(lsd->lsd_feature_compat &
2340                       cpu_to_le32(OBD_COMPAT_OST))) {
2341                         /* this will only happen on the first connect */
2342                         lsd->lsd_ost_index = cpu_to_le32(data->ocd_index);
2343                         lsd->lsd_feature_compat |= cpu_to_le32(OBD_COMPAT_OST);
2344                         filter_update_server_data(exp->exp_obd,
2345                                                   filter->fo_rcvd_filp, lsd, 1);
2346                 } else if (index != data->ocd_index) {
2347                         LCONSOLE_ERROR_MSG(0x136, "Connection from %s to index "
2348                                            "%u doesn't match actual OST index "
2349                                            "%u in last_rcvd file, bad "
2350                                            "configuration?\n",
2351                                            obd_export_nid2str(exp), index,
2352                                            data->ocd_index);
2353                         RETURN(-EBADF);
2354                 }
2355         }
2356
2357         if (OBD_FAIL_CHECK(OBD_FAIL_OST_BRW_SIZE)) {
2358                 data->ocd_brw_size = 65536;
2359         } else if (data->ocd_connect_flags & OBD_CONNECT_BRW_SIZE) {
2360                 data->ocd_brw_size = min(data->ocd_brw_size,
2361                                          (__u32)(PTLRPC_MAX_BRW_PAGES <<
2362                                                  CFS_PAGE_SHIFT));
2363                 LASSERT(data->ocd_brw_size);
2364         }
2365
2366         if (data->ocd_connect_flags & OBD_CONNECT_CKSUM) {
2367                 __u32 cksum_types = data->ocd_cksum_types;
2368
2369                 /* The client set in ocd_cksum_types the checksum types it
2370                  * supports. We have to mask off the algorithms that we don't
2371                  * support */
2372                 if (cksum_types & OBD_CKSUM_ALL)
2373                         data->ocd_cksum_types &= OBD_CKSUM_ALL;
2374                 else
2375                         data->ocd_cksum_types = OBD_CKSUM_CRC32;
2376
2377                 CDEBUG(D_RPCTRACE, "%s: cli %s supports cksum type %x, return "
2378                                    "%x\n", exp->exp_obd->obd_name,
2379                                    obd_export_nid2str(exp), cksum_types,
2380                                    data->ocd_cksum_types);
2381         } else {
2382                 /* This client does not support OBD_CONNECT_CKSUM
2383                  * fall back to CRC32 */
2384                 CDEBUG(D_RPCTRACE, "%s: cli %s does not support "
2385                                    "OBD_CONNECT_CKSUM, CRC32 will be used\n",
2386                                    exp->exp_obd->obd_name,
2387                                    obd_export_nid2str(exp));
2388         }
2389
2390         /* FIXME: Do the same with the MDS UUID and fsd_peeruuid.
2391          * FIXME: We don't strictly need the COMPAT flag for that,
2392          * FIXME: as fsd_peeruuid[0] will tell us if that is set.
2393          * FIXME: We needed it for the index, as index 0 is valid. */
2394
2395         RETURN(0);
2396 }
2397
2398 static int filter_reconnect(struct obd_export *exp, struct obd_device *obd,
2399                             struct obd_uuid *cluuid,
2400                             struct obd_connect_data *data,
2401                             void *localdata)
2402 {
2403         int rc;
2404         ENTRY;
2405
2406         if (exp == NULL || obd == NULL || cluuid == NULL)
2407                 RETURN(-EINVAL);
2408
2409         rc = filter_connect_internal(exp, data);
2410         if (rc == 0)
2411                 filter_export_stats_init(obd, exp, 1, localdata);
2412
2413         RETURN(rc);
2414 }
2415
2416 /* nearly identical to mds_connect */
2417 static int filter_connect(struct lustre_handle *conn, struct obd_device *obd,
2418                           struct obd_uuid *cluuid,
2419                           struct obd_connect_data *data,
2420                           void *localdata)
2421 {
2422         struct obd_export *exp;
2423         struct filter_export_data *fed;
2424         struct lsd_client_data *lcd = NULL;
2425         int rc;
2426         ENTRY;
2427
2428         if (conn == NULL || obd == NULL || cluuid == NULL)
2429                 RETURN(-EINVAL);
2430
2431         /* Check for aborted recovery. */
2432         target_recovery_check_and_stop(obd);
2433
2434         rc = class_connect(conn, obd, cluuid);
2435         if (rc)
2436                 RETURN(rc);
2437         exp = class_conn2export(conn);
2438         LASSERT(exp != NULL);
2439
2440         fed = &exp->exp_filter_data;
2441
2442         rc = filter_connect_internal(exp, data);
2443         if (rc)
2444                 GOTO(cleanup, rc);
2445
2446         filter_export_stats_init(obd, exp, 0, localdata);
2447
2448         if (!obd->obd_replayable)
2449                 GOTO(cleanup, rc = 0);
2450
2451         OBD_ALLOC_PTR(lcd);
2452         if (!lcd) {
2453                 CERROR("filter: out of memory for client data\n");
2454                 GOTO(cleanup, rc = -ENOMEM);
2455         }
2456
2457         memcpy(lcd->lcd_uuid, cluuid, sizeof(lcd->lcd_uuid));
2458         fed->fed_lcd = lcd;
2459
2460         rc = filter_client_add(obd, exp, -1);
2461
2462         GOTO(cleanup, rc);
2463
2464 cleanup:
2465         if (rc) {
2466                 if (lcd) {
2467                         OBD_FREE_PTR(lcd);
2468                         fed->fed_lcd = NULL;
2469                 }
2470                 class_disconnect(exp);
2471                 lprocfs_exp_cleanup(exp);
2472         } else {
2473                 class_export_put(exp);
2474         }
2475
2476         RETURN(rc);
2477 }
2478
2479 /* Do extra sanity checks for grant accounting.  We do this at connect,
2480  * disconnect, and statfs RPC time, so it shouldn't be too bad.  We can
2481  * always get rid of it or turn it off when we know accounting is good. */
2482 static void filter_grant_sanity_check(struct obd_device *obd, const char *func)
2483 {
2484         struct filter_export_data *fed;
2485         struct obd_export *exp;
2486         obd_size maxsize = obd->obd_osfs.os_blocks * obd->obd_osfs.os_bsize;
2487         obd_size tot_dirty = 0, tot_pending = 0, tot_granted = 0;
2488         obd_size fo_tot_dirty, fo_tot_pending, fo_tot_granted;
2489
2490         if (list_empty(&obd->obd_exports))
2491                 return;
2492
2493         /* We don't want to do this for large machines that do lots of
2494            mounts or unmounts.  It burns... */
2495         if (obd->obd_num_exports > 100)
2496                 return;
2497
2498         spin_lock(&obd->obd_osfs_lock);
2499         spin_lock(&obd->obd_dev_lock);
2500         list_for_each_entry(exp, &obd->obd_exports, exp_obd_chain) {
2501                 int error = 0;
2502                 fed = &exp->exp_filter_data;
2503                 if (fed->fed_grant < 0 || fed->fed_pending < 0 ||
2504                     fed->fed_dirty < 0)
2505                         error = 1;
2506                 if (maxsize > 0) { /* we may not have done a statfs yet */
2507                         LASSERTF(fed->fed_grant + fed->fed_pending <= maxsize,
2508                                  "%s: cli %s/%p %ld+%ld > "LPU64"\n", func,
2509                                  exp->exp_client_uuid.uuid, exp,
2510                                  fed->fed_grant, fed->fed_pending, maxsize);
2511                         LASSERTF(fed->fed_dirty <= maxsize,
2512                                  "%s: cli %s/%p %ld > "LPU64"\n", func,
2513                                  exp->exp_client_uuid.uuid, exp,
2514                                  fed->fed_dirty, maxsize);
2515                 }
2516                 if (error)
2517                         CERROR("%s: cli %s/%p dirty %ld pend %ld grant %ld\n",
2518                                obd->obd_name, exp->exp_client_uuid.uuid, exp,
2519                                fed->fed_dirty, fed->fed_pending,fed->fed_grant);
2520                 else
2521                         CDEBUG(D_CACHE, "%s: cli %s/%p dirty %ld pend %ld grant %ld\n",
2522                                obd->obd_name, exp->exp_client_uuid.uuid, exp,
2523                                fed->fed_dirty, fed->fed_pending,fed->fed_grant);
2524                 tot_granted += fed->fed_grant + fed->fed_pending;
2525                 tot_pending += fed->fed_pending;
2526                 tot_dirty += fed->fed_dirty;
2527         }
2528         fo_tot_granted = obd->u.filter.fo_tot_granted;
2529         fo_tot_pending = obd->u.filter.fo_tot_pending;
2530         fo_tot_dirty = obd->u.filter.fo_tot_dirty;
2531         spin_unlock(&obd->obd_dev_lock);
2532         spin_unlock(&obd->obd_osfs_lock);
2533
2534         /* Do these assertions outside the spinlocks so we don't kill system */
2535         if (tot_granted != fo_tot_granted)
2536                 CERROR("%s: tot_granted "LPU64" != fo_tot_granted "LPU64"\n",
2537                        func, tot_granted, fo_tot_granted);
2538         if (tot_pending != fo_tot_pending)
2539                 CERROR("%s: tot_pending "LPU64" != fo_tot_pending "LPU64"\n",
2540                        func, tot_pending, fo_tot_pending);
2541         if (tot_dirty != fo_tot_dirty)
2542                 CERROR("%s: tot_dirty "LPU64" != fo_tot_dirty "LPU64"\n",
2543                        func, tot_dirty, fo_tot_dirty);
2544         if (tot_pending > tot_granted)
2545                 CERROR("%s: tot_pending "LPU64" > tot_granted "LPU64"\n",
2546                        func, tot_pending, tot_granted);
2547         if (tot_granted > maxsize)
2548                 CERROR("%s: tot_granted "LPU64" > maxsize "LPU64"\n",
2549                        func, tot_granted, maxsize);
2550         if (tot_dirty > maxsize)
2551                 CERROR("%s: tot_dirty "LPU64" > maxsize "LPU64"\n",
2552                        func, tot_dirty, maxsize);
2553 }
2554
2555 /* Remove this client from the grant accounting totals.  We also remove
2556  * the export from the obd device under the osfs and dev locks to ensure
2557  * that the filter_grant_sanity_check() calculations are always valid.
2558  * The client should do something similar when it invalidates its import. */
2559 static void filter_grant_discard(struct obd_export *exp)
2560 {
2561         struct obd_device *obd = exp->exp_obd;
2562         struct filter_obd *filter = &obd->u.filter;
2563         struct filter_export_data *fed = &exp->exp_filter_data;
2564
2565         spin_lock(&obd->obd_osfs_lock);
2566         spin_lock(&obd->obd_dev_lock);
2567         list_del_init(&exp->exp_obd_chain);
2568         spin_unlock(&obd->obd_dev_lock);
2569
2570         LASSERTF(filter->fo_tot_granted >= fed->fed_grant,
2571                  "%s: tot_granted "LPU64" cli %s/%p fed_grant %ld\n",
2572                  obd->obd_name, filter->fo_tot_granted,
2573                  exp->exp_client_uuid.uuid, exp, fed->fed_grant);
2574         filter->fo_tot_granted -= fed->fed_grant;
2575         LASSERTF(filter->fo_tot_pending >= fed->fed_pending,
2576                  "%s: tot_pending "LPU64" cli %s/%p fed_pending %ld\n",
2577                  obd->obd_name, filter->fo_tot_pending,
2578                  exp->exp_client_uuid.uuid, exp, fed->fed_pending);
2579         /* fo_tot_pending is handled in filter_grant_commit as bulk finishes */
2580         LASSERTF(filter->fo_tot_dirty >= fed->fed_dirty,
2581                  "%s: tot_dirty "LPU64" cli %s/%p fed_dirty %ld\n",
2582                  obd->obd_name, filter->fo_tot_dirty,
2583                  exp->exp_client_uuid.uuid, exp, fed->fed_dirty);
2584         filter->fo_tot_dirty -= fed->fed_dirty;
2585         fed->fed_dirty = 0;
2586         fed->fed_grant = 0;
2587
2588         spin_unlock(&obd->obd_osfs_lock);
2589 }
2590
2591 static int filter_destroy_export(struct obd_export *exp)
2592 {
2593         ENTRY;
2594
2595         if (exp->exp_filter_data.fed_pending)
2596                 CERROR("%s: cli %s/%p has %lu pending on destroyed export\n",
2597                        exp->exp_obd->obd_name, exp->exp_client_uuid.uuid,
2598                        exp, exp->exp_filter_data.fed_pending);
2599
2600         lquota_clearinfo(filter_quota_interface_ref, exp, exp->exp_obd);
2601
2602         target_destroy_export(exp);
2603         ldlm_destroy_export(exp);
2604
2605         if (obd_uuid_equals(&exp->exp_client_uuid, &exp->exp_obd->obd_uuid))
2606                 RETURN(0);
2607
2608
2609         if (exp->exp_obd->obd_replayable)
2610                 filter_client_free(exp);
2611         else
2612                 fsfilt_sync(exp->exp_obd, exp->exp_obd->u.obt.obt_sb);
2613
2614         filter_grant_discard(exp);
2615         filter_fmd_cleanup(exp);
2616
2617         if (!(exp->exp_flags & OBD_OPT_FORCE))
2618                 filter_grant_sanity_check(exp->exp_obd, __FUNCTION__);
2619
2620         RETURN(0);
2621 }
2622
2623 /* also incredibly similar to mds_disconnect */
2624 static int filter_disconnect(struct obd_export *exp)
2625 {
2626         struct obd_device *obd = exp->exp_obd;
2627         struct llog_ctxt *ctxt;
2628         int rc;
2629         ENTRY;
2630
2631         LASSERT(exp);
2632         class_export_get(exp);
2633
2634         /* Flush any remaining cancel messages out to the target */
2635         ctxt = llog_get_context(obd, LLOG_MDS_OST_REPL_CTXT);
2636         if (ctxt) {
2637                 if (ctxt->loc_imp == exp->exp_imp_reverse)
2638                         CDEBUG(D_RPCTRACE, "Reverse import disconnect\n");
2639                 llog_sync(ctxt, exp);
2640                 llog_ctxt_put(ctxt);
2641         }
2642
2643         if (exp->exp_connect_flags & OBD_CONNECT_GRANT_SHRINK) {
2644                 struct filter_obd *filter = &exp->exp_obd->u.filter;
2645                 if (filter->fo_tot_granted_clients > 0)
2646                         filter->fo_tot_granted_clients --;
2647         }
2648
2649         if (!(exp->exp_flags & OBD_OPT_FORCE))
2650                 filter_grant_sanity_check(obd, __FUNCTION__);
2651         filter_grant_discard(exp);
2652
2653         lquota_clearinfo(filter_quota_interface_ref, exp, exp->exp_obd);
2654
2655         rc = server_disconnect_export(exp);
2656
2657         class_export_put(exp);
2658         RETURN(rc);
2659 }
2660
2661 static int filter_ping(struct obd_export *exp)
2662 {
2663         filter_fmd_expire(exp);
2664
2665         if (exp->exp_delayed)
2666                 filter_update_client_epoch(exp);
2667
2668         return 0;
2669 }
2670
2671 struct dentry *__filter_oa2dentry(struct obd_device *obd, struct obdo *oa,
2672                                   const char *what, int quiet)
2673 {
2674         struct dentry *dchild = NULL;
2675
2676         if (!(oa->o_valid & OBD_MD_FLGROUP))
2677                 oa->o_gr = 0;
2678
2679         dchild = filter_fid2dentry(obd, NULL, oa->o_gr, oa->o_id);
2680
2681         if (IS_ERR(dchild)) {
2682                 CERROR("%s error looking up object: "LPU64"\n",
2683                        what, oa->o_id);
2684                 RETURN(dchild);
2685         }
2686
2687         if (dchild->d_inode == NULL) {
2688                 if (!quiet)
2689                         CERROR("%s: %s on non-existent object: "LPU64"\n",
2690                                obd->obd_name, what, oa->o_id);
2691                 f_dput(dchild);
2692                 RETURN(ERR_PTR(-ENOENT));
2693         }
2694
2695         return dchild;
2696 }
2697
2698 static int filter_getattr(struct obd_export *exp, struct obd_info *oinfo)
2699 {
2700         struct dentry *dentry = NULL;
2701         struct obd_device *obd;
2702         int rc = 0;
2703         ENTRY;
2704
2705         obd = class_exp2obd(exp);
2706         if (obd == NULL) {
2707                 CDEBUG(D_IOCTL, "invalid client export %p\n", exp);
2708                 RETURN(-EINVAL);
2709         }
2710
2711         dentry = filter_oa2dentry(obd, oinfo->oi_oa);
2712         if (IS_ERR(dentry))
2713                 RETURN(PTR_ERR(dentry));
2714
2715         /* Limit the valid bits in the return data to what we actually use */
2716         oinfo->oi_oa->o_valid = OBD_MD_FLID;
2717         obdo_from_inode(oinfo->oi_oa, dentry->d_inode, FILTER_VALID_FLAGS);
2718
2719         f_dput(dentry);
2720         RETURN(rc);
2721 }
2722
2723 /* this should be enabled/disabled in condition to enabled/disabled large
2724  * inodes (fast EAs) in backing store FS. */
2725 int filter_update_fidea(struct obd_export *exp, struct inode *inode,
2726                         void *handle, struct obdo *oa)
2727 {
2728         struct obd_device *obd = exp->exp_obd;
2729         int rc = 0;
2730         ENTRY;
2731
2732         if (oa->o_valid & OBD_MD_FLFID) {
2733                 struct filter_fid ff;
2734
2735                 if (!(oa->o_valid & OBD_MD_FLGROUP))
2736                         oa->o_gr = 0;
2737
2738                 /* packing fid and converting it to LE for storing into EA.
2739                  * Here ->o_stripe_idx should be filled by LOV and rest of
2740                  * fields - by client. */
2741                 ff.ff_fid.id = cpu_to_le64(oa->o_fid);
2742                 ff.ff_fid.f_type = cpu_to_le32(oa->o_stripe_idx);
2743                 ff.ff_fid.generation = cpu_to_le32(oa->o_generation);
2744                 ff.ff_objid = cpu_to_le64(oa->o_id);
2745                 ff.ff_group = cpu_to_le64(oa->o_gr);
2746
2747                 CDEBUG(D_INODE, "storing filter fid EA ("LPU64"/%u/%u"
2748                        LPU64"/"LPU64")\n", oa->o_fid, oa->o_stripe_idx,
2749                        oa->o_generation, oa->o_id, oa->o_gr);
2750
2751                 rc = fsfilt_set_md(obd, inode, handle, &ff, sizeof(ff), "fid");
2752                 if (rc)
2753                         CERROR("store fid in object failed! rc: %d\n", rc);
2754         } else {
2755                 CDEBUG(D_HA, "OSS object without fid info!\n");
2756         }
2757
2758         RETURN(rc);
2759 }
2760
2761 /* this is called from filter_truncate() until we have filter_punch() */
2762 int filter_setattr_internal(struct obd_export *exp, struct dentry *dentry,
2763                             struct obdo *oa, struct obd_trans_info *oti)
2764 {
2765         unsigned int orig_ids[MAXQUOTAS] = {0, 0};
2766         struct llog_cookie *fcc = NULL;
2767         struct filter_obd *filter;
2768         int rc, err, sync = 0;
2769         loff_t old_size = 0;
2770         unsigned int ia_valid;
2771         struct inode *inode;
2772         struct page *page = NULL;
2773         struct iattr iattr;
2774         void *handle;
2775         ENTRY;
2776
2777         LASSERT(dentry != NULL);
2778         LASSERT(!IS_ERR(dentry));
2779
2780         inode = dentry->d_inode;
2781         LASSERT(inode != NULL);
2782
2783         filter = &exp->exp_obd->u.filter;
2784         iattr_from_obdo(&iattr, oa, oa->o_valid);
2785         ia_valid = iattr.ia_valid;
2786
2787         if (oa->o_valid & OBD_MD_FLCOOKIE) {
2788                 OBD_ALLOC(fcc, sizeof(*fcc));
2789                 if (fcc != NULL)
2790                         *fcc = oa->o_lcookie;
2791         }
2792         if (ia_valid & (ATTR_SIZE | ATTR_UID | ATTR_GID)) {
2793                 DQUOT_INIT(inode);
2794                 /* Filter truncates and writes are serialized by
2795                  * i_alloc_sem, see the comment in
2796                  * filter_preprw_write.*/
2797                 if (ia_valid & ATTR_SIZE)
2798                         down_write(&inode->i_alloc_sem);
2799                 LOCK_INODE_MUTEX(inode);
2800                 old_size = i_size_read(inode);
2801         }
2802
2803         /* VBR: version recovery check */
2804         rc = filter_version_get_check(exp, oti, inode);
2805         if (rc)
2806                 GOTO(out_unlock, rc);
2807
2808         /* Let's pin the last page so that ldiskfs_truncate
2809          * should not start GFP_FS allocation (20008). */
2810         if (ia_valid & ATTR_SIZE) {
2811                 page = grab_cache_page(inode->i_mapping,
2812                                        iattr.ia_size >> PAGE_CACHE_SHIFT);
2813                 if (page == NULL)
2814                         GOTO(out_unlock, rc = -ENOMEM);
2815
2816                 unlock_page(page);
2817         }
2818
2819         /* If the inode still has SUID+SGID bits set (see filter_precreate())
2820          * then we will accept the UID+GID sent by the client during write for
2821          * initializing the ownership of this inode.  We only allow this to
2822          * happen once so clear these bits in setattr. In 2.6 kernels it is
2823          * possible to get ATTR_UID and ATTR_GID separately, so we only clear
2824          * the flags that are actually being set. */
2825         if (ia_valid & (ATTR_UID | ATTR_GID)) {
2826                 CDEBUG(D_INODE, "update UID/GID to %lu/%lu\n",
2827                        (unsigned long)oa->o_uid, (unsigned long)oa->o_gid);
2828
2829                 if ((inode->i_mode & S_ISUID) && (ia_valid & ATTR_UID)) {
2830                         if (!(ia_valid & ATTR_MODE)) {
2831                                 iattr.ia_mode = inode->i_mode;
2832                                 iattr.ia_valid |= ATTR_MODE;
2833                         }
2834                         iattr.ia_mode &= ~S_ISUID;
2835                 }
2836                 if ((inode->i_mode & S_ISGID) && (ia_valid & ATTR_GID)) {
2837                         if (!(iattr.ia_valid & ATTR_MODE)) {
2838                                 iattr.ia_mode = inode->i_mode;
2839                                 iattr.ia_valid |= ATTR_MODE;
2840                         }
2841                         iattr.ia_mode &= ~S_ISGID;
2842                 }
2843
2844                 orig_ids[USRQUOTA] = inode->i_uid;
2845                 orig_ids[GRPQUOTA] = inode->i_gid;
2846                 handle = fsfilt_start_log(exp->exp_obd, inode,
2847                                           FSFILT_OP_SETATTR, oti, 1);
2848
2849                 if (IS_ERR(handle))
2850                         GOTO(out_unlock, rc = PTR_ERR(handle));
2851
2852                 /* update inode EA only once when inode is suid bit marked. As
2853                  * on 2.6.x UID and GID may be set separately, we check here
2854                  * only one of them to avoid double setting. */
2855                 if (inode->i_mode & S_ISUID)
2856                         filter_update_fidea(exp, inode, handle, oa);
2857         } else {
2858                 handle = fsfilt_start(exp->exp_obd, inode,
2859                                       FSFILT_OP_SETATTR, oti);
2860
2861                 if (IS_ERR(handle))
2862                         GOTO(out_unlock, rc = PTR_ERR(handle));
2863         }
2864
2865         if (oa->o_valid & OBD_MD_FLFLAGS) {
2866                 rc = fsfilt_iocontrol(exp->exp_obd, dentry,
2867                                       FSFILT_IOC_SETFLAGS, (long)&oa->o_flags);
2868         } else {
2869                 rc = fsfilt_setattr(exp->exp_obd, dentry, handle, &iattr, 1);
2870                 if (fcc != NULL)
2871                         /* set cancel cookie callback function */
2872                         sync = fsfilt_add_journal_cb(exp->exp_obd, 0, handle,
2873                                                      filter_cancel_cookies_cb,
2874                                                      fcc);
2875         }
2876
2877         if (OBD_FAIL_CHECK(OBD_FAIL_OST_SETATTR_CREDITS))
2878                 fsfilt_extend(exp->exp_obd, inode, 0, handle);
2879
2880         /* The truncate might have used up our transaction credits.  Make
2881          * sure we have one left for the last_rcvd update. */
2882         err = fsfilt_extend(exp->exp_obd, inode, 1, handle);
2883         rc = filter_finish_transno(exp, inode, oti, rc, sync);
2884         if (sync) {
2885                 filter_cancel_cookies_cb(exp->exp_obd, 0, fcc, rc);
2886                 fcc = NULL;
2887         }
2888
2889         err = fsfilt_commit(exp->exp_obd, inode, handle, 0);
2890         if (err) {
2891                 CERROR("error on commit, err = %d\n", err);
2892                 if (!rc)
2893                         rc = err;
2894         } else {
2895                 fcc = NULL;
2896         }
2897
2898         /* For a partial-page truncate flush the page to disk immediately
2899          * to avoid data corruption during direct disk write. b=17397 */
2900         if (!sync && (iattr.ia_valid & ATTR_SIZE) &&
2901             old_size != iattr.ia_size && (iattr.ia_size & ~CFS_PAGE_MASK)) {
2902                 err = filemap_fdatawrite_range(inode->i_mapping, iattr.ia_size,
2903                                                iattr.ia_size + 1);
2904                 if (!rc)
2905                         rc = err;
2906         }
2907
2908         EXIT;
2909
2910 out_unlock:
2911         if (page)
2912                 page_cache_release(page);
2913
2914         if (ia_valid & (ATTR_SIZE | ATTR_UID | ATTR_GID))
2915                 UNLOCK_INODE_MUTEX(inode);
2916         if (ia_valid & ATTR_SIZE)
2917                 up_write(&inode->i_alloc_sem);
2918         if (fcc)
2919                 OBD_FREE(fcc, sizeof(*fcc));
2920
2921         /* trigger quota release */
2922         if (ia_valid & (ATTR_SIZE | ATTR_UID | ATTR_GID)) {
2923                 unsigned int cur_ids[MAXQUOTAS] = {oa->o_uid, oa->o_gid};
2924                 int rc2 = lquota_adjust(filter_quota_interface_ref,exp->exp_obd,
2925                                         cur_ids, orig_ids,rc,FSFILT_OP_SETATTR);
2926                 CDEBUG(rc2 ? D_ERROR : D_QUOTA,
2927                        "filter adjust qunit. (rc:%d)\n", rc2);
2928         }
2929         return rc;
2930 }
2931
2932 /* this is called from filter_truncate() until we have filter_punch() */
2933 int filter_setattr(struct obd_export *exp, struct obd_info *oinfo,
2934                    struct obd_trans_info *oti)
2935 {
2936         struct ldlm_res_id res_id = { .name = { oinfo->oi_oa->o_id } };
2937         struct filter_mod_data *fmd;
2938         struct lvfs_run_ctxt saved;
2939         struct filter_obd *filter;
2940         struct ldlm_resource *res;
2941         struct dentry *dentry;
2942         int rc = 0;
2943         ENTRY;
2944
2945         dentry = __filter_oa2dentry(exp->exp_obd, oinfo->oi_oa,
2946                                     __FUNCTION__, 1);
2947         if (IS_ERR(dentry))
2948                 RETURN(PTR_ERR(dentry));
2949
2950         filter = &exp->exp_obd->u.filter;
2951         push_ctxt(&saved, &exp->exp_obd->obd_lvfs_ctxt, NULL);
2952
2953         if (oinfo->oi_oa->o_valid &
2954             (OBD_MD_FLMTIME | OBD_MD_FLATIME | OBD_MD_FLCTIME)) {
2955                 fmd = filter_fmd_get(exp,oinfo->oi_oa->o_id,oinfo->oi_oa->o_gr);
2956                 if (fmd && fmd->fmd_mactime_xid < oti->oti_xid)
2957                         fmd->fmd_mactime_xid = oti->oti_xid;
2958                 filter_fmd_put(exp, fmd);
2959         }
2960
2961         /* setting objects attributes (including owner/group) */
2962         rc = filter_setattr_internal(exp, dentry, oinfo->oi_oa, oti);
2963         if (rc)
2964                 GOTO(out_unlock, rc);
2965
2966         res = ldlm_resource_get(exp->exp_obd->obd_namespace, NULL,
2967                                 res_id, LDLM_EXTENT, 0);
2968
2969         if (res != NULL) {
2970                 rc = ldlm_res_lvbo_update(res, NULL, 0, 0);
2971                 ldlm_resource_putref(res);
2972         }
2973
2974         oinfo->oi_oa->o_valid = OBD_MD_FLID;
2975
2976         /* Quota release need uid/gid info */
2977         obdo_from_inode(oinfo->oi_oa, dentry->d_inode,
2978                         FILTER_VALID_FLAGS | OBD_MD_FLUID | OBD_MD_FLGID);
2979
2980         EXIT;
2981 out_unlock:
2982         f_dput(dentry);
2983         pop_ctxt(&saved, &exp->exp_obd->obd_lvfs_ctxt, NULL);
2984         return rc;
2985 }
2986
2987 /* XXX identical to osc_unpackmd */
2988 static int filter_unpackmd(struct obd_export *exp, struct lov_stripe_md **lsmp,
2989                            struct lov_mds_md *lmm, int lmm_bytes)
2990 {
2991         int lsm_size;
2992         ENTRY;
2993
2994         if (lmm != NULL) {
2995                 if (lmm_bytes < sizeof (*lmm)) {
2996                         CERROR("lov_mds_md too small: %d, need %d\n",
2997                                lmm_bytes, (int)sizeof(*lmm));
2998                         RETURN(-EINVAL);
2999                 }
3000                 /* XXX LOV_MAGIC etc check? */
3001
3002                 if (lmm->lmm_object_id == cpu_to_le64(0)) {
3003                         CERROR("lov_mds_md: zero lmm_object_id\n");
3004                         RETURN(-EINVAL);
3005                 }
3006         }
3007
3008         lsm_size = lov_stripe_md_size(1);
3009         if (lsmp == NULL)
3010                 RETURN(lsm_size);
3011
3012         if (*lsmp != NULL && lmm == NULL) {
3013                 OBD_FREE((*lsmp)->lsm_oinfo[0], sizeof(struct lov_oinfo));
3014                 OBD_FREE(*lsmp, lsm_size);
3015                 *lsmp = NULL;
3016                 RETURN(0);
3017         }
3018
3019         if (*lsmp == NULL) {
3020                 OBD_ALLOC(*lsmp, lsm_size);
3021                 if (*lsmp == NULL)
3022                         RETURN(-ENOMEM);
3023                 OBD_ALLOC((*lsmp)->lsm_oinfo[0], sizeof(struct lov_oinfo));
3024                 if ((*lsmp)->lsm_oinfo[0] == NULL) {
3025                         OBD_FREE(*lsmp, lsm_size);
3026                         RETURN(-ENOMEM);
3027                 }
3028                 loi_init((*lsmp)->lsm_oinfo[0]);
3029         }
3030
3031         if (lmm != NULL) {
3032                 /* XXX zero *lsmp? */
3033                 (*lsmp)->lsm_object_id = le64_to_cpu (lmm->lmm_object_id);
3034                 LASSERT((*lsmp)->lsm_object_id);
3035         }
3036
3037         (*lsmp)->lsm_maxbytes = LUSTRE_STRIPE_MAXBYTES;
3038
3039         RETURN(lsm_size);
3040 }
3041
3042 /* caller must hold fo_create_lock */
3043 static int filter_destroy_precreated(struct obd_export *exp, struct obdo *oa,
3044                                      struct filter_obd *filter)
3045 {
3046         struct obdo doa = { 0 }; /* XXX obdo on stack */
3047         obd_id last, id;
3048         int rc = 0;
3049         int skip_orphan;
3050         ENTRY;
3051
3052         LASSERT(oa);
3053         LASSERT(down_trylock(&filter->fo_create_lock) != 0);
3054
3055         memset(&doa, 0, sizeof(doa));
3056         if (oa->o_valid & OBD_MD_FLGROUP) {
3057                 doa.o_valid |= OBD_MD_FLGROUP;
3058                 doa.o_gr = oa->o_gr;
3059         } else {
3060                 doa.o_gr = 0;
3061         }
3062         doa.o_mode = S_IFREG;
3063
3064         if (!filter->fo_destroy_in_progress) {
3065                 CERROR("%s: destroy_in_progress already cleared\n",
3066                         exp->exp_obd->obd_name);
3067                 RETURN(0);
3068         }
3069
3070         last = filter_last_id(filter, doa.o_gr);
3071         skip_orphan = !!(exp->exp_connect_flags & OBD_CONNECT_SKIP_ORPHAN);
3072
3073         CWARN("%s: deleting orphan objects from "LPU64" to "LPU64"%s\n",
3074                exp->exp_obd->obd_name, oa->o_id + 1, last,
3075                skip_orphan ? ", orphan objids won't be reused any more." : ".");
3076
3077         for (id = last; id > oa->o_id; id--) {
3078                 doa.o_id = id;
3079                 rc = filter_destroy(exp, &doa, NULL, NULL, NULL);
3080                 if (rc && rc != -ENOENT) /* this is pretty fatal... */
3081                         CEMERG("error destroying precreate objid "LPU64": %d\n",
3082                                id, rc);
3083                 /* update last_id on disk periodically so that if we restart
3084                  * we don't need to re-scan all of the just-deleted objects. */
3085                 if ((id & 511) == 0 && !skip_orphan) {
3086                         filter_set_last_id(filter, id - 1, doa.o_gr);
3087                         filter_update_last_objid(exp->exp_obd, doa.o_gr, 0);
3088                 }
3089         }
3090
3091         CDEBUG(D_HA, "%s: after destroy: set last_objids["LPU64"] = "LPU64"\n",
3092                exp->exp_obd->obd_name, doa.o_gr, oa->o_id);
3093
3094         if (!skip_orphan) {
3095                 filter_set_last_id(filter, id, doa.o_gr);
3096                 rc = filter_update_last_objid(exp->exp_obd, doa.o_gr, 1);
3097         } else {
3098                 /* don't reuse orphan object, return last used objid */
3099                 oa->o_id = last;
3100                 rc = 0;
3101         }
3102         filter->fo_destroy_in_progress = 0;
3103
3104         RETURN(rc);
3105 }
3106
3107 static int filter_precreate(struct obd_device *obd, struct obdo *oa,
3108                             obd_gr group, int *num);
3109 /* returns a negative error or a nonnegative number of files to create */
3110 static int filter_handle_precreate(struct obd_export *exp, struct obdo *oa,
3111                                    obd_gr group, struct obd_trans_info *oti)
3112 {
3113         struct obd_device *obd = exp->exp_obd;
3114         struct filter_obd *filter = &obd->u.filter;
3115         int diff, rc;
3116         ENTRY;
3117
3118         /* delete orphans request */
3119         if ((oa->o_valid & OBD_MD_FLFLAGS) && (oa->o_flags & OBD_FL_DELORPHAN)){
3120                 if (oti->oti_conn_cnt < exp->exp_conn_cnt) {
3121                         CERROR("%s: dropping old orphan cleanup request\n",
3122                                obd->obd_name);
3123                         RETURN(0);
3124                 }
3125
3126                 /* This causes inflight precreates to abort and drop lock */
3127                 filter->fo_destroy_in_progress = 1;
3128                 down(&filter->fo_create_lock);
3129                 diff = oa->o_id - filter_last_id(filter, group);
3130                 CDEBUG(D_HA, "filter_last_id() = "LPU64" -> diff = %d\n",
3131                        filter_last_id(filter, group), diff);
3132
3133                 if (-diff > OST_MAX_PRECREATE) {
3134                         CERROR("%s: ignoring bogus orphan destroy request: "
3135                                "obdid "LPU64" last_id "LPU64"\n", obd->obd_name,
3136                                oa->o_id, filter_last_id(filter, group));
3137                         /* FIXME: should reset precreate_next_id on MDS */
3138                         GOTO(out, rc = -EINVAL);
3139                 }
3140                 if (diff < 0) {
3141                         rc = filter_destroy_precreated(exp, oa, filter);
3142                         if (rc)
3143                                 CERROR("%s: unable to write lastobjid, but "
3144                                        "orphans were deleted\n", obd->obd_name);
3145                         GOTO(out, rc);
3146                 } else {
3147                         /*XXX used by MDS for the first time! */
3148                         filter->fo_destroy_in_progress = 0;
3149                 }
3150         } else {
3151                 down(&filter->fo_create_lock);
3152                 if (oti->oti_conn_cnt < exp->exp_conn_cnt) {
3153                         CERROR("%s: dropping old precreate request\n",
3154                                obd->obd_name);
3155                         GOTO(out, rc = 0);
3156                 }
3157                 /* only precreate if group == 0 and o_id is specfied */
3158                 if (group != 0 || oa->o_id == 0)
3159                         diff = 1;
3160                 else
3161                         diff = oa->o_id - filter_last_id(filter, group);
3162                 CDEBUG(D_RPCTRACE, "filter_last_id() = "LPU64" -> diff = %d\n",
3163                        filter_last_id(filter, group), diff);
3164
3165                 LASSERTF(diff >= 0,"%s: "LPU64" - "LPU64" = %d\n",obd->obd_name,
3166                          oa->o_id, filter_last_id(filter, group), diff);
3167         }
3168
3169         if (diff > 0) {
3170                 oa->o_id = filter_last_id(&obd->u.filter, group);
3171                 rc = filter_precreate(obd, oa, group, &diff);
3172                 oa->o_id = filter_last_id(&obd->u.filter, group);
3173                 oa->o_valid = OBD_MD_FLID;
3174                 GOTO(out, rc);
3175         }
3176         /* else diff == 0 */
3177         GOTO(out, rc = 0);
3178 out:
3179         up(&filter->fo_create_lock);
3180         return rc;
3181 }
3182
3183 static int filter_statfs(struct obd_device *obd, struct obd_statfs *osfs,
3184                          __u64 max_age, __u32 flags)
3185 {
3186         struct filter_obd *filter = &obd->u.filter;
3187         int blockbits = obd->u.obt.obt_sb->s_blocksize_bits;
3188         int rc;
3189         ENTRY;
3190
3191         /* at least try to account for cached pages.  its still racey and
3192          * might be under-reporting if clients haven't announced their
3193          * caches with brw recently */
3194         spin_lock(&obd->obd_osfs_lock);
3195         rc = fsfilt_statfs(obd, obd->u.obt.obt_sb, max_age);
3196         memcpy(osfs, &obd->obd_osfs, sizeof(*osfs));
3197         spin_unlock(&obd->obd_osfs_lock);
3198
3199         CDEBUG(D_SUPER | D_CACHE, "blocks cached "LPU64" granted "LPU64
3200                " pending "LPU64" free "LPU64" avail "LPU64"\n",
3201                filter->fo_tot_dirty, filter->fo_tot_granted,
3202                filter->fo_tot_pending,
3203                osfs->os_bfree << blockbits, osfs->os_bavail << blockbits);
3204
3205         filter_grant_sanity_check(obd, __FUNCTION__);
3206
3207         osfs->os_bavail -= min(osfs->os_bavail, GRANT_FOR_LLOG(obd) +
3208                                ((filter->fo_tot_dirty + filter->fo_tot_pending +
3209                                  osfs->os_bsize - 1) >> blockbits));
3210
3211         if (OBD_FAIL_CHECK(OBD_FAIL_OST_ENOSPC)) {
3212                 struct lr_server_data *lsd = filter->fo_fsd;
3213                 int index = le32_to_cpu(lsd->lsd_ost_index);
3214
3215                 if (obd_fail_val == -1 ||
3216                     index == obd_fail_val)
3217                         osfs->os_bfree = osfs->os_bavail = 2;
3218                 else if (obd_fail_loc & OBD_FAIL_ONCE)
3219                         obd_fail_loc &= ~OBD_FAILED; /* reset flag */
3220         }
3221
3222         /* set EROFS to state field if FS is mounted as RDONLY. The goal is to
3223          * stop creating files on MDS if OST is not good shape to create
3224          * objects.*/
3225         osfs->os_state = 0;
3226
3227         if (filter->fo_obt.obt_sb->s_flags & MS_RDONLY)
3228                 osfs->os_state = OS_STATE_READONLY;
3229
3230         if (filter->fo_raid_degraded)
3231                 osfs->os_state |= OS_STATE_DEGRADED;
3232         RETURN(rc);
3233 }
3234
3235 static int filter_use_existing_obj(struct obd_device *obd,
3236                                    struct dentry *dchild, void **handle,
3237                                    int *cleanup_phase)
3238 {
3239         struct inode *inode = dchild->d_inode;
3240         struct iattr iattr;
3241         int rc;
3242
3243         if ((inode->i_mode & (S_ISUID | S_ISGID)) == (S_ISUID|S_ISGID))
3244                 return 0;
3245
3246         *handle = fsfilt_start_log(obd, inode, FSFILT_OP_SETATTR, NULL, 1);
3247         if (IS_ERR(*handle))
3248                 return PTR_ERR(*handle);
3249
3250         iattr.ia_valid = ATTR_MODE;
3251         iattr.ia_mode = S_ISUID | S_ISGID |0666;
3252         rc = fsfilt_setattr(obd, dchild, *handle, &iattr, 1);
3253         if (rc == 0)
3254                 *cleanup_phase = 3;
3255
3256         return rc;
3257 }
3258
3259
3260 /* We rely on the fact that only one thread will be creating files in a given
3261  * group at a time, which is why we don't need an atomic filter_get_new_id.
3262  * Even if we had that atomic function, the following race would exist:
3263  *
3264  * thread 1: gets id x from filter_next_id
3265  * thread 2: gets id (x + 1) from filter_next_id
3266  * thread 2: creates object (x + 1)
3267  * thread 1: tries to create object x, gets -ENOSPC
3268  *
3269  * Caller must hold fo_create_lock
3270  */
3271 static int filter_precreate(struct obd_device *obd, struct obdo *oa,
3272                             obd_gr group, int *num)
3273 {
3274         struct dentry *dchild = NULL, *dparent = NULL;
3275         struct filter_obd *filter;
3276         int err = 0, rc = 0, recreate_obj = 0, i;
3277         cfs_time_t enough_time = cfs_time_shift(DISK_TIMEOUT/2);
3278         obd_id next_id;
3279         void *handle = NULL;
3280         ENTRY;
3281
3282         filter = &obd->u.filter;
3283
3284         LASSERT(down_trylock(&filter->fo_create_lock) != 0);
3285
3286         OBD_FAIL_TIMEOUT(OBD_FAIL_TGT_DELAY_PRECREATE, obd_timeout / 2);
3287
3288         if ((oa->o_valid & OBD_MD_FLFLAGS) &&
3289             (oa->o_flags & OBD_FL_RECREATE_OBJS)) {
3290                 recreate_obj = 1;
3291         } else {
3292                 struct obd_statfs *osfs;
3293
3294                 OBD_ALLOC(osfs, sizeof(*osfs));
3295                 if (osfs == NULL)
3296                         RETURN(-ENOMEM);
3297                 rc = filter_statfs(obd, osfs, cfs_time_current_64() - HZ, 0);
3298                 if (rc == 0 && osfs->os_bavail < (osfs->os_blocks >> 10)) {
3299                         CDEBUG(D_RPCTRACE,"%s: not enough space for create "
3300                                LPU64"\n", obd->obd_name, osfs->os_bavail <<
3301                                filter->fo_vfsmnt->mnt_sb->s_blocksize_bits);
3302                         *num = 0;
3303                         rc = -ENOSPC;
3304                 }
3305                 OBD_FREE(osfs, sizeof(*osfs));
3306                 if (rc)
3307                         RETURN(rc);
3308         }
3309
3310         CDEBUG(D_RPCTRACE, "%s: precreating %d objects in group "LPU64
3311                " at "LPU64"\n", obd->obd_name, *num, group, oa->o_id);
3312
3313         for (i = 0; i < *num && err == 0; i++) {
3314                 int cleanup_phase = 0;
3315
3316                 if (recreate_obj) {
3317                         __u64 last_id;
3318                         next_id = oa->o_id;
3319                         last_id = filter_last_id(filter, group);
3320                         if (next_id > last_id) {
3321                                 CERROR("%s: trying to recreate obj greater"
3322                                        "than last id "LPD64" > "LPD64"\n",
3323                                        obd->obd_name, next_id, last_id);
3324                                 GOTO(cleanup, rc = -EINVAL);
3325                         }
3326                 } else if (filter->fo_destroy_in_progress) {
3327                         CWARN("%s: precreate aborted by destroy\n",
3328                               obd->obd_name);
3329                         rc = -EAGAIN;
3330                         break;
3331                 } else
3332                         next_id = filter_last_id(filter, group) + 1;
3333
3334                 dparent = filter_parent_lock(obd, group, next_id);
3335                 if (IS_ERR(dparent))
3336                         GOTO(cleanup, rc = PTR_ERR(dparent));
3337                 cleanup_phase = 1;      /* filter_parent_unlock(dparent) */
3338
3339                 dchild = filter_fid2dentry(obd, dparent, group, next_id);
3340                 if (IS_ERR(dchild))
3341                         GOTO(cleanup, rc = PTR_ERR(dchild));
3342                 cleanup_phase = 2;      /* f_dput(dchild) */
3343
3344                 if (dchild->d_inode != NULL) {
3345                         /* This would only happen if lastobjid was bad on disk*/
3346                         /* Could also happen if recreating missing obj but it
3347                          * already exists. */
3348                         if (recreate_obj) {
3349                                 CERROR("%s: recreating existing object %.*s?\n",
3350                                        obd->obd_name, dchild->d_name.len,
3351                                        dchild->d_name.name);
3352                         } else {
3353                                 /* Use these existing objects if they are
3354                                  * zero length. */
3355                                 if (dchild->d_inode->i_size == 0) {
3356                                         rc = filter_use_existing_obj(obd,dchild,
3357                                                       &handle, &cleanup_phase);
3358                                         if (rc == 0)
3359                                                 goto set_last_id;
3360                                         else
3361                                                 GOTO(cleanup, rc);
3362                                 }
3363
3364                                 CERROR("%s: Serious error: objid %.*s already "
3365                                        "exists; is this filesystem corrupt?\n",
3366                                        obd->obd_name, dchild->d_name.len,
3367                                        dchild->d_name.name);
3368                                 LBUG();
3369                         }
3370                         GOTO(cleanup, rc = -EEXIST);
3371                 }
3372
3373                 handle = fsfilt_start_log(obd, dparent->d_inode,
3374                                           FSFILT_OP_CREATE, NULL, 1);
3375                 if (IS_ERR(handle))
3376                         GOTO(cleanup, rc = PTR_ERR(handle));
3377                 cleanup_phase = 3;
3378
3379                 CDEBUG(D_INODE, "%s: filter_precreate(od->o_gr="LPU64
3380                        ",od->o_id="LPU64")\n", obd->obd_name, group,
3381                        next_id);
3382
3383                 /* We mark object SUID+SGID to flag it for accepting UID+GID
3384                  * from client on first write.  Currently the permission bits
3385                  * on the OST are never used, so this is OK. */
3386                 rc = ll_vfs_create(dparent->d_inode, dchild,
3387                                    S_IFREG |  S_ISUID | S_ISGID | 0666, NULL);
3388                 if (rc) {
3389                         CERROR("create failed rc = %d\n", rc);
3390                         GOTO(cleanup, rc);
3391                 }
3392                 if (dchild->d_inode)
3393                         CDEBUG(D_INFO, "objid "LPU64" got inum %lu\n", next_id,
3394                                        dchild->d_inode->i_ino);
3395
3396 set_last_id:
3397                 if (!recreate_obj) {
3398                         filter_set_last_id(filter, next_id, group);
3399                         err = filter_update_last_objid(obd, group, 0);
3400                         if (err)
3401                                 CERROR("unable to write lastobjid "
3402                                        "but file created\n");
3403                 }
3404
3405         cleanup:
3406                 switch(cleanup_phase) {
3407                 case 3:
3408                         err = fsfilt_commit(obd, dparent->d_inode, handle, 0);
3409                         if (err) {
3410                                 CERROR("error on commit, err = %d\n", err);
3411                                 if (!rc)
3412                                         rc = err;
3413                         }
3414                 case 2:
3415                         f_dput(dchild);
3416                 case 1:
3417                         filter_parent_unlock(dparent);
3418                 case 0:
3419                         break;
3420                 }
3421
3422                 if (rc)
3423                         break;
3424                 if (cfs_time_after(cfs_time_current(), enough_time)) {
3425                         CDEBUG(D_RPCTRACE,
3426                                "%s: precreate slow - want %d got %d \n",
3427                                obd->obd_name, *num, i);
3428                         break;
3429                 }
3430         }
3431         *num = i;
3432
3433         CDEBUG(D_RPCTRACE,
3434                "%s: created %d objects for group "LPU64": "LPU64" rc %d\n",
3435                obd->obd_name, i, group, filter->fo_last_objids[group], rc);
3436
3437         RETURN(rc);
3438 }
3439
3440 int filter_recreate(struct obd_device *obd, struct obdo *oa)
3441 {
3442         struct ldlm_res_id res_id = { .name = { oa->o_id } };
3443         struct ldlm_valblock_ops *ns_lvbo;
3444         struct ldlm_resource *res;
3445         obd_valid old_valid = oa->o_valid;
3446         obd_flag old_flags = oa->o_flags;
3447         int diff = 1, rc;
3448         ENTRY;
3449
3450         if (oa->o_id > filter_last_id(&obd->u.filter, oa->o_gr)) {
3451                 if (!obd->obd_recovering ||
3452                     oa->o_id > filter_last_id(&obd->u.filter, oa->o_gr) +
3453                     OST_MAX_PRECREATE) {
3454                         CERROR("recreate objid "LPU64" > last id "LPU64"\n",
3455                                oa->o_id, filter_last_id(&obd->u.filter,
3456                                oa->o_gr));
3457                         RETURN(-EINVAL);
3458                 }
3459                 diff = oa->o_id - filter_last_id(&obd->u.filter, oa->o_gr);
3460         } else {
3461                 if ((oa->o_valid & OBD_MD_FLFLAGS) == 0) {
3462                         oa->o_valid |= OBD_MD_FLFLAGS;
3463                         oa->o_flags = OBD_FL_RECREATE_OBJS;
3464                 } else {
3465                         oa->o_flags |= OBD_FL_RECREATE_OBJS;
3466                 }
3467         }
3468
3469         down(&obd->u.filter.fo_create_lock);
3470         rc = filter_precreate(obd, oa, oa->o_gr, &diff);
3471         up(&obd->u.filter.fo_create_lock);
3472
3473         res = ldlm_resource_get(obd->obd_namespace, NULL,
3474                                 res_id, LDLM_EXTENT, 0);
3475         if (res != NULL) {
3476                 /* Update lvb->lvb_blocks for the recreated object */
3477                 ns_lvbo = res->lr_namespace->ns_lvbo;
3478                 if (ns_lvbo && ns_lvbo->lvbo_update) {
3479                         rc = ns_lvbo->lvbo_update(res, NULL, 0, 1);
3480                         if (rc)
3481                                 RETURN(rc);
3482                 }
3483                 ldlm_resource_putref(res);
3484         }
3485
3486         if (rc == 0)
3487                 CWARN("%s: recreated missing object "LPU64"/"LPU64"\n",
3488                       obd->obd_name, oa->o_id, oa->o_gr);
3489
3490         oa->o_valid = old_valid;
3491         oa->o_flags = old_flags;
3492         RETURN(rc);
3493 }
3494
3495 static int filter_create(struct obd_export *exp, struct obdo *oa,
3496                          struct lov_stripe_md **ea, struct obd_trans_info *oti)
3497 {
3498         struct obd_device *obd = exp->exp_obd;
3499         struct lvfs_run_ctxt saved;
3500         struct lov_stripe_md *lsm = NULL;
3501         struct ldlm_res_id res_id = { .name = { oa->o_id } };
3502         ldlm_policy_data_t policy = { .l_extent = { 0, OBD_OBJECT_EOF } };
3503         struct lustre_handle lockh;
3504         int flags = 0;
3505         int rc = 0;
3506         ENTRY;
3507
3508         CDEBUG(D_INODE, "%s: filter_create(od->o_gr="LPU64",od->o_id="
3509                LPU64")\n", obd->obd_name, oa->o_gr, oa->o_id);
3510
3511         if (!(oa->o_valid & OBD_MD_FLGROUP))
3512                 oa->o_gr = 0;
3513
3514         CDEBUG(D_INFO, "object "LPU64"/"LPU64"\n", oa->o_id, oa->o_gr);
3515         if (ea != NULL) {
3516                 lsm = *ea;
3517                 if (lsm == NULL) {
3518                         rc = obd_alloc_memmd(exp, &lsm);
3519                         if (rc < 0)
3520                                 RETURN(rc);
3521                 }
3522         }
3523
3524         push_ctxt(&saved, &obd->obd_lvfs_ctxt, NULL);
3525
3526         if ((oa->o_valid & OBD_MD_FLFLAGS) &&
3527             (oa->o_flags & OBD_FL_RECREATE_OBJS)) {
3528                 /* Cancel all conflicting extent locks on recreating object,
3529                  * thus object's metadata will be updated on the clients */
3530                 rc = ldlm_cli_enqueue_local(obd->obd_namespace, &res_id,
3531                                             LDLM_EXTENT, &policy, LCK_PW,
3532                                             &flags, ldlm_blocking_ast,
3533                                             ldlm_completion_ast,
3534                                             ldlm_glimpse_ast, NULL, 0,
3535                                             NULL, &lockh);
3536                 rc = filter_recreate(obd, oa);
3537                 ldlm_lock_decref(&lockh, LCK_PW);
3538         } else {
3539                 rc = filter_handle_precreate(exp, oa, oa->o_gr, oti);
3540         }
3541
3542         pop_ctxt(&saved, &obd->obd_lvfs_ctxt, NULL);
3543         if (rc && ea != NULL && *ea != lsm) {
3544                 obd_free_memmd(exp, &lsm);
3545         } else if (rc == 0 && ea != NULL) {
3546                 /* XXX LOV STACKING: the lsm that is passed to us from
3547                  * LOV does not have valid lsm_oinfo data structs, so
3548                  * don't go touching that.  This needs to be fixed in a
3549                  * big way. */
3550                 lsm->lsm_object_id = oa->o_id;
3551                 *ea = lsm;
3552         }
3553
3554         RETURN(rc);
3555 }
3556
3557 int filter_destroy(struct obd_export *exp, struct obdo *oa,
3558                    struct lov_stripe_md *md, struct obd_trans_info *oti,
3559                    struct obd_export *md_exp)
3560 {
3561         unsigned int qcids[MAXQUOTAS] = {0, 0};
3562         struct obd_device *obd;
3563         struct filter_obd *filter;
3564         struct dentry *dchild = NULL, *dparent = NULL;
3565         struct lustre_handle lockh = { 0 };
3566         struct lvfs_run_ctxt saved;
3567         void *handle = NULL;
3568         struct llog_cookie *fcc = NULL;
3569         int rc, rc2, cleanup_phase = 0, sync = 0;
3570         struct iattr iattr;
3571         ENTRY;
3572
3573         if (!(oa->o_valid & OBD_MD_FLGROUP))
3574                 oa->o_gr = 0;
3575
3576         obd = exp->exp_obd;
3577         filter = &obd->u.filter;
3578
3579         push_ctxt(&saved, &obd->obd_lvfs_ctxt, NULL);
3580         cleanup_phase = 1;
3581
3582         CDEBUG(D_INODE, "%s: filter_destroy(od->o_gr="LPU64",od->o_id="
3583                LPU64")\n", obd->obd_name, oa->o_gr, oa->o_id);
3584
3585         dchild = filter_fid2dentry(obd, NULL, oa->o_gr, oa->o_id);
3586         if (IS_ERR(dchild))
3587                 GOTO(cleanup, rc = PTR_ERR(dchild));
3588         cleanup_phase = 2;
3589
3590         if (dchild->d_inode == NULL) {
3591                 CDEBUG(D_INODE, "destroying non-existent object "LPU64"\n",
3592                        oa->o_id);
3593                 /* If object already gone, cancel cookie right now */
3594                 if (oa->o_valid & OBD_MD_FLCOOKIE) {
3595                         struct llog_ctxt *ctxt;
3596                         fcc = &oa->o_lcookie;
3597                         ctxt = llog_get_context(obd, fcc->lgc_subsys + 1);
3598                         llog_cancel(ctxt, NULL, 1, fcc, 0);
3599                         llog_ctxt_put(ctxt);
3600                         fcc = NULL; /* we didn't allocate fcc, don't free it */
3601                 }
3602                 GOTO(cleanup, rc = -ENOENT);
3603         }
3604
3605         rc = filter_prepare_destroy(obd, oa->o_id, &lockh);
3606         if (rc)
3607                 GOTO(cleanup, rc);
3608
3609         /* Our MDC connection is established by the MDS to us */
3610         if (oa->o_valid & OBD_MD_FLCOOKIE) {
3611                 OBD_ALLOC(fcc, sizeof(*fcc));
3612                 if (fcc != NULL)
3613                         *fcc = oa->o_lcookie;
3614         }
3615         DQUOT_INIT(dchild->d_inode);
3616
3617         /* we're gonna truncate it first in order to avoid possible deadlock:
3618          *      P1                      P2
3619          * open trasaction      open transaction
3620          * down(i_zombie)       down(i_zombie)
3621          *                      restart transaction
3622          * (see BUG 4180) -bzzz
3623          *
3624          * take i_alloc_sem too to prevent other threads from writing to the
3625          * file while we are truncating it. This can cause lock ordering issue
3626          * between page lock, i_mutex & starting new journal handle.
3627          * (see bug 20321) -johann
3628          */
3629         down_write(&dchild->d_inode->i_alloc_sem);
3630         LOCK_INODE_MUTEX(dchild->d_inode);
3631
3632         /* VBR: version recovery check */
3633         rc = filter_version_get_check(exp, oti, dchild->d_inode);
3634         if (rc) {
3635                 UNLOCK_INODE_MUTEX(dchild->d_inode);
3636                 up_write(&dchild->d_inode->i_alloc_sem);
3637                 GOTO(cleanup, rc);
3638         }
3639
3640         handle = fsfilt_start_log(obd, dchild->d_inode, FSFILT_OP_SETATTR,
3641                                   NULL, 1);
3642         if (IS_ERR(handle)) {
3643                 UNLOCK_INODE_MUTEX(dchild->d_inode);
3644                 up_write(&dchild->d_inode->i_alloc_sem);
3645                 GOTO(cleanup, rc = PTR_ERR(handle));
3646         }
3647
3648         iattr.ia_valid = ATTR_SIZE;
3649         iattr.ia_size = 0;
3650         rc = fsfilt_setattr(obd, dchild, handle, &iattr, 1);
3651         rc2 = fsfilt_commit(obd, dchild->d_inode, handle, 0);
3652         UNLOCK_INODE_MUTEX(dchild->d_inode);
3653         up_write(&dchild->d_inode->i_alloc_sem);
3654         if (rc)
3655                 GOTO(cleanup, rc);
3656         if (rc2)
3657                 GOTO(cleanup, rc = rc2);
3658
3659         /* We don't actually need to lock the parent until we are unlinking
3660          * here, and not while truncating above.  That avoids holding the
3661          * parent lock for a long time during truncate, which can block other
3662          * threads from doing anything to objects in that directory. bug 7171 */
3663         dparent = filter_parent_lock(obd, oa->o_gr, oa->o_id);
3664         if (IS_ERR(dparent))
3665                 GOTO(cleanup, rc = PTR_ERR(dparent));
3666         cleanup_phase = 3; /* filter_parent_unlock */
3667
3668         LOCK_INODE_MUTEX(dchild->d_inode);
3669         handle = fsfilt_start_log(obd, dparent->d_inode,FSFILT_OP_UNLINK,oti,1);
3670         if (IS_ERR(handle)) {
3671                 UNLOCK_INODE_MUTEX(dchild->d_inode);
3672                 GOTO(cleanup, rc = PTR_ERR(handle));
3673         }
3674         cleanup_phase = 4; /* fsfilt_commit */
3675
3676         /* Quota release need uid/gid of inode */
3677         obdo_from_inode(oa, dchild->d_inode, OBD_MD_FLUID|OBD_MD_FLGID);
3678
3679         filter_fmd_drop(exp, oa->o_id, oa->o_gr);
3680
3681         /* this drops dchild->d_inode->i_mutex unconditionally */
3682         rc = filter_destroy_internal(obd, oa->o_id, oa->o_gr, dparent, dchild);
3683
3684         EXIT;
3685 cleanup:
3686         switch(cleanup_phase) {
3687         case 4:
3688                 if (fcc != NULL)
3689                         sync = fsfilt_add_journal_cb(obd, 0, oti ?
3690                                                      oti->oti_handle : handle,
3691                                                      filter_cancel_cookies_cb,
3692                                                      fcc);
3693                 /* If add_journal_cb failed, then filter_finish_transno
3694                  * will commit the handle and we will do a sync
3695                  * on commit. then we call callback directly to free
3696                  * the fcc.
3697                  */
3698                 rc = filter_finish_transno(exp, NULL, oti, rc, sync);
3699                 if (sync) {
3700                         filter_cancel_cookies_cb(obd, 0, fcc, rc);
3701                         fcc = NULL;
3702                 }
3703                 rc2 = fsfilt_commit(obd, dparent->d_inode, handle, 0);
3704                 if (rc2) {
3705                         CERROR("error on commit, err = %d\n", rc2);
3706                         if (!rc)
3707                                 rc = rc2;
3708                 } else {
3709                         fcc = NULL;
3710                 }
3711         case 3:
3712                 filter_parent_unlock(dparent);
3713         case 2:
3714                 filter_fini_destroy(obd, &lockh);
3715
3716                 f_dput(dchild);
3717                 if (fcc != NULL)
3718                         OBD_FREE(fcc, sizeof(*fcc));
3719         case 1:
3720                 pop_ctxt(&saved, &obd->obd_lvfs_ctxt, NULL);
3721                 break;
3722         default:
3723                 CERROR("invalid cleanup_phase %d\n", cleanup_phase);
3724                 LBUG();
3725         }
3726
3727         /* trigger quota release */
3728         qcids[USRQUOTA] = oa->o_uid;
3729         qcids[GRPQUOTA] = oa->o_gid;
3730         rc2 = lquota_adjust(filter_quota_interface_ref, obd, qcids, NULL, rc,
3731                             FSFILT_OP_UNLINK);
3732         if (rc2)
3733                 CERROR("filter adjust qunit! (rc:%d)\n", rc2);
3734         return rc;
3735 }
3736
3737 /* NB start and end are used for punch, but not truncate */
3738 static int filter_truncate(struct obd_export *exp, struct obd_info *oinfo,
3739                            struct obd_trans_info *oti,
3740                            struct ptlrpc_request_set *rqset)
3741 {
3742         int rc;
3743         ENTRY;
3744
3745         if (oinfo->oi_policy.l_extent.end != OBD_OBJECT_EOF) {
3746                 CERROR("PUNCH not supported, only truncate: end = "LPX64"\n",
3747                        oinfo->oi_policy.l_extent.end);
3748                 RETURN(-EFAULT);
3749         }
3750         
3751         CDEBUG(D_INODE, "calling truncate for object "LPU64", valid = "LPX64
3752                ", o_size = "LPD64"\n", oinfo->oi_oa->o_id,
3753                oinfo->oi_oa->o_valid, oinfo->oi_policy.l_extent.start);
3754
3755         oinfo->oi_oa->o_size = oinfo->oi_policy.l_extent.start;
3756         rc = filter_setattr(exp, oinfo, oti);
3757
3758         RETURN(rc);
3759 }
3760
3761 static int filter_sync(struct obd_export *exp, struct obd_info *oinfo,
3762                        obd_off start, obd_off end,
3763                        struct ptlrpc_request_set *set)
3764 {
3765         struct lvfs_run_ctxt saved;
3766         struct filter_obd *filter;
3767         struct dentry *dentry;
3768         struct llog_ctxt *ctxt;
3769         int rc, rc2;
3770         ENTRY;
3771
3772         filter = &exp->exp_obd->u.filter;
3773
3774         /* An objid of zero is taken to mean "sync whole filesystem" */
3775         if (!oinfo->oi_oa || !(oinfo->oi_oa->o_valid & OBD_MD_FLID)) {
3776                 rc = fsfilt_sync(exp->exp_obd, filter->fo_obt.obt_sb);
3777
3778                 /* Flush any remaining cancel messages out to the target */
3779                 ctxt = llog_get_context(exp->exp_obd, LLOG_MDS_OST_REPL_CTXT);
3780                 if (ctxt) {
3781                         llog_sync(ctxt, exp);
3782                         llog_ctxt_put(ctxt);
3783                 } else {
3784                         CERROR("No LLOG_MDS_OST_REPL_CTXT found in obd %p\n",
3785                                exp->exp_obd);
3786                 }
3787                 RETURN(rc);
3788         }
3789
3790         dentry = filter_oa2dentry(exp->exp_obd, oinfo->oi_oa);
3791         if (IS_ERR(dentry))
3792                 RETURN(PTR_ERR(dentry));
3793
3794         push_ctxt(&saved, &exp->exp_obd->obd_lvfs_ctxt, NULL);
3795
3796         LOCK_INODE_MUTEX(dentry->d_inode);
3797
3798         rc = filemap_fdatawrite(dentry->d_inode->i_mapping);
3799         if (rc == 0) {
3800                 /* just any file to grab fsync method - "file" arg unused */
3801                 struct file *file = filter->fo_rcvd_filp;
3802
3803                 if (file->f_op && file->f_op->fsync)
3804                         rc = file->f_op->fsync(NULL, dentry, 1);
3805
3806                 rc2 = filemap_fdatawait(dentry->d_inode->i_mapping);
3807                 if (!rc)
3808                         rc = rc2;
3809         }
3810         UNLOCK_INODE_MUTEX(dentry->d_inode);
3811
3812         oinfo->oi_oa->o_valid = OBD_MD_FLID;
3813         obdo_from_inode(oinfo->oi_oa, dentry->d_inode, FILTER_VALID_FLAGS);
3814
3815         pop_ctxt(&saved, &exp->exp_obd->obd_lvfs_ctxt, NULL);
3816
3817         f_dput(dentry);
3818         RETURN(rc);
3819 }
3820
3821 static int filter_get_info(struct obd_export *exp, __u32 keylen,
3822                            void *key, __u32 *vallen, void *val,
3823                            struct lov_stripe_md *lsm)
3824 {
3825         struct obd_device *obd;
3826         ENTRY;
3827
3828         obd = class_exp2obd(exp);
3829         if (obd == NULL) {
3830                 CDEBUG(D_IOCTL, "invalid client export %p\n", exp);
3831                 RETURN(-EINVAL);
3832         }
3833
3834         if (KEY_IS(KEY_BLOCKSIZE)) {
3835                 __u32 *blocksize = val;
3836                 if (blocksize) {
3837                         if (*vallen < sizeof(*blocksize))
3838                                 RETURN(-EOVERFLOW);
3839                         *blocksize = obd->u.obt.obt_sb->s_blocksize;
3840                 }
3841                 *vallen = sizeof(*blocksize);
3842                 RETURN(0);
3843         }
3844
3845         if (KEY_IS(KEY_BLOCKSIZE_BITS)) {
3846                 __u32 *blocksize_bits = val;
3847                 if (blocksize_bits) {
3848                         if (*vallen < sizeof(*blocksize_bits))
3849                                 RETURN(-EOVERFLOW);
3850                         *blocksize_bits = obd->u.obt.obt_sb->s_blocksize_bits;
3851                 }
3852                 *vallen = sizeof(*blocksize_bits);
3853                 RETURN(0);
3854         }
3855
3856         if (KEY_IS(KEY_LAST_ID)) {
3857                 obd_id *last_id = val;
3858                 /* FIXME: object groups */
3859                 if (last_id) {
3860                         if (*vallen < sizeof(*last_id))
3861                                 RETURN(-EOVERFLOW);
3862                         *last_id = filter_last_id(&obd->u.filter, 0);
3863                 }
3864                 *vallen = sizeof(*last_id);
3865                 RETURN(0);
3866         }
3867
3868         if (KEY_IS(KEY_FIEMAP)) {
3869                 struct ll_fiemap_info_key *fm_key = key;
3870                 struct dentry *dentry;
3871                 struct ll_user_fiemap *fiemap = val;
3872                 struct lvfs_run_ctxt saved;
3873                 int rc;
3874
3875                 if (fiemap == NULL) {
3876                         *vallen = fiemap_count_to_size(
3877                                                 fm_key->fiemap.fm_extent_count);
3878                         RETURN(0);
3879                 }
3880
3881                 dentry = __filter_oa2dentry(exp->exp_obd, &fm_key->oa,
3882                                             __FUNCTION__, 1);
3883                 if (IS_ERR(dentry))
3884                         RETURN(PTR_ERR(dentry));
3885
3886                 memcpy(fiemap, &fm_key->fiemap, sizeof(*fiemap));
3887                 push_ctxt(&saved, &obd->obd_lvfs_ctxt, NULL);
3888
3889                 rc = fsfilt_iocontrol(obd, dentry, FSFILT_IOC_FIEMAP,
3890                                       (long)fiemap);
3891                 pop_ctxt(&saved, &obd->obd_lvfs_ctxt, NULL);
3892
3893                 f_dput(dentry);
3894                 RETURN(rc);
3895         }
3896
3897         CDEBUG(D_IOCTL, "invalid key\n");
3898         RETURN(-EINVAL);
3899 }
3900
3901 static int filter_set_info_async(struct obd_export *exp, __u32 keylen,
3902                                  void *key, __u32 vallen, void *val,
3903                                  struct ptlrpc_request_set *set)
3904 {
3905         struct obd_device *obd;
3906         struct llog_ctxt *ctxt;
3907         int rc = 0;
3908         ENTRY;
3909
3910         obd = exp->exp_obd;
3911         if (obd == NULL) {
3912                 CDEBUG(D_IOCTL, "invalid export %p\n", exp);
3913                 RETURN(-EINVAL);
3914         }
3915
3916         if (KEY_IS(KEY_GRANT_SHRINK)) {
3917                 struct ost_body *body = (struct ost_body *)val;
3918                 /* handle shrink grant */
3919                 spin_lock(&exp->exp_obd->obd_osfs_lock);
3920                 filter_grant_incoming(exp, &body->oa);
3921                 spin_unlock(&exp->exp_obd->obd_osfs_lock);
3922                 RETURN(rc);
3923         }
3924
3925         if (KEY_IS(KEY_CAPA_KEY)) {
3926                 RETURN(0);
3927         }
3928
3929         if (!KEY_IS(KEY_MDS_CONN))
3930                 RETURN(-EINVAL);
3931
3932         LCONSOLE_WARN("%s: received MDS connection from %s\n", obd->obd_name,
3933                       obd_export_nid2str(exp));
3934         obd->u.filter.fo_mdc_conn.cookie = exp->exp_handle.h_cookie;
3935
3936         /* setup llog imports */
3937         ctxt = llog_get_context(obd, LLOG_MDS_OST_REPL_CTXT);
3938         rc = llog_receptor_accept(ctxt, exp->exp_imp_reverse);
3939         llog_ctxt_put(ctxt);
3940
3941         lquota_setinfo(filter_quota_interface_ref, exp, obd);
3942
3943         RETURN(rc);
3944 }
3945
3946 int filter_iocontrol(unsigned int cmd, struct obd_export *exp,
3947                      int len, void *karg, void *uarg)
3948 {
3949         struct obd_device *obd = exp->exp_obd;
3950         struct obd_ioctl_data *data = karg;
3951         int rc = 0;
3952
3953         switch (cmd) {
3954         case OBD_IOC_ABORT_RECOVERY: {
3955                 CERROR("aborting recovery for device %s\n", obd->obd_name);
3956                 target_abort_recovery(obd);
3957                 RETURN(0);
3958         }
3959
3960         case OBD_IOC_SYNC: {
3961                 CDEBUG(D_RPCTRACE, "syncing ost %s\n", obd->obd_name);
3962                 rc = fsfilt_sync(obd, obd->u.obt.obt_sb);
3963                 RETURN(rc);
3964         }
3965
3966         case OBD_IOC_SET_READONLY: {
3967                 void *handle;
3968                 struct super_block *sb = obd->u.obt.obt_sb;
3969                 struct inode *inode = sb->s_root->d_inode;
3970                 LCONSOLE_WARN("*** setting obd %s device '%s' read-only ***\n",
3971                               obd->obd_name, sb->s_id);
3972
3973                 handle = fsfilt_start(obd, inode, FSFILT_OP_MKNOD, NULL);
3974                 if (!IS_ERR(handle))
3975                         rc = fsfilt_commit(obd, inode, handle, 1);
3976
3977                 CDEBUG(D_HA, "syncing ost %s\n", obd->obd_name);
3978                 rc = fsfilt_sync(obd, obd->u.obt.obt_sb);
3979
3980                 lvfs_set_rdonly(obd, obd->u.obt.obt_sb);
3981                 RETURN(0);
3982         }
3983
3984         case OBD_IOC_CATLOGLIST: {
3985                 rc = llog_catalog_list(obd, 1, data);
3986                 RETURN(rc);
3987         }
3988
3989         case OBD_IOC_LLOG_CANCEL:
3990         case OBD_IOC_LLOG_REMOVE:
3991         case OBD_IOC_LLOG_INFO:
3992         case OBD_IOC_LLOG_PRINT: {
3993                 /* FIXME to be finished */
3994                 RETURN(-EOPNOTSUPP);
3995 /*
3996                 struct llog_ctxt *ctxt = NULL;
3997
3998                 push_ctxt(&saved, &ctxt->loc_exp->exp_obd->obd_lvfs_ctxt, NULL);
3999                 rc = llog_ioctl(ctxt, cmd, data);
4000                 pop_ctxt(&saved, &ctxt->loc_exp->exp_obd->obd_lvfs_ctxt, NULL);
4001
4002                 RETURN(rc);
4003 */
4004         }
4005         default:
4006                 RETURN(-EINVAL);
4007         }
4008         RETURN(0);
4009 }
4010
4011 static int filter_health_check(struct obd_device *obd)
4012 {
4013 #ifdef USE_HEALTH_CHECK_WRITE
4014         struct filter_obd *filter = &obd->u.filter;
4015 #endif
4016         int rc = 0;
4017
4018         /*
4019          * health_check to return 0 on healthy
4020          * and 1 on unhealthy.
4021          */
4022         if (obd->u.obt.obt_sb->s_flags & MS_RDONLY)
4023                 rc = 1;
4024
4025 #ifdef USE_HEALTH_CHECK_WRITE
4026         LASSERT(filter->fo_obt.obt_health_check_filp != NULL);
4027         rc |= !!lvfs_check_io_health(obd, filter->fo_obt.obt_health_check_filp);
4028 #endif
4029
4030         return rc;
4031 }
4032
4033 static struct dentry *filter_lvfs_fid2dentry(__u64 id, __u32 gen, __u64 gr,
4034                                              void *data)
4035 {
4036         return filter_fid2dentry(data, NULL, gr, id);
4037 }
4038
4039 static int filter_process_config(struct obd_device *obd,obd_count len,void *buf)
4040 {
4041         struct lustre_cfg *lcfg = buf;
4042         struct lprocfs_static_vars lvars;
4043         int rc = 0;
4044
4045         lprocfs_filter_init_vars(&lvars);
4046
4047         rc = class_process_proc_param(PARAM_OST, lvars.obd_vars, lcfg, obd);
4048
4049         return(rc);
4050 }
4051
4052 static struct lvfs_callback_ops filter_lvfs_ops = {
4053         l_fid2dentry:     filter_lvfs_fid2dentry,
4054 };
4055
4056 static int filter_notify(struct obd_device *obd, struct obd_device *watched,
4057                          enum obd_notify_event ev, void *data)
4058 {
4059         ENTRY;
4060
4061         CDEBUG(D_CONFIG, "notify %s ev=%d\n", watched->obd_name, ev);
4062
4063         switch (ev) {
4064         case OBD_NOTIFY_CONFIG:
4065                 /* call this only when config is processed and stale_export_age
4066                  * value is configured */
4067                 class_disconnect_expired_exports(obd);
4068         default:
4069                 RETURN(0);
4070         }
4071 }
4072
4073 static struct obd_ops filter_obd_ops = {
4074         .o_owner          = THIS_MODULE,
4075         .o_get_info       = filter_get_info,
4076         .o_set_info_async = filter_set_info_async,
4077         .o_setup          = filter_setup,
4078         .o_precleanup     = filter_precleanup,
4079         .o_cleanup        = filter_cleanup,
4080         .o_connect        = filter_connect,
4081         .o_reconnect      = filter_reconnect,
4082         .o_disconnect     = filter_disconnect,
4083         .o_ping           = filter_ping,
4084         .o_init_export    = filter_init_export,
4085         .o_destroy_export = filter_destroy_export,
4086         .o_statfs         = filter_statfs,
4087         .o_getattr        = filter_getattr,
4088         .o_unpackmd       = filter_unpackmd,
4089         .o_create         = filter_create,
4090         .o_setattr        = filter_setattr,
4091         .o_destroy        = filter_destroy,
4092         .o_brw            = filter_brw,
4093         .o_punch          = filter_truncate,
4094         .o_sync           = filter_sync,
4095         .o_preprw         = filter_preprw,
4096         .o_commitrw       = filter_commitrw,
4097         .o_llog_init      = filter_llog_init,
4098         .o_llog_finish    = filter_llog_finish,
4099         .o_iocontrol      = filter_iocontrol,
4100         .o_health_check   = filter_health_check,
4101         .o_process_config = filter_process_config,
4102         .o_postrecov      = filter_postrecov,
4103         .o_notify         = filter_notify,
4104 };
4105
4106 quota_interface_t *filter_quota_interface_ref;
4107 extern quota_interface_t filter_quota_interface;
4108
4109 static int __init obdfilter_init(void)
4110 {
4111         struct lprocfs_static_vars lvars;
4112         int rc;
4113
4114         printk(KERN_INFO "Lustre: Filtering OBD driver; http://www.lustre.org/\n");
4115
4116         lprocfs_filter_init_vars(&lvars);
4117
4118         request_module("lquota");
4119         OBD_ALLOC(obdfilter_created_scratchpad,
4120                   OBDFILTER_CREATED_SCRATCHPAD_ENTRIES *
4121                   sizeof(*obdfilter_created_scratchpad));
4122         if (obdfilter_created_scratchpad == NULL)
4123                 return -ENOMEM;
4124
4125         ll_fmd_cachep = cfs_mem_cache_create("ll_fmd_cache",
4126                                              sizeof(struct filter_mod_data),
4127                                              0, 0);
4128         if (!ll_fmd_cachep)
4129                 GOTO(out, rc = -ENOMEM);
4130
4131         filter_quota_interface_ref = PORTAL_SYMBOL_GET(filter_quota_interface);
4132         init_obd_quota_ops(filter_quota_interface_ref, &filter_obd_ops);
4133
4134         rc = class_register_type(&filter_obd_ops, lvars.module_vars,
4135                                  LUSTRE_OST_NAME);
4136         if (rc) {
4137                 int err;
4138
4139                 err = cfs_mem_cache_destroy(ll_fmd_cachep);
4140                 LASSERTF(err == 0, "Cannot destroy ll_fmd_cachep: rc %d\n",err);
4141                 ll_fmd_cachep = NULL;
4142 out:
4143                 if (filter_quota_interface_ref)
4144                         PORTAL_SYMBOL_PUT(filter_quota_interface);
4145
4146                 OBD_FREE(obdfilter_created_scratchpad,
4147                          OBDFILTER_CREATED_SCRATCHPAD_ENTRIES *
4148                          sizeof(*obdfilter_created_scratchpad));
4149         }
4150
4151         return rc;
4152 }
4153
4154 static void __exit obdfilter_exit(void)
4155 {
4156         if (filter_quota_interface_ref)
4157                 PORTAL_SYMBOL_PUT(filter_quota_interface);
4158
4159         if (ll_fmd_cachep) {
4160                 int rc = cfs_mem_cache_destroy(ll_fmd_cachep);
4161                 LASSERTF(rc == 0, "Cannot destroy ll_fmd_cachep: rc %d\n", rc);
4162                 ll_fmd_cachep = NULL;
4163         }
4164
4165         class_unregister_type(LUSTRE_OST_NAME);
4166         OBD_FREE(obdfilter_created_scratchpad,
4167                  OBDFILTER_CREATED_SCRATCHPAD_ENTRIES *
4168                  sizeof(*obdfilter_created_scratchpad));
4169 }
4170
4171 MODULE_AUTHOR("Sun Microsystems, Inc. <http://www.lustre.org/>");
4172 MODULE_DESCRIPTION("Lustre Filtering OBD driver");
4173 MODULE_LICENSE("GPL");
4174
4175 module_init(obdfilter_init);
4176 module_exit(obdfilter_exit);