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