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