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