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