Whamcloud - gitweb
b=8654
[fs/lustre-release.git] / lustre / obdfilter / filter.c
1 /* -*- mode: c; c-basic-offset: 8; indent-tabs-mode: nil; -*-
2  * vim:expandtab:shiftwidth=8:tabstop=8:
3  *
4  *  linux/fs/obdfilter/filter.c
5  *
6  *  Copyright (c) 2001-2003 Cluster File Systems, Inc.
7  *   Author: Peter Braam <braam@clusterfs.com>
8  *   Author: Andreas Dilger <adilger@clusterfs.com>
9  *
10  *   This file is part of Lustre, http://www.lustre.org.
11  *
12  *   Lustre is free software; you can redistribute it and/or
13  *   modify it under the terms of version 2 of the GNU General Public
14  *   License as published by the Free Software Foundation.
15  *
16  *   Lustre is distributed in the hope that it will be useful,
17  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
18  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  *   GNU General Public License for more details.
20  *
21  *   You should have received a copy of the GNU General Public License
22  *   along with Lustre; if not, write to the Free Software
23  *   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
24  */
25
26 /*
27  * Invariant: Get O/R i_sem for lookup, if needed, before any journal ops
28  *            (which need to get journal_lock, may block if journal full).
29  *
30  * Invariant: Call filter_start_transno() before any journal ops to avoid the
31  *            same deadlock problem.  We can (and want) to get rid of the
32  *            transno sem in favour of the dir/inode i_sem to avoid single
33  *            threaded operation on the OST.
34  */
35
36 #define DEBUG_SUBSYSTEM S_FILTER
37
38 #include <linux/config.h>
39 #include <linux/module.h>
40 #include <linux/fs.h>
41 #include <linux/dcache.h>
42 #include <linux/init.h>
43 #include <linux/version.h>
44 #include <linux/jbd.h>
45 #include <linux/ext3_fs.h>
46 #if (LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0))
47 # include <linux/mount.h>
48 # include <linux/buffer_head.h>
49 # include <linux/bio.h>
50 #endif
51
52 #include <linux/obd_class.h>
53 #include <linux/obd_lov.h>
54 #include <linux/obd_ost.h>
55 #include <linux/lustre_dlm.h>
56 #include <linux/lustre_fsfilt.h>
57 #include <linux/lprocfs_status.h>
58 #include <linux/lustre_log.h>
59 #include <linux/lustre_commit_confd.h>
60 #include <libcfs/list.h>
61
62 #include <linux/lustre_smfs.h>
63 #include <linux/lustre_sec.h>
64 #include "filter_internal.h"
65
66 /* Group 0 is no longer a legal group, to catch uninitialized IDs */
67 #define FILTER_MIN_GROUPS 3
68
69 static struct lvfs_callback_ops filter_lvfs_ops;
70
71 static int filter_destroy(struct obd_export *exp, struct obdo *oa,
72                           struct lov_stripe_md *ea, struct obd_trans_info *);
73 struct obd_llogs *filter_grab_llog_for_group(struct obd_device *,
74                                              int, struct obd_export *);
75
76 static void filter_commit_cb(struct obd_device *obd, __u64 transno,
77                              void *cb_data, int error)
78 {
79         obd_transno_commit_cb(obd, transno, error);
80 }
81
82 /* Assumes caller has already pushed us into the kernel context. */
83 int filter_finish_transno(struct obd_export *exp, struct obd_trans_info *oti,
84                           int rc)
85 {
86         struct filter_obd *filter = &exp->exp_obd->u.filter;
87         struct filter_export_data *fed = &exp->exp_filter_data;
88         struct filter_client_data *fcd = fed->fed_fcd;
89         __u64 last_rcvd;
90         loff_t off;
91         int err, log_pri = D_HA;
92
93         /* Propagate error code. */
94         if (rc)
95                 RETURN(rc);
96
97         if (!exp->exp_obd->obd_replayable || oti == NULL)
98                 RETURN(rc);
99
100         /* we don't allocate new transnos for replayed requests */
101         if (oti->oti_transno == 0) {
102                 spin_lock(&filter->fo_translock);
103                 last_rcvd = le64_to_cpu(filter->fo_fsd->fsd_last_transno) + 1;
104                 filter->fo_fsd->fsd_last_transno = cpu_to_le64(last_rcvd);
105                 spin_unlock(&filter->fo_translock);
106                 oti->oti_transno = last_rcvd;
107         } else {
108                 spin_lock(&filter->fo_translock);
109                 last_rcvd = oti->oti_transno;
110                 if (last_rcvd > le64_to_cpu(filter->fo_fsd->fsd_last_transno))
111                         filter->fo_fsd->fsd_last_transno =
112                                 cpu_to_le64(last_rcvd);
113                 spin_unlock(&filter->fo_translock);
114         }
115         
116         fcd->fcd_last_rcvd = cpu_to_le64(last_rcvd);
117
118         /* could get xid from oti, if it's ever needed */
119         fcd->fcd_last_xid = 0;
120
121         off = fed->fed_lr_off;
122
123         fsfilt_add_journal_cb(exp->exp_obd, filter->fo_sb, last_rcvd,
124                               oti->oti_handle, filter_commit_cb, NULL);
125
126         err = fsfilt_write_record(exp->exp_obd, filter->fo_rcvd_filp, fcd,
127                                   sizeof(*fcd), &off, 0);
128         if (err) {
129                 log_pri = D_ERROR;
130                 if (rc == 0)
131                         rc = err;
132         }
133
134         CDEBUG(log_pri, "wrote trans "LPU64" for client %s at #%d: err = %d\n",
135                last_rcvd, fcd->fcd_uuid, fed->fed_lr_idx, err);
136
137         RETURN(rc);
138 }
139
140 void f_dput(struct dentry *dentry)
141 {
142         /* Can't go inside filter_ddelete because it can block */
143         CDEBUG(D_INODE, "putting %s: %p, count = %d\n",
144                dentry->d_name.name, dentry, atomic_read(&dentry->d_count) - 1);
145         LASSERT(atomic_read(&dentry->d_count) > 0);
146
147         dput(dentry);
148 }
149
150 /* Add client data to the FILTER.  We use a bitmap to locate a free space
151  * in the last_rcvd file if cl_idx is -1 (i.e. a new client).
152  * Otherwise, we have just read the data from the last_rcvd file and
153  * we know its offset. */
154 static int filter_client_add(struct obd_device *obd, struct filter_obd *filter,
155                              struct filter_export_data *fed, int cl_idx)
156 {
157         unsigned long *bitmap = filter->fo_last_rcvd_slots;
158         int new_client = (cl_idx == -1);
159         ENTRY;
160
161         LASSERT(bitmap != NULL);
162
163         /* XXX if fcd_uuid were a real obd_uuid, I could use obd_uuid_equals */
164         if (!strcmp((char *)fed->fed_fcd->fcd_uuid, (char *)obd->obd_uuid.uuid))
165                 RETURN(0);
166
167         /* the bitmap operations can handle cl_idx > sizeof(long) * 8, so
168          * there's no need for extra complication here
169          */
170         if (new_client) {
171                 cl_idx = find_first_zero_bit(bitmap, FILTER_LR_MAX_CLIENTS);
172         repeat:
173                 if (cl_idx >= FILTER_LR_MAX_CLIENTS) {
174                         CERROR("no client slots - fix FILTER_LR_MAX_CLIENTS\n");
175                         RETURN(-ENOMEM);
176                 }
177                 if (test_and_set_bit(cl_idx, bitmap)) {
178                         CERROR("FILTER client %d: found bit is set in bitmap\n",
179                                cl_idx);
180                         cl_idx = find_next_zero_bit(bitmap,
181                                                     FILTER_LR_MAX_CLIENTS,
182                                                     cl_idx);
183                         goto repeat;
184                 }
185         } else {
186                 if (test_and_set_bit(cl_idx, bitmap)) {
187                         CERROR("FILTER client %d: bit already set in bitmap!\n",
188                                cl_idx);
189                         LBUG();
190                 }
191         }
192
193         fed->fed_lr_idx = cl_idx;
194         fed->fed_lr_off = le32_to_cpu(filter->fo_fsd->fsd_client_start) +
195                 cl_idx * le16_to_cpu(filter->fo_fsd->fsd_client_size);
196
197         CDEBUG(D_INFO, "client at index %d (%llu) with UUID '%s' added\n",
198                fed->fed_lr_idx, fed->fed_lr_off, fed->fed_fcd->fcd_uuid);
199
200         if (new_client) {
201                 struct lvfs_run_ctxt saved;
202                 loff_t off = fed->fed_lr_off;
203                 int err;
204                 void *handle;
205
206                 CDEBUG(D_INFO, "writing client fcd at idx %u (%llu) (len %u)\n",
207                        fed->fed_lr_idx,off,(unsigned int)sizeof(*fed->fed_fcd));
208
209                 push_ctxt(&saved, &obd->obd_lvfs_ctxt, NULL);
210                 /* Transaction needed to fix bug 1403 */
211                 handle = fsfilt_start(obd,
212                                       filter->fo_rcvd_filp->f_dentry->d_inode,
213                                       FSFILT_OP_SETATTR, NULL);
214                 if (IS_ERR(handle)) {
215                         err = PTR_ERR(handle);
216                         CERROR("unable to start transaction: rc %d\n", err);
217                 } else {
218                         err = fsfilt_write_record(obd, filter->fo_rcvd_filp,
219                                                   fed->fed_fcd,
220                                                   sizeof(*fed->fed_fcd),
221                                                   &off, 1);
222                         fsfilt_commit(obd, filter->fo_sb,
223                                       filter->fo_rcvd_filp->f_dentry->d_inode,
224                                       handle, 1);
225                 }
226                 pop_ctxt(&saved, &obd->obd_lvfs_ctxt, NULL);
227
228                 if (err) {
229                         CERROR("error writing %s client idx %u: rc %d\n",
230                                LAST_RCVD, fed->fed_lr_idx, err);
231                         RETURN(err);
232                 }
233         }
234         RETURN(0);
235 }
236
237 static int filter_client_free(struct obd_export *exp, int flags)
238 {
239         struct filter_export_data *fed = &exp->exp_filter_data;
240         struct filter_obd *filter = &exp->exp_obd->u.filter;
241         struct obd_device *obd = exp->exp_obd;
242         struct filter_client_data zero_fcd;
243         struct lvfs_run_ctxt saved;
244         int rc;
245         loff_t off;
246         ENTRY;
247
248         if (fed->fed_fcd == NULL)
249                 RETURN(0);
250
251         if (flags & OBD_OPT_FAILOVER)
252                 GOTO(free, 0);
253
254         /* XXX if fcd_uuid were a real obd_uuid, I could use obd_uuid_equals */
255         if (!strcmp((char *)fed->fed_fcd->fcd_uuid, (char *)obd->obd_uuid.uuid))
256                 GOTO(free, 0);
257
258         LASSERT(filter->fo_last_rcvd_slots != NULL);
259
260         off = fed->fed_lr_off;
261
262         CDEBUG(D_INFO, "freeing client at idx %u (%lld) with UUID '%s'\n",
263                fed->fed_lr_idx, fed->fed_lr_off, fed->fed_fcd->fcd_uuid);
264
265         /* Clear the bit _after_ zeroing out the client so we don't
266            race with filter_client_add and zero out new clients.*/
267         if (!test_bit(fed->fed_lr_idx, filter->fo_last_rcvd_slots)) {
268                 CERROR("FILTER client %u: bit already clear in bitmap!!\n",
269                        fed->fed_lr_idx);
270                 LBUG();
271         }
272
273         memset(&zero_fcd, 0, sizeof zero_fcd);
274         push_ctxt(&saved, &obd->obd_lvfs_ctxt, NULL);
275         rc = fsfilt_write_record(obd, filter->fo_rcvd_filp, &zero_fcd,
276                                  sizeof(zero_fcd), &off, 1);
277         if (rc == 0)
278                 /* update server's transno */
279                 filter_update_server_data(obd, filter->fo_rcvd_filp,
280                                           filter->fo_fsd, 1);
281         pop_ctxt(&saved, &obd->obd_lvfs_ctxt, NULL);
282
283         CDEBUG(rc == 0 ? D_INFO : D_ERROR,
284                "zeroing disconnecting client %s at idx %u (%llu) in %s rc %d\n",
285                fed->fed_fcd->fcd_uuid, fed->fed_lr_idx, fed->fed_lr_off,
286                LAST_RCVD, rc);
287
288         if (!test_and_clear_bit(fed->fed_lr_idx, filter->fo_last_rcvd_slots)) {
289                 CERROR("FILTER client %u: bit already clear in bitmap!!\n",
290                        fed->fed_lr_idx);
291                 LBUG();
292         }
293
294 free:
295         OBD_FREE(fed->fed_fcd, sizeof(*fed->fed_fcd));
296
297         RETURN(0);
298 }
299
300 static int filter_free_server_data(struct filter_obd *filter)
301 {
302         OBD_FREE(filter->fo_fsd, sizeof(*filter->fo_fsd));
303         filter->fo_fsd = NULL;
304         OBD_FREE(filter->fo_last_rcvd_slots, FILTER_LR_MAX_CLIENTS/8);
305         filter->fo_last_rcvd_slots = NULL;
306         return 0;
307 }
308
309 /* assumes caller is already in kernel ctxt */
310 int filter_update_server_data(struct obd_device *obd, struct file *filp,
311                               struct filter_server_data *fsd, int force_sync)
312 {
313         loff_t off = 0;
314         int rc;
315         ENTRY;
316
317         CDEBUG(D_INODE, "server uuid      : %s\n", fsd->fsd_uuid);
318         CDEBUG(D_INODE, "server last_rcvd : "LPU64"\n",
319                le64_to_cpu(fsd->fsd_last_transno));
320         CDEBUG(D_INODE, "server last_mount: "LPU64"\n",
321                le64_to_cpu(fsd->fsd_mount_count));
322
323         rc = fsfilt_write_record(obd, filp, fsd, sizeof(*fsd), &off,force_sync);
324         if (rc)
325                 CERROR("error writing filter_server_data: rc = %d\n", rc);
326
327         RETURN(rc);
328 }
329
330 int filter_update_last_objid(struct obd_device *obd, obd_gr group,
331                              int force_sync)
332 {
333         struct filter_obd *filter = &obd->u.filter;
334         __u64 tmp;
335         loff_t off = 0;
336         int rc;
337         ENTRY;
338
339         if (filter->fo_last_objid_files[group] == NULL) {
340                 CERROR("Object group "LPU64" not fully setup; not updating "
341                        "last_objid\n", group);
342                 RETURN(0);
343         }
344
345         CDEBUG(D_INODE, "server last_objid for group "LPU64": "LPU64"\n",
346                group, filter->fo_last_objids[group]);
347
348         tmp = cpu_to_le64(filter->fo_last_objids[group]);
349         rc = fsfilt_write_record(obd, filter->fo_last_objid_files[group],
350                                  &tmp, sizeof(tmp), &off, force_sync);
351         if (rc)
352                 CERROR("error writing group "LPU64" last objid: rc = %d\n",
353                        group, rc);
354         RETURN(rc);
355 }
356
357 /* assumes caller has already in kernel ctxt */
358 static int filter_init_server_data(struct obd_device *obd, struct file * filp)
359 {
360         struct filter_obd *filter = &obd->u.filter;
361         struct filter_server_data *fsd;
362         struct filter_client_data *fcd = NULL;
363         struct inode *inode = filp->f_dentry->d_inode;
364         unsigned long last_rcvd_size = inode->i_size;
365         __u64 mount_count;
366         int cl_idx;
367         loff_t off = 0;
368         int rc;
369
370         /* ensure padding in the struct is the correct size */
371         LASSERT (offsetof(struct filter_server_data, fsd_padding) +
372                  sizeof(fsd->fsd_padding) == FILTER_LR_SERVER_SIZE);
373         LASSERT (offsetof(struct filter_client_data, fcd_padding) +
374                  sizeof(fcd->fcd_padding) == FILTER_LR_CLIENT_SIZE);
375
376         OBD_ALLOC(fsd, sizeof(*fsd));
377         if (!fsd)
378                 RETURN(-ENOMEM);
379         filter->fo_fsd = fsd;
380
381         OBD_ALLOC(filter->fo_last_rcvd_slots, FILTER_LR_MAX_CLIENTS/8);
382         if (filter->fo_last_rcvd_slots == NULL) {
383                 OBD_FREE(fsd, sizeof(*fsd));
384                 RETURN(-ENOMEM);
385         }
386
387         if (last_rcvd_size == 0) {
388                 CWARN("%s: initializing new %s\n", obd->obd_name, LAST_RCVD);
389
390                 memcpy(fsd->fsd_uuid, obd->obd_uuid.uuid,sizeof(fsd->fsd_uuid));
391                 fsd->fsd_last_transno = 0;
392                 mount_count = fsd->fsd_mount_count = 0;
393                 fsd->fsd_server_size = cpu_to_le32(FILTER_LR_SERVER_SIZE);
394                 fsd->fsd_client_start = cpu_to_le32(FILTER_LR_CLIENT_START);
395                 fsd->fsd_client_size = cpu_to_le16(FILTER_LR_CLIENT_SIZE);
396                 fsd->fsd_subdir_count = cpu_to_le16(FILTER_SUBDIR_COUNT);
397                 filter->fo_subdir_count = FILTER_SUBDIR_COUNT;
398         } else {
399                 rc = fsfilt_read_record(obd, filp, fsd, sizeof(*fsd), &off);
400                 if (rc) {
401                         CDEBUG(D_INODE,"OBD filter: error reading %s: rc %d\n",
402                                LAST_RCVD, rc);
403                         GOTO(err_fsd, rc);
404                 }
405                 if (strcmp((char *)fsd->fsd_uuid, (char *)obd->obd_uuid.uuid)) {
406                         CERROR("OBD UUID %s does not match last_rcvd UUID %s\n",
407                                obd->obd_uuid.uuid, fsd->fsd_uuid);
408                         GOTO(err_fsd, rc = -EINVAL);
409                 }
410                 mount_count = le64_to_cpu(fsd->fsd_mount_count);
411                 filter->fo_subdir_count = le16_to_cpu(fsd->fsd_subdir_count);
412         }
413
414         if (fsd->fsd_feature_incompat & ~cpu_to_le32(FILTER_INCOMPAT_SUPP)) {
415                 CERROR("unsupported feature %x\n",
416                        le32_to_cpu(fsd->fsd_feature_incompat) &
417                        ~FILTER_INCOMPAT_SUPP);
418                 GOTO(err_fsd, rc = -EINVAL);
419         }
420         if (fsd->fsd_feature_rocompat & ~cpu_to_le32(FILTER_ROCOMPAT_SUPP)) {
421                 CERROR("read-only feature %x\n",
422                        le32_to_cpu(fsd->fsd_feature_rocompat) &
423                        ~FILTER_ROCOMPAT_SUPP);
424                 /* Do something like remount filesystem read-only */
425                 GOTO(err_fsd, rc = -EINVAL);
426         }
427
428         CDEBUG(D_INODE, "%s: server last_rcvd : "LPU64"\n",
429                obd->obd_name, le64_to_cpu(fsd->fsd_last_transno));
430         CDEBUG(D_INODE, "%s: server mount_count: "LPU64"\n",
431                obd->obd_name, mount_count + 1);
432         CDEBUG(D_INODE, "%s: server data size: %u\n",
433                obd->obd_name, le32_to_cpu(fsd->fsd_server_size));
434         CDEBUG(D_INODE, "%s: per-client data start: %u\n",
435                obd->obd_name, le32_to_cpu(fsd->fsd_client_start));
436         CDEBUG(D_INODE, "%s: per-client data size: %u\n",
437                obd->obd_name, le32_to_cpu(fsd->fsd_client_size));
438         CDEBUG(D_INODE, "%s: server subdir_count: %u\n",
439                obd->obd_name, le16_to_cpu(fsd->fsd_subdir_count));
440         CDEBUG(D_INODE, "%s: last_rcvd clients: %lu\n", obd->obd_name,
441                last_rcvd_size <= le32_to_cpu(fsd->fsd_client_start) ? 0 :
442                (last_rcvd_size - le32_to_cpu(fsd->fsd_client_start)) /
443                 le16_to_cpu(fsd->fsd_client_size));
444
445         if (!obd->obd_replayable) {
446                 CWARN("%s: recovery support OFF\n", obd->obd_name);
447                 GOTO(out, rc = 0);
448         }
449
450         for (cl_idx = 0, off = le32_to_cpu(fsd->fsd_client_start);
451              off < last_rcvd_size; cl_idx++) {
452                 __u64 last_rcvd;
453                 struct obd_export *exp;
454                 struct filter_export_data *fed;
455
456                 if (!fcd) {
457                         OBD_ALLOC(fcd, sizeof(*fcd));
458                         if (!fcd)
459                                 GOTO(err_client, rc = -ENOMEM);
460                 }
461
462                 /* Don't assume off is incremented properly by
463                  * fsfilt_read_record(), in case sizeof(*fcd)
464                  * isn't the same as fsd->fsd_client_size.  */
465                 off = le32_to_cpu(fsd->fsd_client_start) +
466                         cl_idx * le16_to_cpu(fsd->fsd_client_size);
467                 rc = fsfilt_read_record(obd, filp, fcd, sizeof(*fcd), &off);
468                 if (rc) {
469                         CERROR("error reading FILT %s idx %d off %llu: rc %d\n",
470                                LAST_RCVD, cl_idx, off, rc);
471                         break; /* read error shouldn't cause startup to fail */
472                 }
473
474                 if (fcd->fcd_uuid[0] == '\0') {
475                         CDEBUG(D_INFO, "skipping zeroed client at offset %d\n",
476                                cl_idx);
477                         continue;
478                 }
479
480                 last_rcvd = le64_to_cpu(fcd->fcd_last_rcvd);
481
482                 /* These exports are cleaned up by filter_disconnect(), so they
483                  * need to be set up like real exports as filter_connect() does.
484                  */
485                 exp = class_new_export(obd);
486                 CDEBUG(D_HA, "RCVRNG CLIENT uuid: %s idx: %d lr: "LPU64" "
487                        "srv lr: "LPU64" fcd_group %d \n", fcd->fcd_uuid, cl_idx,
488                        last_rcvd, le64_to_cpu(fsd->fsd_last_transno), 
489                        le32_to_cpu(fcd->fcd_group));
490                 if (exp == NULL)
491                         GOTO(err_client, rc = -ENOMEM);
492
493                 memcpy(&exp->exp_client_uuid.uuid, fcd->fcd_uuid,
494                        sizeof exp->exp_client_uuid.uuid);
495                 fed = &exp->exp_filter_data;
496                 fed->fed_fcd = fcd;
497                 fed->fed_group = le32_to_cpu(fcd->fcd_group);
498                 filter_client_add(obd, filter, fed, cl_idx);
499                 /* create helper if export init gets more complex */
500                 spin_lock_init(&fed->fed_lock);
501
502                 fcd = NULL;
503                 exp->exp_connected = 0;
504                 exp->exp_req_replay_needed = 1;
505                 exp->exp_lock_replay_needed = 1;
506                 atomic_inc(&obd->obd_req_replay_clients);
507                 atomic_inc(&obd->obd_lock_replay_clients);
508                 obd->obd_recoverable_clients++;
509                 obd->obd_max_recoverable_clients++;
510                 class_export_put(exp);
511
512                 CDEBUG(D_OTHER, "client at idx %d has last_rcvd = "LPU64"\n",
513                        cl_idx, last_rcvd);
514
515                 if (last_rcvd > le64_to_cpu(fsd->fsd_last_transno))
516                         fsd->fsd_last_transno = cpu_to_le64(last_rcvd);
517
518         }
519
520         obd->obd_last_committed = le64_to_cpu(fsd->fsd_last_transno);
521
522         if (obd->obd_recoverable_clients) {
523                 CWARN("RECOVERY: service %s, %d recoverable clients, "
524                       "last_transno "LPU64"\n", obd->obd_name,
525                       obd->obd_recoverable_clients,
526                       le64_to_cpu(fsd->fsd_last_transno));
527                 obd->obd_next_recovery_transno = obd->obd_last_committed + 1;
528                 target_start_recovery_thread(obd, ost_handle);
529         }
530
531         if (fcd)
532                 OBD_FREE(fcd, sizeof(*fcd));
533
534 out:
535         filter->fo_mount_count = mount_count + 1;
536         fsd->fsd_mount_count = cpu_to_le64(filter->fo_mount_count);
537
538         /* save it, so mount count and last_transno is current */
539         rc = filter_update_server_data(obd, filp, filter->fo_fsd, 1);
540         if (rc)
541                 GOTO(err_client, rc);
542         RETURN(0);
543
544 err_client:
545         class_disconnect_exports(obd, 0);
546 err_fsd:
547         filter_free_server_data(filter);
548         RETURN(rc);
549 }
550
551 static int filter_cleanup_groups(struct obd_device *obd)
552 {
553         struct filter_obd *filter = &obd->u.filter;
554         struct dentry *dentry;
555         int i, k;
556         ENTRY;
557
558         for (i = 0; i < filter->fo_group_count; i++) {
559                 if (filter->fo_subdirs != NULL) {
560                         for (k = 0; k < filter->fo_subdir_count; k++) {
561                                 dentry = filter->fo_subdirs[i].dentry[k];
562                                 if (dentry == NULL)
563                                         continue;
564                                 f_dput(dentry);
565                                 filter->fo_subdirs[i].dentry[k] = NULL;
566                         }
567                 }
568                 if (filter->fo_last_objid_files[i] != NULL) {
569                         filp_close(filter->fo_last_objid_files[i], 0);
570                         filter->fo_last_objid_files[i] = NULL;
571                 }
572                 if (filter->fo_groups[i] != NULL) {
573                         dput(filter->fo_groups[i]);
574                         filter->fo_groups[i] = NULL;
575                 }
576         }
577         if (filter->fo_subdirs != NULL)
578                 OBD_FREE(filter->fo_subdirs,
579                          filter->fo_group_count * sizeof(*filter->fo_subdirs));
580         if (filter->fo_groups != NULL)
581                 OBD_FREE(filter->fo_groups,
582                          filter->fo_group_count * sizeof(*filter->fo_groups));
583         if (filter->fo_last_objids != NULL)
584                 OBD_FREE(filter->fo_last_objids,
585                          filter->fo_group_count * sizeof(__u64));
586         if (filter->fo_last_objid_files != NULL)
587                 OBD_FREE(filter->fo_last_objid_files,
588                          filter->fo_group_count * sizeof(struct file *));
589         f_dput(filter->fo_dentry_O);
590         RETURN(0);
591 }
592
593 static int filter_update_last_group(struct obd_device *obd, int group)
594 {
595         struct filter_obd *filter = &obd->u.filter;
596         struct file *filp = NULL;
597         int last_group = 0, rc;
598         loff_t off = 0;
599         ENTRY;
600
601         if (group <= filter->fo_committed_group)
602                 RETURN(0);
603
604         filp = filp_open("LAST_GROUP", O_RDWR, 0700);
605         if (IS_ERR(filp)) {
606                 rc = PTR_ERR(filp);
607                 filp = NULL;
608                 CERROR("cannot open LAST_GROUP: rc = %d\n", rc);
609                 GOTO(cleanup, rc);
610         }
611
612         rc = fsfilt_read_record(obd, filp, &last_group, sizeof(__u32), &off);
613         if (rc) {
614                 CDEBUG(D_INODE, "error reading LAST_GROUP: rc %d\n",rc);
615                 GOTO(cleanup, rc);
616         }
617         LASSERT(off == 0 || last_group >= FILTER_MIN_GROUPS);
618         CDEBUG(D_INODE, "%s: previous %d, new %d\n",
619                obd->obd_name, last_group, group);
620
621         off = 0;
622         last_group = group;
623         /* must be sync: bXXXX */
624         rc = fsfilt_write_record(obd, filp, &last_group, sizeof(__u32), &off, 1);
625         if (rc) {
626                 CDEBUG(D_INODE, "error updating LAST_GROUP: rc %d\n", rc);
627                 GOTO(cleanup, rc);
628         }
629
630         filter->fo_committed_group = group;
631 cleanup:
632         if (filp)
633                 filp_close(filp, 0);
634         RETURN(rc);
635 }
636
637 static int filter_read_group_internal(struct obd_device *obd, int group,
638                                       int create)
639 {
640         struct filter_obd *filter = &obd->u.filter;
641         __u64 *new_objids = NULL;
642         struct filter_subdirs *new_subdirs = NULL, *tmp_subdirs = NULL;
643         struct dentry **new_groups = NULL;
644         struct file **new_files = NULL;
645         struct dentry *dentry;
646         struct file *filp;
647         int old_count = filter->fo_group_count, rc, stage = 0, i;
648         char name[25];
649         __u64 last_objid;
650         loff_t off = 0;
651
652         snprintf(name, 24, "%d", group);
653         name[24] = '\0';
654
655         if (!create) {
656                 dentry = ll_lookup_one_len(name, filter->fo_dentry_O,
657                                            strlen(name));
658                 if (IS_ERR(dentry)) {
659                         CERROR("Cannot lookup expected object group %d: %ld\n",
660                                group, PTR_ERR(dentry));
661                         RETURN(PTR_ERR(dentry));
662                 }
663         } else {
664                 dentry = simple_mkdir(filter->fo_dentry_O, name, 0700, 1);
665                 if (IS_ERR(dentry)) {
666                         CERROR("cannot lookup/create O/%s: rc = %ld\n", name,
667                                PTR_ERR(dentry));
668                         RETURN(PTR_ERR(dentry));
669                 }
670         }
671         stage = 1;
672
673         snprintf(name, 24, "O/%d/LAST_ID", group);
674         name[24] = '\0';
675         filp = filp_open(name, O_CREAT | O_RDWR, 0700);
676         if (IS_ERR(filp)) {
677                 CERROR("cannot create %s: rc = %ld\n", name, PTR_ERR(filp));
678                 GOTO(cleanup, rc = PTR_ERR(filp));
679         }
680         stage = 2;
681
682         rc = fsfilt_read_record(obd, filp, &last_objid, sizeof(__u64), &off);
683         if (rc) {
684                 CDEBUG(D_INODE, "error reading %s: rc %d\n", name, rc);
685                 GOTO(cleanup, rc);
686         }
687
688         if (filter->fo_subdir_count) {
689                 OBD_ALLOC(tmp_subdirs, sizeof(*tmp_subdirs));
690                 if (tmp_subdirs == NULL)
691                         GOTO(cleanup, rc = -ENOMEM);
692                 stage = 3;
693
694                 for (i = 0; i < filter->fo_subdir_count; i++) {
695                         char dir[20];
696                         snprintf(dir, sizeof(dir), "d%u", i);
697
698                         tmp_subdirs->dentry[i] = simple_mkdir(dentry, dir, 0700, 1);
699                         if (IS_ERR(tmp_subdirs->dentry[i])) {
700                                 rc = PTR_ERR(tmp_subdirs->dentry[i]);
701                                 CERROR("can't lookup/create O/%d/%s: rc = %d\n",
702                                        group, dir, rc);
703                                 GOTO(cleanup, rc);
704                         }
705
706                         /* turn on smfs plugins if any */
707                         fsfilt_set_fs_flags(obd, tmp_subdirs->dentry[i]->d_inode,
708                                             SM_ALL_PLG);
709
710                         CDEBUG(D_INODE, "got/created O/%d/%s: %p\n", group, dir,
711                                tmp_subdirs->dentry[i]);
712                 }
713         }
714
715         /* 'group' is an index; we need an array of length 'group + 1' */
716         if (group + 1 > old_count) {
717                 int len = group + 1;
718                 OBD_ALLOC(new_objids, len * sizeof(*new_objids));
719                 OBD_ALLOC(new_subdirs, len * sizeof(*new_subdirs));
720                 OBD_ALLOC(new_groups, len * sizeof(*new_groups));
721                 OBD_ALLOC(new_files, len * sizeof(*new_files));
722                 stage = 4;
723                 if (new_objids == NULL || new_subdirs == NULL ||
724                     new_groups == NULL || new_files == NULL)
725                         GOTO(cleanup, rc = -ENOMEM);
726
727                 memcpy(new_objids, filter->fo_last_objids,
728                        old_count * sizeof(*new_objids));
729                 memcpy(new_subdirs, filter->fo_subdirs,
730                        old_count * sizeof(*new_subdirs));
731                 memcpy(new_groups, filter->fo_groups,
732                        old_count * sizeof(*new_groups));
733                 memcpy(new_files, filter->fo_last_objid_files,
734                        old_count * sizeof(*new_files));
735
736                 if (old_count) {
737                         OBD_FREE(filter->fo_last_objids,
738                                  old_count * sizeof(*new_objids));
739                         OBD_FREE(filter->fo_subdirs,
740                                  old_count * sizeof(*new_subdirs));
741                         OBD_FREE(filter->fo_groups,
742                                  old_count * sizeof(*new_groups));
743                         OBD_FREE(filter->fo_last_objid_files,
744                                  old_count * sizeof(*new_files));
745                 }
746                 filter->fo_last_objids = new_objids;
747                 filter->fo_subdirs = new_subdirs;
748                 filter->fo_groups = new_groups;
749                 filter->fo_last_objid_files = new_files;
750                 filter->fo_group_count = len;
751         }
752
753         filter->fo_groups[group] = dentry;
754         filter->fo_last_objid_files[group] = filp;
755         if (filter->fo_subdir_count) {
756                 filter->fo_subdirs[group] = *tmp_subdirs;
757                 OBD_FREE(tmp_subdirs, sizeof(*tmp_subdirs));
758         }
759
760         filter_update_last_group(obd, group);
761         
762         if (filp->f_dentry->d_inode->i_size == 0) {
763                 filter->fo_last_objids[group] = FILTER_INIT_OBJID;
764                 RETURN(0);
765         }
766
767         filter->fo_last_objids[group] = le64_to_cpu(last_objid);
768         CDEBUG(D_INODE, "%s: server last_objid group %d: "LPU64"\n",
769                obd->obd_name, group, last_objid);
770         RETURN(0);
771  cleanup:
772         switch (stage) {
773         case 4:
774                 if (new_objids != NULL)
775                         OBD_FREE(new_objids, group * sizeof(*new_objids));
776                 if (new_subdirs != NULL)
777                         OBD_FREE(new_subdirs, group * sizeof(*new_subdirs));
778                 if (new_groups != NULL)
779                         OBD_FREE(new_groups, group * sizeof(*new_groups));
780                 if (new_files != NULL)
781                         OBD_FREE(new_files, group * sizeof(*new_files));
782         case 3:
783                 if (filter->fo_subdir_count) {
784                         for (i = 0; i < filter->fo_subdir_count; i++) {
785                                 if (tmp_subdirs->dentry[i] != NULL)
786                                         dput(tmp_subdirs->dentry[i]);
787                         }
788                         OBD_FREE(tmp_subdirs, sizeof(*tmp_subdirs));
789                 }
790         case 2:
791                 filp_close(filp, 0);
792         case 1:
793                 dput(dentry);
794         }
795         RETURN(rc);
796 }
797
798 static int filter_read_groups(struct obd_device *obd, int last_group,
799                               int create)
800 {
801         struct filter_obd *filter = &obd->u.filter;
802         int old_count, group, rc = 0;
803
804         down(&filter->fo_init_lock);
805         old_count = filter->fo_group_count;
806         for (group = old_count; group <= last_group; group++) {
807                 if (group == 0)
808                         continue; /* no group zero */
809
810                 rc = filter_read_group_internal(obd, group, create);
811                 if (rc != 0)
812                         break;
813         }
814         up(&filter->fo_init_lock);
815         return rc;
816 }
817
818 static int filter_prep_groups(struct obd_device *obd)
819 {
820         struct filter_obd *filter = &obd->u.filter;
821         struct dentry *dentry, *O_dentry;
822         int rc = 0, cleanup_phase = 0;
823         struct file *filp = NULL;
824         int last_group;
825         loff_t off = 0;
826         ENTRY;
827
828         O_dentry = simple_mkdir(current->fs->pwd, "O", 0700, 1);
829         CDEBUG(D_INODE, "got/created O: %p\n", O_dentry);
830         if (IS_ERR(O_dentry)) {
831                 rc = PTR_ERR(O_dentry);
832                 CERROR("cannot open/create O: rc = %d\n", rc);
833                 GOTO(cleanup, rc);
834         }
835         filter->fo_dentry_O = O_dentry;
836         cleanup_phase = 1; /* O_dentry */
837
838         /* Lookup "R" to tell if we're on an old OST FS and need to convert
839          * from O/R/<dir>/<objid> to O/0/<dir>/<objid>.  This can be removed
840          * some time post 1.0 when all old-style OSTs have converted along
841          * with the init_objid hack. */
842         dentry = ll_lookup_one_len("R", O_dentry, 1);
843         if (IS_ERR(dentry))
844                 GOTO(cleanup, rc = PTR_ERR(dentry));
845         if (dentry->d_inode && S_ISDIR(dentry->d_inode->i_mode)) {
846                 struct dentry *O0_dentry = lookup_one_len("0", O_dentry, 1);
847                 ENTRY;
848
849                 CWARN("converting OST to new object layout\n");
850                 if (IS_ERR(O0_dentry)) {
851                         rc = PTR_ERR(O0_dentry);
852                         CERROR("error looking up O/0: rc %d\n", rc);
853                         GOTO(cleanup_R, rc);
854                 }
855
856                 if (O0_dentry->d_inode) {
857                         CERROR("Both O/R and O/0 exist. Fix manually.\n");
858                         GOTO(cleanup_O0, rc = -EEXIST);
859                 }
860
861                 down(&O_dentry->d_inode->i_sem);
862                 rc = vfs_rename(O_dentry->d_inode, dentry,
863                                 O_dentry->d_inode, O0_dentry);
864                 up(&O_dentry->d_inode->i_sem);
865
866                 if (rc) {
867                         CERROR("error renaming O/R to O/0: rc %d\n", rc);
868                         GOTO(cleanup_O0, rc);
869                 }
870                 filter->fo_fsd->fsd_feature_incompat |=
871                         cpu_to_le32(FILTER_INCOMPAT_GROUPS);
872                 rc = filter_update_server_data(obd, filter->fo_rcvd_filp,
873                                                filter->fo_fsd, 1);
874                 GOTO(cleanup_O0, rc);
875
876         cleanup_O0:
877                 f_dput(O0_dentry);
878         cleanup_R:
879                 f_dput(dentry);
880                 if (rc)
881                         GOTO(cleanup, rc);
882         } else {
883                 f_dput(dentry);
884         }
885
886         cleanup_phase = 2; /* groups */
887
888         /* we have to initialize all groups before first connections from
889          * clients because they may send create/destroy for any group -bzzz */
890         filp = filp_open("LAST_GROUP", O_CREAT | O_RDWR, 0700);
891         if (IS_ERR(filp)) {
892                 CERROR("cannot create LAST_GROUP: rc = %ld\n", PTR_ERR(filp));
893                 GOTO(cleanup, rc = PTR_ERR(filp));
894         }
895         cleanup_phase = 3; /* filp */
896
897         rc = fsfilt_read_record(obd, filp, &last_group, sizeof(__u32), &off);
898         if (rc) {
899                 CDEBUG(D_INODE, "error reading LAST_GROUP: rc %d\n", rc);
900                 GOTO(cleanup, rc);
901         }
902         if (off == 0) {
903                 last_group = FILTER_MIN_GROUPS;
904         } else {
905                 LASSERT(last_group >= FILTER_MIN_GROUPS);
906         }
907
908         CWARN("%s: initialize groups [%d,%d]\n", obd->obd_name,
909               FILTER_MIN_GROUPS, last_group);
910         filter->fo_committed_group = last_group;
911         rc = filter_read_groups(obd, last_group, 1);
912         if (rc)
913                 GOTO(cleanup, rc);
914         
915         filp_close(filp, 0);
916         RETURN(0);
917
918  cleanup:
919         switch (cleanup_phase) {
920         case 3:
921                 filp_close(filp, 0);
922         case 2:
923                 filter_cleanup_groups(obd);
924         case 1:
925                 f_dput(filter->fo_dentry_O);
926                 filter->fo_dentry_O = NULL;
927         default:
928                 break;
929         }
930         return rc;
931 }
932
933
934 /* setup the object store with correct subdirectories */
935 static int filter_prep(struct obd_device *obd)
936 {
937         struct lvfs_run_ctxt saved;
938         struct filter_obd *filter = &obd->u.filter;
939         struct file *file;
940         struct inode *inode;
941         int rc = 0;
942         ENTRY;
943
944         push_ctxt(&saved, &obd->obd_lvfs_ctxt, NULL);
945         file = filp_open(LAST_RCVD, O_RDWR | O_CREAT | O_LARGEFILE, 0700);
946         if (!file || IS_ERR(file)) {
947                 rc = PTR_ERR(file);
948                 CERROR("OBD filter: cannot open/create %s: rc = %d\n",
949                        LAST_RCVD, rc);
950                 GOTO(out, rc);
951         }
952
953         if (!S_ISREG(file->f_dentry->d_inode->i_mode)) {
954                 CERROR("%s is not a regular file!: mode = %o\n", LAST_RCVD,
955                        file->f_dentry->d_inode->i_mode);
956                 GOTO(err_filp, rc = -ENOENT);
957         }
958
959         /* steal operations */
960         inode = file->f_dentry->d_inode;
961         filter->fo_fop = file->f_op;
962         filter->fo_iop = inode->i_op;
963         filter->fo_aops = inode->i_mapping->a_ops;
964
965         rc = filter_init_server_data(obd, file);
966         if (rc) {
967                 CERROR("cannot read %s: rc = %d\n", LAST_RCVD, rc);
968                 GOTO(err_filp, rc);
969         }
970         filter->fo_rcvd_filp = file;
971
972         rc = filter_prep_groups(obd);
973         if (rc)
974                 GOTO(err_server_data, rc);
975
976  out:
977         pop_ctxt(&saved, &obd->obd_lvfs_ctxt, NULL);
978
979         return(rc);
980
981  err_server_data:
982         //class_disconnect_exports(obd, 0);
983         filter_free_server_data(filter);
984  err_filp:
985         if (filp_close(file, 0))
986                 CERROR("can't close %s after error\n", LAST_RCVD);
987         filter->fo_rcvd_filp = NULL;
988         goto out;
989 }
990
991 /* cleanup the filter: write last used object id to status file */
992 static void filter_post(struct obd_device *obd)
993 {
994         struct lvfs_run_ctxt saved;
995         struct filter_obd *filter = &obd->u.filter;
996         int rc, i;
997
998         /* XXX: filter_update_lastobjid used to call fsync_dev.  It might be
999          * best to start a transaction with h_sync, because we removed this
1000          * from lastobjid */
1001
1002         push_ctxt(&saved, &obd->obd_lvfs_ctxt, NULL);
1003         rc = filter_update_server_data(obd, filter->fo_rcvd_filp,
1004                                        filter->fo_fsd, 0);
1005         if (rc)
1006                 CERROR("error writing server data: rc = %d\n", rc);
1007
1008         for (i = 1; i < filter->fo_group_count; i++) {
1009                 rc = filter_update_last_objid(obd, i,
1010                                              (i == filter->fo_group_count - 1));
1011                 if (rc)
1012                         CERROR("error writing group %d lastobjid: rc = %d\n",
1013                                i, rc);
1014         }
1015
1016         rc = filp_close(filter->fo_rcvd_filp, 0);
1017         filter->fo_rcvd_filp = NULL;
1018         if (rc)
1019                 CERROR("error closing %s: rc = %d\n", LAST_RCVD, rc);
1020
1021         filter_cleanup_groups(obd);
1022         filter_free_server_data(filter);
1023         pop_ctxt(&saved, &obd->obd_lvfs_ctxt, NULL);
1024
1025         filter_free_capa_keys(filter);
1026 }
1027
1028 static void filter_set_last_id(struct filter_obd *filter, int group, obd_id id)
1029 {
1030         LASSERT(filter->fo_fsd != NULL);
1031         LASSERT(group > 0);
1032         LASSERT(group < filter->fo_group_count);
1033
1034         spin_lock(&filter->fo_objidlock);
1035         filter->fo_last_objids[group] = id;
1036         spin_unlock(&filter->fo_objidlock);
1037 }
1038
1039 __u64 filter_last_id(struct filter_obd *filter, int group)
1040 {
1041         obd_id id;
1042         LASSERT(filter->fo_fsd != NULL);
1043         LASSERT(group > 0);
1044         LASSERT(group < filter->fo_group_count);
1045
1046         spin_lock(&filter->fo_objidlock);
1047         id = filter->fo_last_objids[group];
1048         spin_unlock(&filter->fo_objidlock);
1049
1050         return id;
1051 }
1052
1053 static void filter_save_last_id(struct filter_obd *filter, int group, obd_id id)
1054 {
1055         LASSERT(group > 0);
1056         LASSERT(group < filter->fo_group_count);
1057
1058         spin_lock(&filter->fo_lastidlock);
1059         if (id > filter_last_id(filter, group))
1060                 filter_set_last_id(filter, group, id);
1061         spin_unlock(&filter->fo_lastidlock);
1062 }
1063         
1064 /* direct cut-n-paste of mds_blocking_ast() */
1065 static int filter_blocking_ast(struct ldlm_lock *lock,
1066                                struct ldlm_lock_desc *desc,
1067                                void *data, int flag)
1068 {
1069         int do_ast;
1070         ENTRY;
1071
1072         if (flag == LDLM_CB_CANCELING) {
1073                 /* Don't need to do anything here. */
1074                 RETURN(0);
1075         }
1076
1077         /* XXX layering violation!  -phil */
1078         lock_res_and_lock(lock);
1079         /* Get this: if filter_blocking_ast is racing with ldlm_intent_policy,
1080          * such that filter_blocking_ast is called just before l_i_p takes the
1081          * ns_lock, then by the time we get the lock, we might not be the
1082          * correct blocking function anymore.  So check, and return early, if
1083          * so. */
1084         if (lock->l_blocking_ast != filter_blocking_ast) {
1085                 unlock_res_and_lock(lock);
1086                 RETURN(0);
1087         }
1088
1089         lock->l_flags |= LDLM_FL_CBPENDING;
1090         do_ast = (!lock->l_readers && !lock->l_writers);
1091         unlock_res_and_lock(lock);
1092
1093         if (do_ast) {
1094                 struct lustre_handle lockh;
1095                 int rc;
1096
1097                 LDLM_DEBUG(lock, "already unused, calling ldlm_cli_cancel");
1098                 ldlm_lock2handle(lock, &lockh);
1099                 rc = ldlm_cli_cancel(&lockh);
1100                 if (rc < 0)
1101                         CERROR("ldlm_cli_cancel: %d\n", rc);
1102         } else {
1103                 LDLM_DEBUG(lock, "Lock still has references, will be "
1104                            "cancelled later");
1105         }
1106         RETURN(0);
1107 }
1108
1109 extern void *lock_dir(struct inode *dir, struct qstr *name);
1110 extern void unlock_dir(struct inode *dir, void *lock);
1111
1112 static void *filter_lock_dentry(struct obd_device *obd,
1113                                 struct dentry *dparent,
1114                                 obd_id id)
1115 {
1116 #ifdef S_PDIROPS
1117         struct qstr qstr;
1118         char name[32];
1119         int len;
1120
1121         len = sprintf(name, LPU64, id);
1122         qstr_assign(&qstr, (char *)name, len);
1123         return lock_dir(dparent->d_inode, &qstr);
1124 #else
1125         down(&dparent->d_inode->i_sem);
1126 #endif
1127         return 0;
1128 }
1129
1130 /* We never dget the object parent, so DON'T dput it either */
1131 static void filter_parent_unlock(struct dentry *dparent, void *lock)
1132 {
1133 #ifdef S_PDIROPS
1134         LASSERT(lock != NULL);
1135         unlock_dir(dparent->d_inode, lock);
1136 #else
1137         up(&dparent->d_inode->i_sem);
1138 #endif
1139 }
1140
1141 /* We never dget the object parent, so DON'T dput it either */
1142 struct dentry *filter_parent(struct obd_device *obd, obd_gr group, obd_id objid)
1143 {
1144         struct filter_obd *filter = &obd->u.filter;
1145         LASSERTF(group < filter->fo_group_count,
1146                  "group %d < filter->fo_group_count %d failed\n",
1147                  (int)group, (int)filter->fo_group_count);
1148         LASSERTF(group > 0, "group %d > 0 failed\n", (int)group);
1149
1150         if (filter->fo_subdir_count == 0)
1151                 return filter->fo_groups[group];
1152
1153         return filter->fo_subdirs[group].dentry[objid & (filter->fo_subdir_count - 1)];
1154 }
1155
1156 /* We never dget the object parent, so DON'T dput it either */
1157 struct dentry *filter_parent_lock(struct obd_device *obd, obd_gr group,
1158                                   obd_id objid, void **lock)
1159 {
1160         unsigned long now = jiffies;
1161         struct dentry *dparent = filter_parent(obd, group, objid);
1162
1163         if (IS_ERR(dparent))
1164                 return dparent;
1165
1166         LASSERT(dparent);
1167         LASSERT(dparent->d_inode);
1168
1169         *lock = filter_lock_dentry(obd, dparent, objid);
1170         fsfilt_check_slow(now, obd_timeout, "parent lock");
1171         return dparent;
1172 }
1173
1174 /* How to get files, dentries, inodes from object id's.
1175  *
1176  * If dir_dentry is passed, the caller has already locked the parent
1177  * appropriately for this operation (normally a write lock).  If
1178  * dir_dentry is NULL, we do a read lock while we do the lookup to
1179  * avoid races with create/destroy and such changing the directory
1180  * internal to the filesystem code. */
1181 struct dentry *filter_id2dentry(struct obd_device *obd,
1182                                 struct dentry *dir_dentry,
1183                                 obd_gr group, obd_id id)
1184 {
1185         struct dentry *dparent = dir_dentry;
1186         struct dentry *dchild;
1187         void *lock = NULL;
1188         char name[32];
1189         int len;
1190         ENTRY;
1191
1192         if (id == 0) {
1193                 CERROR("fatal: invalid object id 0\n");
1194                 RETURN(ERR_PTR(-ESTALE));
1195         }
1196
1197         len = sprintf(name, LPU64, id);
1198         if (dir_dentry == NULL) {
1199                 dparent = filter_parent_lock(obd, group, id, &lock);
1200                 if (IS_ERR(dparent)) {
1201                         CERROR("%s: error getting object "LPU64":"LPU64
1202                                " parent: rc %ld\n", obd->obd_name,
1203                                id, group, PTR_ERR(dparent));
1204                         RETURN(dparent);
1205                 }
1206         }
1207         CDEBUG(D_INODE, "looking up object O/%.*s/%s\n",
1208                dparent->d_name.len, dparent->d_name.name, name);
1209         dchild = /*ll_*/lookup_one_len(name, dparent, len);
1210         if (dir_dentry == NULL)
1211                 filter_parent_unlock(dparent, lock);
1212         if (IS_ERR(dchild)) {
1213                 CERROR("%s: child lookup error %ld\n", obd->obd_name,
1214                        PTR_ERR(dchild));
1215                 RETURN(dchild);
1216         }
1217
1218         if (dchild->d_inode != NULL && is_bad_inode(dchild->d_inode)) {
1219                 CERROR("%s: got bad inode "LPU64"\n", obd->obd_name, id);
1220                 f_dput(dchild);
1221                 RETURN(ERR_PTR(-ENOENT));
1222         }
1223
1224         CDEBUG(D_INODE, "got child objid %s: %p, count = %d\n",
1225                name, dchild, atomic_read(&dchild->d_count));
1226
1227         LASSERT(atomic_read(&dchild->d_count) > 0);
1228
1229         RETURN(dchild);
1230 }
1231
1232 static int filter_prepare_destroy(struct obd_device *obd, obd_id objid,
1233                                   obd_id group)
1234 {
1235         struct lustre_handle lockh;
1236         int flags = LDLM_AST_DISCARD_DATA, rc;
1237         struct ldlm_res_id res_id = { .name = { objid, 0, group, 0 } };
1238         ldlm_policy_data_t policy = { .l_extent = { 0, OBD_OBJECT_EOF } };
1239
1240         ENTRY;
1241         /* Tell the clients that the object is gone now and that they should
1242          * throw away any cached pages. */
1243         rc = ldlm_cli_enqueue(NULL, NULL, obd->obd_namespace, res_id,
1244                               LDLM_EXTENT, &policy, LCK_PW,
1245                               &flags, filter_blocking_ast, ldlm_completion_ast,
1246                               NULL, NULL, NULL, 0, NULL, &lockh);
1247
1248         /* We only care about the side-effects, just drop the lock. */
1249         if (rc == ELDLM_OK)
1250                 ldlm_lock_decref(&lockh, LCK_PW);
1251
1252         RETURN(rc);
1253 }
1254
1255 /* Caller must hold LCK_PW on parent and push us into kernel context.
1256  * Caller is also required to ensure that dchild->d_inode exists. */
1257 static int filter_destroy_internal(struct obd_device *obd, obd_id objid,
1258                                    struct dentry *dparent,
1259                                    struct dentry *dchild)
1260 {
1261         struct inode *inode = dchild->d_inode;
1262         int rc;
1263         ENTRY;
1264
1265         if (inode->i_nlink != 1 || atomic_read(&inode->i_count) != 1) {
1266                 CERROR("destroying objid %.*s nlink = %lu, count = %d\n",
1267                        dchild->d_name.len, dchild->d_name.name,
1268                        (unsigned long)inode->i_nlink,
1269                        atomic_read(&inode->i_count));
1270         }
1271
1272         rc = vfs_unlink(dparent->d_inode, dchild);
1273
1274         if (rc)
1275                 CERROR("error unlinking objid %.*s: rc %d\n",
1276                        dchild->d_name.len, dchild->d_name.name, rc);
1277
1278         RETURN(rc);
1279 }
1280
1281 static int filter_intent_policy(struct ldlm_namespace *ns,
1282                                 struct ldlm_lock **lockp, void *req_cookie,
1283                                 ldlm_mode_t mode, int flags, void *data)
1284 {
1285         struct list_head rpc_list = LIST_HEAD_INIT(rpc_list);
1286         struct ptlrpc_request *req = req_cookie;
1287         struct ldlm_lock *lock = *lockp, *l = NULL;
1288         struct ldlm_resource *res = lock->l_resource;
1289         ldlm_processing_policy policy;
1290         struct ost_lvb *res_lvb, *reply_lvb;
1291         struct ldlm_reply *rep;
1292         struct list_head *tmp;
1293         ldlm_error_t err;
1294         int tmpflags = 0, rc, repsize[2] = {sizeof(*rep), sizeof(*reply_lvb)};
1295         ENTRY;
1296
1297         policy = ldlm_get_processing_policy(res);
1298         LASSERT(policy != NULL);
1299         LASSERT(req != NULL);
1300
1301         rc = lustre_pack_reply(req, 2, repsize, NULL);
1302         if (rc)
1303                 RETURN(req->rq_status = rc);
1304
1305         rep = lustre_msg_buf(req->rq_repmsg, 0, sizeof(*rep));
1306         LASSERT(rep != NULL);
1307
1308         reply_lvb = lustre_msg_buf(req->rq_repmsg, 1, sizeof(*reply_lvb));
1309         LASSERT(reply_lvb != NULL);
1310
1311         //fixup_handle_for_resent_req(req, lock, &lockh);
1312
1313         /* If we grant any lock at all, it will be a whole-file read lock.
1314          * Call the extent policy function to see if our request can be
1315          * granted, or is blocked. */
1316         lock->l_policy_data.l_extent.start = 0;
1317         lock->l_policy_data.l_extent.end = OBD_OBJECT_EOF;
1318         lock->l_req_mode = LCK_PR;
1319
1320         lock_res_and_lock(lock);
1321         res = lock->l_resource;
1322         rc = policy(lock, &tmpflags, 0, &err, &rpc_list);
1323
1324         /* FIXME: we should change the policy function slightly, to not make
1325          * this list at all, since we just turn around and free it */
1326         while (!list_empty(&rpc_list)) {
1327                 struct ldlm_lock *wlock =
1328                         list_entry(rpc_list.next, struct ldlm_lock, l_cp_ast);
1329                 LASSERT((lock->l_flags & LDLM_FL_AST_SENT) == 0);
1330                 LASSERT(lock->l_flags & LDLM_FL_CP_REQD);
1331                 lock->l_flags &= ~LDLM_FL_CP_REQD;
1332                 list_del_init(&wlock->l_cp_ast);
1333                 LDLM_LOCK_PUT(wlock);
1334         }
1335
1336         if (rc == LDLM_ITER_CONTINUE) {
1337                 /* The lock met with no resistance; we're finished. */
1338                 unlock_res_and_lock(lock);
1339                 RETURN(ELDLM_LOCK_REPLACED);
1340         }
1341
1342         /* Do not grant any lock, but instead send GL callbacks.  The extent
1343          * policy nicely created a list of all PW locks for us.  We will choose
1344          * the highest of those which are larger than the size in the LVB, if
1345          * any, and perform a glimpse callback. */
1346         res_lvb = res->lr_lvb_data;
1347         LASSERT(res_lvb != NULL);
1348         *reply_lvb = *res_lvb;
1349
1350         list_for_each(tmp, &res->lr_granted) {
1351                 struct ldlm_lock *tmplock =
1352                         list_entry(tmp, struct ldlm_lock, l_res_link);
1353
1354                 if (tmplock->l_granted_mode == LCK_PR)
1355                         continue;
1356
1357                 if (tmplock->l_policy_data.l_extent.end <= reply_lvb->lvb_size)
1358                         continue;
1359
1360                 if (l == NULL) {
1361                         l = LDLM_LOCK_GET(tmplock);
1362                         continue;
1363                 }
1364
1365                 if (l->l_policy_data.l_extent.start >
1366                     tmplock->l_policy_data.l_extent.start)
1367                         continue;
1368
1369                 LDLM_LOCK_PUT(l);
1370                 l = LDLM_LOCK_GET(tmplock);
1371         }
1372         unlock_res(res);
1373
1374         /* There were no PW locks beyond the size in the LVB; finished. */
1375         if (l == NULL)
1376                 RETURN(ELDLM_LOCK_ABORTED);
1377
1378         if (l->l_glimpse_ast == NULL) {
1379                 /* We are racing with unlink(); just return -ENOENT */
1380                 CDEBUG(D_OTHER, "race with unlink: "LPX64"/"LPX64"\n",
1381                        res->lr_name.name[0], res->lr_name.name[2]);
1382                 rep->lock_policy_res1 = -ENOENT;
1383                 goto out;
1384         }
1385
1386         LASSERTF(l->l_glimpse_ast != NULL, "l == %p", l);
1387
1388         rc = l->l_glimpse_ast(l, NULL); /* this will update the LVB */
1389         if (rc != 0 && res->lr_namespace->ns_lvbo &&
1390             res->lr_namespace->ns_lvbo->lvbo_update) {
1391                 res->lr_namespace->ns_lvbo->lvbo_update(res, NULL, 0, 1);
1392         }
1393
1394         lock_res(res);
1395         *reply_lvb = *res_lvb;
1396         unlock_res(res);
1397 out:
1398         LDLM_LOCK_PUT(l);
1399
1400         RETURN(ELDLM_LOCK_ABORTED);
1401 }
1402
1403 static int filter_post_fs_cleanup(struct obd_device *obd)
1404 {
1405         int rc = 0;
1406
1407         rc = fsfilt_post_cleanup(obd);
1408
1409         RETURN(rc);
1410 }
1411
1412 static int filter_post_fs_setup(struct obd_device *obd)
1413 {
1414         struct filter_obd *filter = &obd->u.filter;
1415         int rc = 0;
1416         ENTRY;
1417         
1418         rc = fsfilt_post_setup(obd, filter->fo_dentry_O);
1419
1420         RETURN(rc);
1421 }
1422
1423 /* mount the file system (secretly) */
1424 int filter_common_setup(struct obd_device *obd, obd_count len, void *buf,
1425                         char *option)
1426 {
1427         struct lustre_cfg *lcfg = buf;
1428         struct filter_obd *filter = &obd->u.filter;
1429         struct lvfs_obd_ctxt *lvfs_ctxt = NULL;
1430         struct vfsmount *mnt;
1431         struct crypto_tfm *tfm;
1432         char *str;
1433         char ns_name[48];
1434         int rc = 0, i;
1435         ENTRY;
1436
1437         if ((LUSTRE_CFG_BUFLEN(lcfg, 1)) < 1 || 
1438             (LUSTRE_CFG_BUFLEN(lcfg, 2) < 1)) 
1439                 RETURN(-EINVAL);
1440
1441         obd->obd_fsops = fsfilt_get_ops(lustre_cfg_string(lcfg, 2));
1442         if (IS_ERR(obd->obd_fsops))
1443                 RETURN(PTR_ERR(obd->obd_fsops));
1444
1445         rc = lvfs_mount_fs(lustre_cfg_string(lcfg, 1), 
1446                            lustre_cfg_string(lcfg, 2), 
1447                            option, MS_NOATIME | MS_NODIRATIME, &lvfs_ctxt);
1448         if (rc) {
1449                 CERROR("lvfs_mount_fs failed: rc = %d\n", rc);
1450                 GOTO(err_ops, rc);
1451         }
1452         LASSERT(lvfs_ctxt);
1453
1454         mnt = lvfs_ctxt->loc_mnt;
1455         filter->fo_lvfs_ctxt = lvfs_ctxt;
1456
1457         if (LUSTRE_CFG_BUFLEN(lcfg, 3) > 0 && lustre_cfg_buf(lcfg, 3)) {
1458                 str = lustre_cfg_string(lcfg, 3);
1459                 if (*str == 'f') {
1460                         obd->obd_replayable = 1;
1461                         obd_sync_filter = 1;
1462                         CWARN("%s: recovery enabled\n", obd->obd_name);
1463                 } else {
1464                         if (*str != 'n') {
1465                                 CERROR("unrecognised flag '%c'\n",
1466                                        *str);
1467                         }
1468                         // XXX Robert? Why do we get errors here
1469                         // GOTO(err_mntput, rc = -EINVAL);
1470                 }
1471         }
1472
1473         filter->fo_vfsmnt = mnt;
1474         filter->fo_sb = mnt->mnt_sb;
1475         filter->fo_fstype = mnt->mnt_sb->s_type->name;
1476         CDEBUG(D_SUPER, "%s: mnt = %p\n", filter->fo_fstype, mnt);
1477
1478         OBD_SET_CTXT_MAGIC(&obd->obd_lvfs_ctxt);
1479         obd->obd_lvfs_ctxt.pwdmnt = mnt;
1480         obd->obd_lvfs_ctxt.pwd = mnt->mnt_root;
1481         obd->obd_lvfs_ctxt.fs = get_ds();
1482         obd->obd_lvfs_ctxt.cb_ops = filter_lvfs_ops;
1483
1484         ll_clear_rdonly(ll_sbdev(filter->fo_sb));
1485         
1486         rc = fsfilt_setup(obd, mnt->mnt_sb);
1487         if (rc)
1488                 GOTO(err_mntput, rc);
1489
1490         sema_init(&filter->fo_init_lock, 1);
1491         filter->fo_committed_group = 0;
1492
1493         tfm = crypto_alloc_tfm(CAPA_HMAC_ALG, 0);
1494         if (!tfm)
1495                 GOTO(err_mntput, rc = -ENOSYS);
1496
1497         filter->fo_capa_hmac = tfm;
1498         INIT_LIST_HEAD(&filter->fo_capa_keys);
1499         spin_lock_init(&filter->fo_capa_lock);
1500
1501         rc = filter_prep(obd);
1502         if (rc)
1503                 GOTO(err_capa, rc);
1504
1505         filter->fo_destroys_in_progress = 0;
1506         for (i = 0; i < 32; i++)
1507                 sema_init(&filter->fo_create_locks[i], 1);
1508
1509         spin_lock_init(&filter->fo_translock);
1510         spin_lock_init(&filter->fo_objidlock);
1511         spin_lock_init(&filter->fo_lastidlock);
1512         INIT_LIST_HEAD(&filter->fo_export_list);
1513         sema_init(&filter->fo_alloc_lock, 1);
1514         spin_lock_init(&filter->fo_r_pages.oh_lock);
1515         spin_lock_init(&filter->fo_w_pages.oh_lock);
1516         spin_lock_init(&filter->fo_r_discont_pages.oh_lock);
1517         spin_lock_init(&filter->fo_w_discont_pages.oh_lock);
1518         spin_lock_init(&filter->fo_r_discont_blocks.oh_lock);
1519         spin_lock_init(&filter->fo_w_discont_blocks.oh_lock);
1520         filter->fo_readcache_max_filesize = FILTER_MAX_CACHE_SIZE;
1521
1522         INIT_LIST_HEAD(&filter->fo_llog_list);
1523         spin_lock_init(&filter->fo_llog_list_lock);
1524
1525         spin_lock_init(&filter->fo_denylist_lock);
1526         INIT_LIST_HEAD(&filter->fo_denylist);
1527
1528         sprintf(ns_name, "filter-%s", obd->obd_uuid.uuid);
1529         obd->obd_namespace = ldlm_namespace_new(ns_name, LDLM_NAMESPACE_SERVER);
1530
1531         if (obd->obd_namespace == NULL)
1532                 GOTO(err_post, rc = -ENOMEM);
1533         obd->obd_namespace->ns_lvbp = obd;
1534         obd->obd_namespace->ns_lvbo = &filter_lvbo;
1535         ldlm_register_intent(obd->obd_namespace, filter_intent_policy);
1536
1537         ptlrpc_init_client(LDLM_CB_REQUEST_PORTAL, LDLM_CB_REPLY_PORTAL,
1538                            "filter_ldlm_cb_client", &obd->obd_ldlm_client);
1539
1540         rc = obd_llog_cat_initialize(obd, &obd->obd_llogs, 1, CATLIST);
1541         if (rc) {
1542                 CERROR("failed to setup llogging subsystems\n");
1543                 GOTO(err_post, rc);
1544         }
1545         RETURN(0);
1546
1547 err_post:
1548         filter_post(obd);
1549 err_capa:
1550         crypto_free_tfm(filter->fo_capa_hmac);
1551 err_mntput:
1552         unlock_kernel();
1553         lvfs_umount_fs(filter->fo_lvfs_ctxt);
1554         filter->fo_sb = 0;
1555         lock_kernel();
1556 err_ops:
1557         fsfilt_put_ops(obd->obd_fsops);
1558         return rc;
1559 }
1560
1561 static int filter_attach(struct obd_device *obd, obd_count len, void *data)
1562 {
1563         struct lprocfs_static_vars lvars;
1564         int rc;
1565
1566         lprocfs_init_vars(filter, &lvars);
1567         rc = lprocfs_obd_attach(obd, lvars.obd_vars);
1568         if (rc != 0)
1569                 return rc;
1570
1571         rc = lprocfs_alloc_obd_stats(obd, LPROC_FILTER_LAST);
1572         if (rc != 0)
1573                 return rc;
1574
1575         /* Init obdfilter private stats here */
1576         lprocfs_counter_init(obd->obd_stats, LPROC_FILTER_READ_BYTES,
1577                              LPROCFS_CNTR_AVGMINMAX, "read_bytes", "bytes");
1578         lprocfs_counter_init(obd->obd_stats, LPROC_FILTER_WRITE_BYTES,
1579                              LPROCFS_CNTR_AVGMINMAX, "write_bytes", "bytes");
1580
1581         return lproc_filter_attach_seqstat(obd);
1582 }
1583
1584 static int filter_detach(struct obd_device *dev)
1585 {
1586         lprocfs_free_obd_stats(dev);
1587         return lprocfs_obd_detach(dev);
1588 }
1589
1590 static int filter_setup(struct obd_device *obd, obd_count len, void *buf)
1591 {
1592         struct lustre_cfg *lcfg = buf;
1593         unsigned long page;
1594         int rc;
1595         ENTRY;
1596
1597         /* 2.6.9 selinux wants a full option page for do_kern_mount (bug6471) */
1598         page = get_zeroed_page(GFP_KERNEL);
1599         if (!page)
1600                 RETURN(-ENOMEM);
1601
1602         memcpy((void *)page, lustre_cfg_buf(lcfg, 4),
1603                LUSTRE_CFG_BUFLEN(lcfg, 4));
1604         
1605         /* all mount options including errors=remount-ro and asyncdel are passed
1606          * using 4th lcfg param. And it is good, finally we have got rid of
1607          * hardcoded fs types in the code. */
1608         rc = filter_common_setup(obd, len, buf, (void *)page);
1609         free_page(page);
1610         
1611         if (rc)
1612                 RETURN(rc);
1613         rc = filter_post_fs_setup(obd);
1614         RETURN(rc);
1615 }
1616
1617 static int filter_cleanup(struct obd_device *obd, int flags)
1618 {
1619         struct filter_obd *filter = &obd->u.filter;
1620         ll_sbdev_type save_dev;
1621         ENTRY;
1622
1623         if (flags & OBD_OPT_FAILOVER)
1624                 CERROR("%s: shutting down for failover; client state will"
1625                        " be preserved.\n", obd->obd_name);
1626
1627         if (!list_empty(&obd->obd_exports)) {
1628                 CERROR("%s: still has clients!\n", obd->obd_name);
1629                 class_disconnect_exports(obd, flags);
1630                 if (!list_empty(&obd->obd_exports)) {
1631                         CERROR("still has exports after forced cleanup?\n");
1632                         RETURN(-EBUSY);
1633                 }
1634         }
1635
1636         target_cleanup_recovery(obd);
1637         
1638         ldlm_namespace_free(obd->obd_namespace, flags & OBD_OPT_FORCE);
1639
1640         if (filter->fo_sb == NULL)
1641                 RETURN(0);
1642
1643         save_dev = ll_sbdev(filter->fo_sb);
1644         filter_post_fs_cleanup(obd);
1645         filter_post(obd);
1646
1647         shrink_dcache_parent(filter->fo_sb->s_root);
1648         filter->fo_sb = 0;
1649
1650         spin_lock(&filter->fo_denylist_lock);
1651         while (!list_empty(&filter->fo_denylist)) {
1652                 deny_sec_t *p_deny_sec = list_entry(filter->fo_denylist.next,
1653                                                     deny_sec_t, list);
1654                 list_del(&p_deny_sec->list);
1655                 OBD_FREE(p_deny_sec, sizeof(*p_deny_sec));
1656         }
1657         spin_unlock(&filter->fo_denylist_lock);
1658
1659         unlock_kernel();
1660         lvfs_umount_fs(filter->fo_lvfs_ctxt);
1661         //destroy_buffers(filter->fo_sb->s_dev);
1662         filter->fo_sb = NULL;
1663         fsfilt_put_ops(obd->obd_fsops);
1664         lock_kernel();
1665
1666         ll_clear_rdonly(save_dev);
1667
1668         RETURN(0);
1669 }
1670
1671 static int filter_process_config(struct obd_device *obd, obd_count len, void *buf)
1672 {
1673         struct lustre_cfg *lcfg = buf;
1674         struct filter_obd *filter = &obd->u.filter;
1675         int rc = 0;
1676         ENTRY;
1677
1678         switch(lcfg->lcfg_command) {
1679         case LCFG_SET_SECURITY: {
1680                 if ((LUSTRE_CFG_BUFLEN(lcfg, 1) == 0) ||
1681                     (LUSTRE_CFG_BUFLEN(lcfg, 2) == 0))
1682                         GOTO(out, rc = -EINVAL);
1683
1684                 if (!strcmp(lustre_cfg_string(lcfg, 1), "deny_sec")){
1685                         spin_lock(&filter->fo_denylist_lock);
1686                         rc = add_deny_security(lustre_cfg_string(lcfg, 2),
1687                                                &filter->fo_denylist);
1688                         spin_unlock(&filter->fo_denylist_lock);
1689                 }else {
1690                         CERROR("Unrecognized key\n");
1691                         rc = -EINVAL;
1692                 }
1693                 break;
1694         }
1695         default: {
1696                 CERROR("Unknown command: %d\n", lcfg->lcfg_command);
1697                 GOTO(out, rc = -EINVAL);
1698
1699         }
1700         }
1701 out:
1702         RETURN(rc);
1703 }
1704
1705 static int filter_connect_post(struct obd_export *exp, unsigned initial,
1706                                unsigned long connect_flags)
1707 {
1708         struct obd_device *obd = exp->exp_obd;
1709         struct filter_export_data *fed;
1710         char str[PTL_NALFMT_SIZE];
1711         struct obd_llogs *llog;
1712         struct llog_ctxt *ctxt;
1713         int rc = 0;
1714         ENTRY;
1715
1716         fed = &exp->exp_filter_data;
1717         if (fed->fed_group < FILTER_MIN_GROUPS)
1718                 RETURN(0);
1719
1720         /* initialize llogs for connections from MDS */
1721         llog = filter_grab_llog_for_group(obd, fed->fed_group, exp);
1722         LASSERT(llog != NULL);
1723
1724         ctxt = llog_get_context(llog, LLOG_UNLINK_REPL_CTXT);
1725         LASSERT(ctxt != NULL);
1726
1727         rc = llog_receptor_accept(ctxt, exp->exp_imp_reverse);
1728         
1729         portals_nid2str(exp->exp_connection->c_peer.peer_ni->pni_number,
1730                         exp->exp_connection->c_peer.peer_id.nid, str);
1731         
1732         CDEBUG(D_OTHER, "%s: init llog ctxt for export "LPX64"/%s, group %d\n",
1733                obd->obd_name, exp->exp_connection->c_peer.peer_id.nid,
1734                str, fed->fed_group);
1735
1736         RETURN(rc);
1737 }
1738
1739 /* nearly identical to mds_connect */
1740 static int filter_connect(struct lustre_handle *conn, struct obd_device *obd,
1741                           struct obd_uuid *cluuid,
1742                           struct obd_connect_data *data,
1743                           unsigned long connect_flags)
1744 {
1745         struct obd_export *exp;
1746         struct filter_export_data *fed;
1747         struct filter_client_data *fcd = NULL;
1748         struct filter_obd *filter = &obd->u.filter;
1749         struct lvfs_run_ctxt saved;
1750         int rc, group;
1751         ENTRY;
1752
1753         if (conn == NULL || obd == NULL || cluuid == NULL)
1754                 RETURN(-EINVAL);
1755
1756         rc = class_connect(conn, obd, cluuid);
1757         if (rc)
1758                 RETURN(rc);
1759         exp = class_conn2export(conn);
1760         LASSERT(exp != NULL);
1761
1762         fed = &exp->exp_filter_data;
1763
1764         spin_lock_init(&fed->fed_lock);
1765
1766        /* connection from MDS */
1767         group = connect_flags;
1768         if (obd->obd_replayable) {
1769                 OBD_ALLOC(fcd, sizeof(*fcd));
1770                 if (!fcd) {
1771                         CERROR("filter: out of memory for client data\n");
1772                         GOTO(cleanup, rc = -ENOMEM);
1773                 }
1774
1775                 memcpy(fcd->fcd_uuid, cluuid, sizeof(fcd->fcd_uuid));
1776                 fed->fed_fcd = fcd;
1777                 fed->fed_fcd->fcd_group = group;
1778                 rc = filter_client_add(obd, filter, fed, -1);
1779                 if (rc)
1780                         GOTO(cleanup, rc);
1781         }
1782         CWARN("%s: Received MDS connection ("LPX64"); group %d\n",
1783               obd->obd_name, exp->exp_handle.h_cookie, group);
1784  
1785         if (group == 0)
1786                 GOTO(cleanup, rc);
1787         
1788         if (fed->fed_group != 0 && fed->fed_group != group) {
1789                 char str[PTL_NALFMT_SIZE];
1790                 portals_nid2str(exp->exp_connection->c_peer.peer_ni->pni_number,
1791                                 exp->exp_connection->c_peer.peer_id.nid, str);
1792                 CERROR("!!! This export (nid "LPX64"/%s) used object group %d "
1793                        "earlier; now it's trying to use group %d!  This could "
1794                        "be a bug in the MDS.  Tell CFS.\n",
1795                        exp->exp_connection->c_peer.peer_id.nid, str,
1796                        fed->fed_group, group);
1797                 GOTO(cleanup, rc = -EPROTO);
1798         }
1799         fed->fed_group = group;
1800
1801         push_ctxt(&saved, &obd->obd_lvfs_ctxt, NULL);
1802         rc = filter_read_groups(obd, group, 1);
1803         pop_ctxt(&saved, &obd->obd_lvfs_ctxt, NULL);
1804         if (rc != 0) {
1805                 CERROR("can't read group %u\n", group);
1806                 GOTO(cleanup, rc);
1807         }
1808 cleanup:
1809         if (rc) {
1810                 if (fcd)
1811                         OBD_FREE(fcd, sizeof(*fcd));
1812                 class_disconnect(exp, 0);
1813         } else {
1814                 class_export_put(exp);
1815         }
1816         return rc;
1817 }
1818
1819 static int filter_precleanup(struct obd_device *obd, int flags)
1820 {
1821         struct filter_group_llog *log;
1822         struct filter_obd *filter;
1823         int rc = 0;
1824         ENTRY;
1825
1826         filter = &obd->u.filter;
1827
1828         spin_lock(&filter->fo_llog_list_lock);
1829         while (!list_empty(&filter->fo_llog_list)) {
1830                 log = list_entry(filter->fo_llog_list.next,
1831                                  struct filter_group_llog, list);
1832                 list_del(&log->list);
1833                 spin_unlock(&filter->fo_llog_list_lock);
1834
1835                 rc = obd_llog_finish(obd, log->llogs, 0);
1836                 if (rc)
1837                         CERROR("failed to cleanup llogging subsystem for %u\n",
1838                                 log->group);
1839                 OBD_FREE(log->llogs, sizeof(*(log->llogs)));
1840                 OBD_FREE(log, sizeof(*log));
1841                 spin_lock(&filter->fo_llog_list_lock);
1842         }
1843         spin_unlock(&filter->fo_llog_list_lock);
1844
1845         rc = obd_llog_finish(obd, &obd->obd_llogs, 0);
1846         if (rc)
1847                 CERROR("failed to cleanup llogging subsystem\n");
1848
1849         RETURN(rc);
1850 }
1851
1852 /* Do extra sanity checks for grant accounting.  We do this at connect,
1853  * disconnect, and statfs RPC time, so it shouldn't be too bad.  We can
1854  * always get rid of it or turn it off when we know accounting is good. */
1855 static void filter_grant_sanity_check(struct obd_device *obd, const char *func)
1856 {
1857         struct filter_export_data *fed;
1858         struct obd_export *exp;
1859         obd_size maxsize = obd->obd_osfs.os_blocks * obd->obd_osfs.os_bsize;
1860         obd_size tot_dirty = 0, tot_pending = 0, tot_granted = 0;
1861         obd_size fo_tot_dirty, fo_tot_pending, fo_tot_granted;
1862         int level = D_CACHE;
1863
1864         if (list_empty(&obd->obd_exports))
1865                 return;
1866
1867         spin_lock(&obd->obd_osfs_lock);
1868         spin_lock(&obd->obd_dev_lock);
1869         list_for_each_entry(exp, &obd->obd_exports, exp_obd_chain) {
1870                 fed = &exp->exp_filter_data;
1871                 if (fed->fed_grant < 0 || fed->fed_pending < 0 ||
1872                     fed->fed_dirty < 0)
1873                         level = D_ERROR;
1874                 if (maxsize > 0) { /* we may not have done a statfs yet */
1875                         LASSERTF(fed->fed_grant + fed->fed_pending <= maxsize,
1876                                  "cli %s/%p %ld+%ld > "LPU64"\n",
1877                                  exp->exp_client_uuid.uuid, exp,
1878                                  fed->fed_grant, fed->fed_pending, maxsize);
1879                         LASSERTF(fed->fed_dirty <= maxsize,
1880                                  "cli %s/%p %ld > "LPU64"\n",
1881                                  exp->exp_client_uuid.uuid, exp,
1882                                  fed->fed_dirty, maxsize);
1883                 }
1884                 CDEBUG(level, "%s: cli %s/%p dirty %ld pend %ld grant %ld\n",
1885                        obd->obd_name, exp->exp_client_uuid.uuid, exp,
1886                        fed->fed_dirty, fed->fed_pending, fed->fed_grant);
1887                 tot_granted += fed->fed_grant + fed->fed_pending;
1888                 tot_pending += fed->fed_pending;
1889                 tot_dirty += fed->fed_dirty;
1890         }
1891         fo_tot_granted = obd->u.filter.fo_tot_granted;
1892         fo_tot_pending = obd->u.filter.fo_tot_pending;
1893         fo_tot_dirty = obd->u.filter.fo_tot_dirty;
1894         spin_unlock(&obd->obd_dev_lock);
1895         spin_unlock(&obd->obd_osfs_lock);
1896
1897         /* Do these assertions outside the spinlocks so we don't kill system */
1898         if (tot_granted != fo_tot_granted)
1899                 CERROR("%s: tot_granted "LPU64" != fo_tot_granted "LPU64"\n",
1900                        func, tot_granted, fo_tot_granted);
1901         if (tot_pending != fo_tot_pending)
1902                 CERROR("%s: tot_pending "LPU64" != fo_tot_pending "LPU64"\n",
1903                        func, tot_pending, fo_tot_pending);
1904         if (tot_dirty != fo_tot_dirty)
1905                 CERROR("%s: tot_dirty "LPU64" != fo_tot_dirty "LPU64"\n",
1906                        func, tot_dirty, fo_tot_dirty);
1907         if (tot_pending > tot_granted)
1908                 CERROR("%s: tot_pending "LPU64" > tot_granted "LPU64"\n",
1909                        func, tot_pending, tot_granted);
1910         if (tot_granted > maxsize)
1911                 CERROR("%s: tot_granted "LPU64" > maxsize "LPU64"\n",
1912                        func, tot_granted, maxsize);
1913         if (tot_dirty > maxsize)
1914                 CERROR("%s: tot_dirty "LPU64" > maxsize "LPU64"\n",
1915                        func, tot_dirty, maxsize);
1916 }
1917
1918 /* Remove this client from the grant accounting totals.  We also remove
1919  * the export from the obd device under the osfs and dev locks to ensure
1920  * that the filter_grant_sanity_check() calculations are always valid.
1921  * The client should do something similar when it invalidates its import. */
1922 static void filter_grant_discard(struct obd_export *exp)
1923 {
1924         struct obd_device *obd = exp->exp_obd;
1925         struct filter_obd *filter = &obd->u.filter;
1926         struct filter_export_data *fed = &exp->exp_filter_data;
1927         int level = D_CACHE;
1928
1929         spin_lock(&obd->obd_osfs_lock);
1930         spin_lock(&exp->exp_obd->obd_dev_lock);
1931         list_del_init(&exp->exp_obd_chain);
1932         spin_unlock(&exp->exp_obd->obd_dev_lock);
1933
1934         if (fed->fed_dirty < 0 || fed->fed_grant < 0 || fed->fed_pending < 0)
1935                 level = D_ERROR;
1936         CDEBUG(level, "%s: cli %s/%p dirty %ld pend %ld grant %ld\n",
1937                obd->obd_name, exp->exp_client_uuid.uuid, exp,
1938                fed->fed_dirty, fed->fed_pending, fed->fed_grant);
1939
1940         LASSERTF(filter->fo_tot_granted >= fed->fed_grant,
1941                  "%s: tot_granted "LPU64" cli %s/%p fed_grant %ld\n",
1942                  obd->obd_name, filter->fo_tot_granted,
1943                  exp->exp_client_uuid.uuid, exp, fed->fed_grant);
1944         filter->fo_tot_granted -= fed->fed_grant;
1945         LASSERTF(filter->fo_tot_pending >= fed->fed_pending,
1946                  "%s: tot_pending "LPU64" cli %s/%p fed_pending %ld\n",
1947                  obd->obd_name, filter->fo_tot_pending,
1948                  exp->exp_client_uuid.uuid, exp, fed->fed_pending);
1949         LASSERTF(filter->fo_tot_dirty >= fed->fed_dirty,
1950                  "%s: tot_dirty "LPU64" cli %s/%p fed_dirty %ld\n",
1951                  obd->obd_name, filter->fo_tot_dirty,
1952                  exp->exp_client_uuid.uuid, exp, fed->fed_dirty);
1953         filter->fo_tot_dirty -= fed->fed_dirty;
1954         fed->fed_dirty = 0;
1955         fed->fed_grant = 0;
1956
1957         spin_unlock(&obd->obd_osfs_lock);
1958 }
1959
1960 static int filter_destroy_export(struct obd_export *exp)
1961 {
1962         ENTRY;
1963
1964         if (exp->exp_filter_data.fed_pending)
1965                 CERROR("%s: cli %s/%p has %lu pending on destroyed export\n",
1966                        exp->exp_obd->obd_name, exp->exp_client_uuid.uuid,
1967                        exp, exp->exp_filter_data.fed_pending);
1968
1969         target_destroy_export(exp);
1970
1971         if (exp->exp_obd->obd_replayable)
1972                 filter_client_free(exp, exp->exp_flags);
1973
1974         filter_grant_discard(exp);
1975         if (!(exp->exp_flags & OBD_OPT_FORCE))
1976                 filter_grant_sanity_check(exp->exp_obd, __FUNCTION__);
1977
1978         RETURN(0);
1979 }
1980
1981 static void filter_sync_llogs(struct obd_device *obd, struct obd_export *dexp)
1982 {
1983         struct filter_group_llog *fglog, *nlog;
1984         struct filter_obd *filter;
1985         int worked = 0, group;
1986         struct llog_ctxt *ctxt;
1987         ENTRY;
1988
1989         filter = &obd->u.filter;
1990
1991         /* we can't sync log holding spinlock. also, we do not want to get
1992          * into livelock. so we do following: loop over MDS's exports in
1993          * group order and skip already synced llogs -bzzz */
1994         do {
1995                 /* look for group with min. number, but > worked */
1996                 fglog = NULL;
1997                 group = 1 << 30;
1998                 spin_lock(&filter->fo_llog_list_lock);
1999                 list_for_each_entry(nlog, &filter->fo_llog_list, list) {
2000                        
2001                         if (nlog->group <= worked) {
2002                                 /* this group is already synced */
2003                                 continue;
2004                         }
2005         
2006                         if (group < nlog->group) {
2007                                 /* we have group with smaller number to sync */
2008                                 continue;
2009                         }
2010
2011                         /* store current minimal group */
2012                         fglog = nlog;
2013                         group = nlog->group;
2014                 }
2015                 spin_unlock(&filter->fo_llog_list_lock);
2016
2017                 if (fglog == NULL)
2018                         break;
2019
2020                 worked = fglog->group;
2021                 if (fglog->exp && (dexp == fglog->exp || dexp == NULL)) {
2022                         ctxt = llog_get_context(fglog->llogs,
2023                                         LLOG_UNLINK_REPL_CTXT);
2024                         LASSERT(ctxt != NULL);
2025                         llog_sync(ctxt, fglog->exp);
2026                 }
2027         } while (fglog != NULL);
2028 }
2029
2030 /* also incredibly similar to mds_disconnect */
2031 static int filter_disconnect(struct obd_export *exp, unsigned long flags)
2032 {
2033         struct obd_device *obd = exp->exp_obd;
2034         unsigned long irqflags;
2035         int rc;
2036         ENTRY;
2037
2038         LASSERT(exp);
2039         class_export_get(exp);
2040
2041         spin_lock_irqsave(&exp->exp_lock, irqflags);
2042         exp->exp_flags = flags;
2043         spin_unlock_irqrestore(&exp->exp_lock, irqflags);
2044
2045         if (!(flags & OBD_OPT_FORCE))
2046                 filter_grant_sanity_check(obd, __FUNCTION__);
2047         filter_grant_discard(exp);
2048
2049         /* Disconnect early so that clients can't keep using export */
2050         rc = class_disconnect(exp, flags);
2051
2052         ldlm_cancel_locks_for_export(exp);
2053
2054         fsfilt_sync(obd, obd->u.filter.fo_sb);
2055
2056         /* flush any remaining cancel messages out to the target */
2057         filter_sync_llogs(obd, exp);
2058         class_export_put(exp);
2059         RETURN(rc);
2060 }
2061
2062 struct dentry *__filter_oa2dentry(struct obd_device *obd,
2063                                   struct obdo *oa, const char *what)
2064 {
2065         struct dentry *dchild = NULL;
2066         obd_gr group = 0;
2067         ENTRY;
2068
2069         if (oa->o_valid & OBD_MD_FLGROUP)
2070                 group = oa->o_gr;
2071
2072         dchild = filter_id2dentry(obd, NULL, group, oa->o_id);
2073
2074         if (IS_ERR(dchild)) {
2075                 CERROR("%s error looking up object: "LPU64"\n",
2076                        what, oa->o_id);
2077                 RETURN(dchild);
2078         }
2079
2080         if (dchild->d_inode == NULL) {
2081                 CDEBUG(D_INFO, "%s: %s on non-existent object: "
2082                        LPU64"\n", obd->obd_name, what, oa->o_id);
2083                 f_dput(dchild);
2084                 RETURN(ERR_PTR(-ENOENT));
2085         }
2086
2087         RETURN(dchild);
2088 }
2089
2090 static int filter_getattr(struct obd_export *exp, struct obdo *oa,
2091                           struct lov_stripe_md *md)
2092 {
2093         struct dentry *dentry = NULL;
2094         struct obd_device *obd;
2095         int rc = 0;
2096         ENTRY;
2097
2098         obd = class_exp2obd(exp);
2099         if (obd == NULL) {
2100                 CDEBUG(D_IOCTL, "invalid client cookie "LPX64"\n",
2101                        exp->exp_handle.h_cookie);
2102                 RETURN(-EINVAL);
2103         }
2104
2105         dentry = filter_oa2dentry(obd, oa);
2106         if (IS_ERR(dentry))
2107                 RETURN(PTR_ERR(dentry));
2108
2109         /* Limit the valid bits in the return data to what we actually use */
2110         oa->o_valid = OBD_MD_FLID;
2111         obdo_from_inode(oa, dentry->d_inode, FILTER_VALID_FLAGS);
2112
2113         f_dput(dentry);
2114         RETURN(rc);
2115 }
2116
2117 int filter_setattr_internal(struct obd_export *exp, struct dentry *dentry,
2118                             struct obdo *oa, struct obd_trans_info *oti)
2119 {
2120         struct filter_obd *filter;
2121         struct iattr iattr;
2122         void *handle;
2123         int rc, err;
2124         ENTRY;
2125
2126         LASSERT(dentry != NULL);
2127         LASSERT(!IS_ERR(dentry));
2128         LASSERT(dentry->d_inode != NULL);
2129         
2130         filter = &exp->exp_obd->u.filter;
2131         iattr_from_obdo(&iattr, oa, oa->o_valid);
2132
2133         if (iattr.ia_valid & ATTR_SIZE)
2134                 down(&dentry->d_inode->i_sem);
2135         handle = fsfilt_start(exp->exp_obd, dentry->d_inode,
2136                               FSFILT_OP_SETATTR, oti);
2137         if (IS_ERR(handle))
2138                 GOTO(out_unlock, rc = PTR_ERR(handle));
2139
2140         /* XXX this could be a rwsem instead, if filter_preprw played along */
2141         if (iattr.ia_valid & ATTR_ATTR_FLAG)
2142                 rc = fsfilt_iocontrol(exp->exp_obd, dentry->d_inode,
2143                                       NULL, EXT3_IOC_SETFLAGS,
2144                                       (long)&iattr.ia_attr_flags);
2145         else
2146                 rc = fsfilt_setattr(exp->exp_obd, dentry, handle,
2147                                     &iattr, 1);
2148         
2149         rc = filter_finish_transno(exp, oti, rc);
2150         
2151         err = fsfilt_commit(exp->exp_obd, filter->fo_sb,
2152                             dentry->d_inode, handle,
2153                             exp->exp_sync);
2154         if (err) {
2155                 CERROR("error on commit, err = %d\n", err);
2156                 if (!rc)
2157                         rc = err;
2158         }
2159         EXIT;
2160 out_unlock:
2161         if (iattr.ia_valid & ATTR_SIZE)
2162                 up(&dentry->d_inode->i_sem);
2163         return rc;
2164 }
2165
2166 /* this is called from filter_truncate() until we have filter_punch() */
2167 int filter_setattr(struct obd_export *exp, struct obdo *oa,
2168                    struct lov_stripe_md *md, struct obd_trans_info *oti,
2169                    struct lustre_capa *capa)
2170 {
2171         struct ldlm_res_id res_id = { .name = { oa->o_id, 0, oa->o_gr, 0 } };
2172         struct ldlm_valblock_ops *ns_lvbo;
2173         struct lvfs_run_ctxt saved;
2174         struct filter_obd *filter;
2175         struct ldlm_resource *res;
2176         struct dentry *dentry;
2177         /*obd_uid uid;*/
2178         /*obd_gid gid;*/
2179         int rc;
2180         ENTRY;
2181
2182         LASSERT(oti != NULL);
2183
2184         filter = &exp->exp_obd->u.filter;
2185         push_ctxt(&saved, &exp->exp_obd->obd_lvfs_ctxt, NULL);
2186         /* pass nid through */
2187         current->user->nid = oti->oti_nid;
2188         
2189         /* make sure that object is allocated. */
2190         dentry = filter_crow_object(exp->exp_obd, oa);
2191         if (IS_ERR(dentry))
2192                 GOTO(out_pop, rc = PTR_ERR(dentry));
2193
2194         rc = filter_verify_fid(exp, dentry->d_inode, capa);
2195         if (rc)
2196                 GOTO(out_pop, rc);
2197
2198         lock_kernel();
2199
2200         /* setting objects attributes (including owner/group) */
2201         rc = filter_setattr_internal(exp, dentry, oa, oti);
2202         if (rc)
2203                 GOTO(out_unlock, rc);
2204
2205         res = ldlm_resource_get(exp->exp_obd->obd_namespace, NULL,
2206                                 res_id, LDLM_EXTENT, 0);
2207         
2208         if (res != NULL) {
2209                 ns_lvbo = res->lr_namespace->ns_lvbo;
2210                 if (ns_lvbo && ns_lvbo->lvbo_update)
2211                         rc = ns_lvbo->lvbo_update(res, NULL, 0, 0);
2212                 ldlm_resource_putref(res);
2213         }
2214         
2215         oa->o_valid = OBD_MD_FLID;
2216         obdo_from_inode(oa, dentry->d_inode, FILTER_VALID_FLAGS);
2217
2218         EXIT;
2219 out_unlock:
2220         unlock_kernel();
2221         f_dput(dentry);
2222 out_pop:
2223         pop_ctxt(&saved, &exp->exp_obd->obd_lvfs_ctxt, NULL);
2224         return rc;
2225 }
2226
2227 /* XXX identical to osc_unpackmd */
2228 static int filter_unpackmd(struct obd_export *exp, struct lov_stripe_md **lsmp,
2229                            struct lov_mds_md *lmm, int lmm_bytes)
2230 {
2231         int lsm_size;
2232         ENTRY;
2233
2234         if (lmm != NULL) {
2235                 if (lmm_bytes < sizeof (*lmm)) {
2236                         CERROR("lov_mds_md too small: %d, need %d\n",
2237                                lmm_bytes, (int)sizeof(*lmm));
2238                         RETURN(-EINVAL);
2239                 }
2240                 /* XXX LOV_MAGIC etc check? */
2241
2242                 if (lmm->lmm_object_id == cpu_to_le64(0)) {
2243                         CERROR("lov_mds_md: zero lmm_object_id\n");
2244                         RETURN(-EINVAL);
2245                 }
2246         }
2247
2248         lsm_size = lov_stripe_md_size(1);
2249         if (lsmp == NULL)
2250                 RETURN(lsm_size);
2251
2252         if (*lsmp != NULL && lmm == NULL) {
2253                 OBD_FREE(*lsmp, lsm_size);
2254                 *lsmp = NULL;
2255                 RETURN(0);
2256         }
2257
2258         if (*lsmp == NULL) {
2259                 OBD_ALLOC(*lsmp, lsm_size);
2260                 if (*lsmp == NULL)
2261                         RETURN(-ENOMEM);
2262
2263                 loi_init((*lsmp)->lsm_oinfo);
2264         }
2265
2266         if (lmm != NULL) {
2267                 /* XXX zero *lsmp? */
2268                 (*lsmp)->lsm_object_id = le64_to_cpu (lmm->lmm_object_id);
2269                 LASSERT((*lsmp)->lsm_object_id);
2270         }
2271
2272         (*lsmp)->lsm_maxbytes = LUSTRE_STRIPE_MAXBYTES;
2273
2274         RETURN(lsm_size);
2275 }
2276
2277 static int filter_statfs(struct obd_device *obd, struct obd_statfs *osfs,
2278                          unsigned long max_age)
2279 {
2280         struct filter_obd *filter = &obd->u.filter;
2281         int blockbits = filter->fo_sb->s_blocksize_bits;
2282         int rc;
2283         ENTRY;
2284
2285         /* at least try to account for cached pages.  its still racey and
2286          * might be under-reporting if clients haven't announced their
2287          * caches with brw recently */
2288         spin_lock(&obd->obd_osfs_lock);
2289         rc = fsfilt_statfs(obd, filter->fo_sb, max_age);
2290         memcpy(osfs, &obd->obd_osfs, sizeof(*osfs));
2291         spin_unlock(&obd->obd_osfs_lock);
2292
2293         CDEBUG(D_SUPER | D_CACHE, "blocks cached "LPU64" granted "LPU64
2294                " pending "LPU64" free "LPU64" avail "LPU64"\n",
2295                filter->fo_tot_dirty, filter->fo_tot_granted,
2296                filter->fo_tot_pending,
2297                osfs->os_bfree << blockbits, osfs->os_bavail << blockbits);
2298
2299         filter_grant_sanity_check(obd, __FUNCTION__);
2300
2301         osfs->os_bavail -= min(osfs->os_bavail,
2302                                (filter->fo_tot_dirty + filter->fo_tot_pending +
2303                                 osfs->os_bsize -1) >> blockbits);
2304
2305         RETURN(rc);
2306 }
2307
2308 int filter_create_object(struct obd_device *obd, struct obdo *oa)
2309 {
2310         struct dentry *dparent = NULL;
2311         struct dentry *dchild = NULL;
2312         struct lvfs_ucred uc = {0,};
2313         struct lvfs_run_ctxt saved;
2314         struct filter_obd *filter;
2315         int cleanup_phase = 0;
2316         int err = 0, rc = 0;
2317         void *handle = NULL;
2318         void *lock = NULL;
2319         obd_uid uid;
2320         obd_gid gid;
2321         ENTRY;
2322
2323         filter = &obd->u.filter;
2324
2325         down(&filter->fo_create_locks[oa->o_gr]);
2326
2327         if (test_bit(oa->o_gr, &filter->fo_destroys_in_progress)) {
2328                 CWARN("%s: create aborted by destroy\n",
2329                       obd->obd_name);
2330                 GOTO(out, rc = -EALREADY);
2331         }
2332
2333         CDEBUG(D_INFO, "create objid "LPU64"\n", oa->o_id);
2334
2335         dparent = filter_parent_lock(obd, oa->o_gr, oa->o_id, &lock);
2336         if (IS_ERR(dparent))
2337                 GOTO(cleanup, rc = PTR_ERR(dparent));
2338         cleanup_phase = 1;
2339
2340         dchild = filter_id2dentry(obd, dparent, oa->o_gr, oa->o_id);
2341         if (IS_ERR(dchild))
2342                 GOTO(cleanup, rc = PTR_ERR(dchild));
2343         cleanup_phase = 2;
2344
2345         if (dchild->d_inode != NULL)
2346                 GOTO(cleanup, rc = 0);
2347
2348         handle = fsfilt_start_log(obd, dparent->d_inode,
2349                                   FSFILT_OP_CREATE, NULL, 1);
2350         if (IS_ERR(handle))
2351                 GOTO(cleanup, rc = PTR_ERR(handle));
2352         cleanup_phase = 3;
2353
2354         uid = oa->o_valid & OBD_MD_FLUID ? oa->o_uid : 0;
2355         gid = oa->o_valid & OBD_MD_FLGID ? oa->o_gid : 0;
2356         
2357         uc.luc_uid = uid;
2358         uc.luc_gid = gid;
2359         uc.luc_fsuid = uid;
2360         uc.luc_fsgid = gid;
2361         uc.luc_cap = current->cap_effective;
2362         cap_raise(uc.luc_cap, CAP_SYS_RESOURCE);
2363
2364         push_ctxt(&saved, &obd->obd_lvfs_ctxt, &uc);
2365         rc = ll_vfs_create(dparent->d_inode, dchild, S_IFREG, NULL);
2366         pop_ctxt(&saved, &obd->obd_lvfs_ctxt, &uc);
2367
2368         if (rc) {
2369                 CERROR("create failed rc = %d\n", rc);
2370                 GOTO(cleanup, rc);
2371         }
2372
2373         /* nobody else is touching this newly created object */
2374         LASSERT(dchild->d_inode);
2375         if (oa->o_valid & OBD_MD_FLIFID) {
2376                 rc = fsfilt_set_md(obd, dchild->d_inode, handle, obdo_id(oa),
2377                                    sizeof(struct lustre_id), EA_SID);
2378                 if (rc) {
2379                         CERROR("store fid in object failed! rc:%d\n", rc);
2380                         GOTO(cleanup, rc);
2381                 }
2382         } else {
2383                 CWARN("create object without lustre id!\n");
2384                 portals_debug_dumpstack(NULL);
2385         }
2386
2387         fsfilt_set_fs_flags(obd, dparent->d_inode, SM_DO_REC);
2388
2389         /* save last created object id */
2390         filter_save_last_id(filter, oa->o_gr, oa->o_id);
2391
2392         rc = filter_update_last_objid(obd, oa->o_gr, 0);
2393         if (rc) {
2394                 CERROR("unable to write lastobjid, but "
2395                        "orphans were deleted, err = %d\n",
2396                        rc);
2397                 rc = 0;
2398         }
2399 cleanup:
2400         switch(cleanup_phase) {
2401         case 3:
2402                 err = fsfilt_commit(obd, filter->fo_sb,
2403                                     dparent->d_inode, handle, 0);
2404                 if (err) {
2405                         CERROR("error on commit, err = %d\n", err);
2406                         if (!rc)
2407                                 rc = err;
2408                 }
2409         case 2:
2410                 f_dput(dchild);
2411         case 1:
2412                 filter_parent_unlock(dparent, lock);
2413         case 0:
2414                 break;
2415         }
2416
2417         if (rc)
2418                 GOTO(out, rc);
2419
2420 out:
2421         up(&filter->fo_create_locks[oa->o_gr]);
2422         RETURN(rc);
2423 }
2424
2425 struct dentry *
2426 filter_crow_object(struct obd_device *obd, struct obdo *oa)
2427 {
2428         struct dentry *dentry;
2429         /* obd_uid uid; */
2430         /* obd_gid gid; */
2431         int rc = 0;
2432         ENTRY;
2433
2434         /* check if object is already allocated */
2435         dentry = filter_id2dentry(obd, NULL, oa->o_gr, oa->o_id);
2436         if (IS_ERR(dentry))
2437                 RETURN(dentry);
2438
2439         if (dentry->d_inode)
2440                 RETURN(dentry);
2441
2442         f_dput(dentry);
2443         CDEBUG(D_INODE, "OSS object "LPU64"/"LPU64
2444                " does not exists - allocate it now\n",
2445                oa->o_id, oa->o_gr);
2446         /*
2447         uid = oa->o_valid & OBD_MD_FLUID ? oa->o_uid : 0;
2448         gid = oa->o_valid & OBD_MD_FLGID ? oa->o_gid : 0;
2449         */
2450         rc = filter_create_object(obd, oa);
2451         if (rc) {
2452                 CERROR("cannot create OSS object "LPU64"/"LPU64
2453                        ", err = %d\n", oa->o_id, oa->o_gr, rc);
2454                 RETURN(ERR_PTR(rc));
2455         }
2456
2457         /* lookup for just created object and return it to caller */
2458         dentry = filter_id2dentry(obd, NULL, oa->o_gr, oa->o_id);
2459         if (IS_ERR(dentry))
2460                 RETURN(dentry);
2461                 
2462         if (dentry->d_inode == NULL) {
2463                 f_dput(dentry);
2464                 dentry = ERR_PTR(-ENOENT);
2465                 CERROR("cannot find just created OSS object "
2466                        LPU64"/"LPU64" err = %d\n", oa->o_id,
2467                        oa->o_gr, (int)PTR_ERR(dentry));
2468                 RETURN(dentry);
2469         }
2470         RETURN(dentry);
2471 }
2472
2473 static int
2474 filter_clear_orphans(struct obd_export *exp, struct obdo *oa)
2475 {
2476         struct obd_device *obd = NULL;
2477         struct filter_obd *filter;
2478         struct obdo *doa = NULL;
2479         int rc = 0, orphans;
2480         __u64 last, id;
2481         ENTRY;
2482         
2483         LASSERT(oa);
2484         LASSERT(oa->o_gr != 0);
2485         LASSERT(oa->o_valid & OBD_MD_FLGROUP);
2486
2487         obd = exp->exp_obd;
2488         filter = &obd->u.filter;
2489
2490         last = filter_last_id(filter, oa->o_gr);
2491         orphans = last - oa->o_id;
2492         
2493         if (orphans <= 0)
2494                 RETURN(0);
2495                 
2496         doa = obdo_alloc();
2497         if (doa == NULL)
2498                 RETURN(-ENOMEM);
2499
2500         doa->o_gr = oa->o_gr;
2501         doa->o_mode = S_IFREG;
2502         doa->o_valid = oa->o_valid & (OBD_MD_FLGROUP | OBD_MD_FLID);
2503
2504         set_bit(doa->o_gr, &filter->fo_destroys_in_progress);
2505         down(&filter->fo_create_locks[doa->o_gr]);
2506         if (!test_bit(doa->o_gr, &filter->fo_destroys_in_progress)) {
2507                 CERROR("%s:["LPU64"] destroy_in_progress already cleared\n",
2508                        exp->exp_obd->obd_name, doa->o_gr);
2509                 up(&filter->fo_create_locks[doa->o_gr]);
2510                 GOTO(out_free_doa, 0);
2511         }
2512
2513         CDEBUG(D_ERROR, "%s:["LPU64"] deleting orphan objects from "LPU64" to "
2514               LPU64"\n", exp->exp_obd->obd_name, doa->o_gr,
2515               oa->o_id + 1, last);
2516         
2517         for (id = oa->o_id + 1; id <= last; id++) {
2518                 doa->o_id = id;
2519                 filter_destroy(exp, doa, NULL, NULL);
2520         }
2521
2522         CDEBUG(D_ERROR, "%s:["LPU64"] after destroy: set last_objids = "
2523                LPU64"\n", exp->exp_obd->obd_name, doa->o_gr, last + 1);
2524
2525         /* return next free id to be used as a new start of sequence -bzzz */
2526         oa->o_id = last + 1;
2527
2528         filter_set_last_id(filter, oa->o_gr, oa->o_id);
2529         clear_bit(doa->o_gr, &filter->fo_destroys_in_progress);
2530         up(&filter->fo_create_locks[oa->o_gr]);
2531
2532         EXIT;
2533 out_free_doa:
2534         obdo_free(doa);
2535         return rc;
2536 }
2537
2538 /*
2539  * by now this function is only needed as entry point for deleting orphanes on
2540  * OSS as objects are created on first write attempt. --umka
2541  */
2542 static int
2543 filter_create(struct obd_export *exp, struct obdo *oa, void *acl,
2544               int acl_size, struct lov_stripe_md **ea,
2545               struct obd_trans_info *oti)
2546 {
2547         struct filter_export_data *fed;
2548         struct obd_device *obd = NULL;
2549         int group = oa->o_gr, rc = 0;
2550         struct lvfs_run_ctxt saved;
2551         struct filter_obd *filter;
2552         char str[PTL_NALFMT_SIZE];
2553         ENTRY;
2554
2555         LASSERT(acl == NULL && acl_size == 0);
2556
2557         if (!(oa->o_valid & OBD_MD_FLGROUP) || group == 0) {
2558                 portals_nid2str(exp->exp_connection->c_peer.peer_ni->pni_number,
2559                                 exp->exp_connection->c_peer.peer_id.nid, str);
2560                 CERROR("!!! nid "LPX64"/%s sent invalid object group %d\n",
2561                        exp->exp_connection->c_peer.peer_id.nid, str, group);
2562                 RETURN(-EINVAL);
2563         }
2564
2565         obd = exp->exp_obd;
2566         fed = &exp->exp_filter_data;
2567         filter = &obd->u.filter;
2568
2569         if (fed->fed_group != group) {
2570                 portals_nid2str(exp->exp_connection->c_peer.peer_ni->pni_number,
2571                                 exp->exp_connection->c_peer.peer_id.nid, str);
2572                 CERROR("!!! this export (nid "LPX64"/%s) used object group %d "
2573                        "earlier; now it's trying to use group %d!  This could "
2574                        "be a bug in the MDS.  Tell CFS.\n",
2575                        exp->exp_connection->c_peer.peer_id.nid, str,
2576                        fed->fed_group, group);
2577                 RETURN(-ENOTUNIQ);
2578         }
2579
2580         CDEBUG(D_INFO, "filter_create(od->o_gr=%d,od->o_id="LPU64")\n",
2581                group, oa->o_id);
2582         if (oa->o_gr == FILTER_GROUP_ECHO) {
2583                 rc = filter_create_object(obd, oa);
2584                 if (rc == 0 && ea != NULL) {
2585                         struct lov_stripe_md *lsm = *ea;
2586                         if (lsm == NULL) {
2587                                 rc = obd_alloc_memmd(exp, &lsm);
2588                                 LASSERT(rc >= 0);
2589                         }
2590                         lsm->lsm_object_id = oa->o_id;
2591                         *ea = lsm;
2592                         rc = 0;
2593                 }
2594
2595                 RETURN(rc);
2596         }
2597
2598         obd = exp->exp_obd;
2599         push_ctxt(&saved, &obd->obd_lvfs_ctxt, NULL);
2600
2601         LASSERT((oa->o_valid & OBD_MD_FLFLAGS) &&
2602                 (oa->o_flags == OBD_FL_DELORPHAN));
2603                 
2604         rc = filter_clear_orphans(exp, oa);
2605         if (rc) {
2606                 CERROR("cannot clear orphanes starting from "
2607                        LPU64", err = %d\n", oa->o_id, rc);
2608         } else {
2609                 rc = filter_update_last_objid(obd, group, 0);
2610                 if (rc) {
2611                         CERROR("unable to write lastobjid, but "
2612                                "orphans were deleted, err = %d\n",
2613                                rc);
2614                 }
2615         }
2616         pop_ctxt(&saved, &obd->obd_lvfs_ctxt, NULL);
2617         
2618         RETURN(0);
2619 }
2620
2621 static int filter_destroy(struct obd_export *exp, struct obdo *oa,
2622                           struct lov_stripe_md *ea, struct obd_trans_info *oti)
2623 {
2624         int rc, rc2, cleanup_phase = 0, have_prepared = 0;
2625         struct dentry *dchild = NULL, *dparent = NULL;
2626         struct llog_cookie *fcc = NULL;
2627         struct lvfs_run_ctxt saved;
2628         struct filter_obd *filter;
2629         struct obd_device *obd;
2630         void *handle = NULL;
2631         void *lock = NULL;
2632         struct iattr iattr;
2633         ENTRY;
2634
2635         LASSERT(oa->o_valid & OBD_MD_FLGROUP);
2636
2637         obd = exp->exp_obd;
2638         filter = &obd->u.filter;
2639
2640         push_ctxt(&saved, &obd->obd_lvfs_ctxt, NULL);
2641
2642  acquire_locks:
2643         dparent = filter_parent_lock(obd, oa->o_gr, oa->o_id, &lock);
2644         if (IS_ERR(dparent))
2645                 GOTO(cleanup, rc = PTR_ERR(dparent));
2646         cleanup_phase = 1;
2647
2648         dchild = filter_id2dentry(obd, dparent, oa->o_gr, oa->o_id);
2649         if (IS_ERR(dchild))
2650                 GOTO(cleanup, rc = PTR_ERR(dchild));
2651         cleanup_phase = 2;
2652
2653         if (dchild->d_inode == NULL) {
2654                 CDEBUG(D_INODE, "destroying non-existent object "LPU64"\n",
2655                        oa->o_id);
2656                 if (have_prepared)
2657                         GOTO(cleanup, rc = -ENOENT);
2658         }
2659
2660         if (!have_prepared) {
2661                 /* If we're really going to destroy the object, get ready
2662                  * by getting the clients to discard their cached data.
2663                  *
2664                  * We have to drop the parent lock, because
2665                  * filter_prepare_destroy will acquire a PW on the object, and
2666                  * we don't want to deadlock with an incoming write to the
2667                  * object, which has the extent PW and then wants to get the
2668                  * parent dentry to do the lookup.
2669                  *
2670                  * We dput the child because it's not worth the extra
2671                  * complication of condition the above code to skip it on the
2672                  * second time through. */
2673                 f_dput(dchild);
2674                 filter_parent_unlock(dparent, lock);
2675
2676                 filter_prepare_destroy(obd, oa->o_id, oa->o_gr);
2677                 have_prepared = 1;
2678                 goto acquire_locks;
2679         }
2680
2681         /* Our MDC connection is established by the MDS to us */
2682         if (oa->o_valid & OBD_MD_FLCOOKIE) {
2683                 OBD_ALLOC(fcc, sizeof(*fcc));
2684                 if (fcc != NULL)
2685                         memcpy(fcc, obdo_logcookie(oa), sizeof(*fcc));
2686         }
2687
2688         /* we're gonna truncate it first in order to avoid possible
2689          * deadlock:
2690          *      P1                      P2
2691          * open trasaction      open transaction
2692          * down(i_zombie)       down(i_zombie)
2693          *                      restart transaction
2694          * (see BUG 4180) -bzzz
2695          */
2696         down(&dchild->d_inode->i_sem);
2697         handle = fsfilt_start_log(obd, dparent->d_inode,FSFILT_OP_SETATTR,NULL,1);
2698         if (IS_ERR(handle)) {
2699                 up(&dchild->d_inode->i_sem);
2700                 GOTO(cleanup, rc = PTR_ERR(handle));
2701         }
2702
2703         iattr.ia_valid = ATTR_SIZE;
2704         iattr.ia_size = 0;
2705         rc = fsfilt_setattr(obd, dchild, handle, &iattr, 1);
2706
2707         rc2 = fsfilt_commit(obd, filter->fo_sb, dparent->d_inode, handle, 0);
2708         up(&dchild->d_inode->i_sem);
2709         if (rc)
2710                 GOTO(cleanup, rc);
2711         if (rc2)
2712                 GOTO(cleanup, rc = rc2);
2713
2714         handle = fsfilt_start_log(obd, dparent->d_inode,FSFILT_OP_UNLINK,oti,1);
2715         if (IS_ERR(handle))
2716                 GOTO(cleanup, rc = PTR_ERR(handle));
2717
2718         cleanup_phase = 3;
2719
2720         rc = filter_destroy_internal(obd, oa->o_id, dparent, dchild);
2721
2722 cleanup:
2723         switch(cleanup_phase) {
2724         case 3:
2725                 if (fcc != NULL) {
2726                         fsfilt_add_journal_cb(obd, filter->fo_sb, 0,
2727                                               oti ? oti->oti_handle : handle,
2728                                               filter_cancel_cookies_cb, fcc);
2729                 }
2730                 rc = filter_finish_transno(exp, oti, rc);
2731                 rc2 = fsfilt_commit(obd, filter->fo_sb, dparent->d_inode, 
2732                                     handle, exp->exp_sync);
2733                 if (rc2) {
2734                         CERROR("error on commit, err = %d\n", rc2);
2735                         if (!rc)
2736                                 rc = rc2;
2737                 }
2738         case 2:
2739                 f_dput(dchild);
2740         case 1:
2741                 filter_parent_unlock(dparent, lock);
2742         case 0:
2743                 pop_ctxt(&saved, &obd->obd_lvfs_ctxt, NULL);
2744                 break;
2745         default:
2746                 CERROR("invalid cleanup_phase %d\n", cleanup_phase);
2747                 LBUG();
2748         }
2749
2750         RETURN(rc);
2751 }
2752
2753 /* NB start and end are used for punch, but not truncate */
2754 static int filter_truncate(struct obd_export *exp, struct obdo *oa,
2755                            struct lov_stripe_md *lsm, obd_off start,
2756                            obd_off end, struct obd_trans_info *oti,
2757                            struct lustre_capa *capa)
2758 {
2759         int error;
2760         int rc;
2761         ENTRY;
2762
2763         if (end != OBD_OBJECT_EOF)
2764                 CERROR("PUNCH not supported, only truncate: end = "LPX64"\n",
2765                        end);
2766
2767         rc = filter_verify_capa(OBD_BRW_WRITE, exp, capa);
2768         if (rc)
2769                 RETURN(rc);
2770
2771         CDEBUG(D_INODE, "calling truncate for object "LPU64", valid = "LPU64", "
2772                "o_size = "LPD64"\n", oa->o_id, oa->o_valid, start);
2773
2774         oa->o_size = start;
2775         error = filter_setattr(exp, oa, NULL, oti, capa);
2776         RETURN(error);
2777 }
2778
2779 static int filter_sync(struct obd_export *exp, struct obdo *oa,
2780                        struct lov_stripe_md *lsm, obd_off start, obd_off end)
2781 {
2782         struct obd_device *obd = exp->exp_obd;
2783         struct lvfs_run_ctxt saved;
2784         struct filter_obd *filter;
2785         struct dentry *dentry;
2786         int rc, rc2;
2787         ENTRY;
2788
2789         filter = &obd->u.filter;
2790
2791         /* an objid of zero is taken to mean "sync whole filesystem" */
2792         if (!oa || !(oa->o_valid & OBD_MD_FLID)) {
2793                 rc = fsfilt_sync(obd, filter->fo_sb);
2794                 /* flush any remaining cancel messages out to the target */
2795                 filter_sync_llogs(obd, NULL);
2796                 RETURN(rc);
2797         }
2798
2799         dentry = filter_oa2dentry(obd, oa);
2800         if (IS_ERR(dentry))
2801                 RETURN(PTR_ERR(dentry));
2802
2803         push_ctxt(&saved, &exp->exp_obd->obd_lvfs_ctxt, NULL);
2804
2805         down(&dentry->d_inode->i_sem);
2806         rc = filemap_fdatawrite(dentry->d_inode->i_mapping);
2807         if (rc == 0) {
2808                 /* just any file to grab fsync method - "file" arg unused */
2809                 struct file *file = filter->fo_rcvd_filp;
2810
2811                 if (file->f_op && file->f_op->fsync)
2812                         rc = file->f_op->fsync(NULL, dentry, 1);
2813
2814                 rc2 = filemap_fdatawait(dentry->d_inode->i_mapping);
2815                 if (!rc)
2816                         rc = rc2;
2817         }
2818         up(&dentry->d_inode->i_sem);
2819
2820         oa->o_valid = OBD_MD_FLID;
2821         obdo_from_inode(oa, dentry->d_inode, FILTER_VALID_FLAGS);
2822
2823         pop_ctxt(&saved, &exp->exp_obd->obd_lvfs_ctxt, NULL);
2824
2825         f_dput(dentry);
2826         RETURN(rc);
2827 }
2828
2829 static int filter_set_info(struct obd_export *exp, __u32 keylen,
2830                            void *key, __u32 vallen, void *val)
2831 {
2832         struct obd_device *obd;
2833         int rc = -EINVAL;
2834         ENTRY;
2835
2836         obd = class_exp2obd(exp);
2837         if (obd == NULL) {
2838                 CDEBUG(D_IOCTL, "invalid client cookie "LPX64"\n",
2839                        exp->exp_handle.h_cookie);
2840                 RETURN(-EINVAL);
2841         }
2842
2843         if (keylen == 8 && memcmp(key, "auditlog", 8) == 0) {
2844                 rc = fsfilt_set_info(obd, obd->u.filter.fo_sb, NULL,
2845                                      8, "auditlog", vallen, val);
2846                 RETURN(rc);
2847         } else if (keylen == 5 && strcmp(key, "audit") == 0) {
2848                 /* set audit for whole FS on OSS */
2849                 struct audit_attr_msg * msg = val;
2850
2851                 rc = fsfilt_set_info(obd, obd->u.filter.fo_sb, NULL,
2852                                      5, "audit", sizeof(msg->attr), &msg->attr);
2853                 RETURN(rc);
2854         } else if (keylen == 9 && strcmp(key, "audit_obj") == 0) {
2855                 struct obdo * oa = val;
2856                 struct dentry * dentry;
2857                 __u64 mask = oa->o_fid;
2858                 
2859                 dentry = filter_crow_object(obd, oa);
2860                 if (IS_ERR(dentry))
2861                         RETURN(PTR_ERR(dentry));
2862                 
2863                 rc = fsfilt_set_info(obd, obd->u.filter.fo_sb, dentry->d_inode,
2864                                      5, "audit", sizeof(mask), &mask);
2865
2866                 f_dput(dentry);
2867
2868                 RETURN(rc);
2869         } else if (keylen == 8 && memcmp(key, "capa_key", 8) == 0) {
2870                 struct lustre_capa_key *lkey = val;
2871                 rc = filter_update_capa_key(obd, lkey);
2872                 RETURN(rc);
2873         }
2874
2875         if (rc)
2876                 CDEBUG(D_IOCTL, "invalid key '%s'\n", (char *)key);
2877         
2878         RETURN(rc);
2879 }
2880
2881 static int filter_get_info(struct obd_export *exp, __u32 keylen,
2882                            void *key, __u32 *vallen, void *val)
2883 {
2884         struct filter_export_data *fed = &exp->exp_filter_data;
2885         struct obd_device *obd;
2886         ENTRY;
2887
2888         obd = class_exp2obd(exp);
2889         if (obd == NULL) {
2890                 CDEBUG(D_IOCTL, "invalid client cookie "LPX64"\n",
2891                        exp->exp_handle.h_cookie);
2892                 RETURN(-EINVAL);
2893         }
2894
2895         if (keylen == strlen("blocksize") &&
2896             memcmp(key, "blocksize", keylen) == 0) {
2897                 __u32 *blocksize = val;
2898                 *vallen = sizeof(*blocksize);
2899                 *blocksize = obd->u.filter.fo_sb->s_blocksize;
2900                 RETURN(0);
2901         }
2902
2903         if (keylen == strlen("blocksize_bits") &&
2904             memcmp(key, "blocksize_bits", keylen) == 0) {
2905                 __u32 *blocksize_bits = val;
2906                 *vallen = sizeof(*blocksize_bits);
2907                 *blocksize_bits = obd->u.filter.fo_sb->s_blocksize_bits;
2908                 RETURN(0);
2909         }
2910
2911         if (keylen >= strlen("last_id") && memcmp(key, "last_id", 7) == 0) {
2912                 obd_id *last_id = val;
2913                 *last_id = filter_last_id(&obd->u.filter, fed->fed_group);
2914                 RETURN(0);
2915         }
2916         if (keylen >= strlen("reint_log") && memcmp(key, "reint_log", 9) == 0) {
2917                 /*Get log_context handle*/
2918                 unsigned long *llh_handle = val;
2919                 *vallen = sizeof(unsigned long);
2920                 *llh_handle = (unsigned long)llog_get_context(&obd->obd_llogs,
2921                                                        LLOG_REINT_ORIG_CTXT);
2922                 RETURN(0);
2923         }
2924         if (keylen >= strlen("cache_sb") && memcmp(key, "cache_sb", 8) == 0) {
2925                 unsigned long *sb = val;
2926                 *vallen = sizeof(unsigned long);
2927                 *sb = (unsigned long)obd->u.filter.fo_sb;
2928                 RETURN(0);
2929         }
2930
2931         CDEBUG(D_IOCTL, "invalid key\n");
2932         RETURN(-EINVAL);
2933 }
2934
2935 struct obd_llogs *filter_grab_llog_for_group(struct obd_device *obd, int group,
2936                                              struct obd_export *export)
2937 {
2938         struct filter_group_llog *fglog, *nlog;
2939         char name[32] = "CATLIST";
2940         struct filter_obd *filter;
2941         struct llog_ctxt *ctxt;
2942         struct list_head *cur;
2943         int rc;
2944
2945         filter = &obd->u.filter;
2946
2947         spin_lock(&filter->fo_llog_list_lock);
2948         list_for_each(cur, &filter->fo_llog_list) {
2949                 fglog = list_entry(cur, struct filter_group_llog, list);
2950                 if (fglog->group == group) {
2951                         if (!(fglog->exp == NULL || fglog->exp == export || export == NULL))
2952                                 CWARN("%s: export for group %d changes: 0x%p -> 0x%p\n",
2953                                       obd->obd_name, group, fglog->exp, export);
2954                         spin_unlock(&filter->fo_llog_list_lock);
2955                         goto init;
2956                 }
2957         }
2958         spin_unlock(&filter->fo_llog_list_lock);
2959
2960         if (export == NULL)
2961                 RETURN(NULL);
2962
2963         OBD_ALLOC(fglog, sizeof(*fglog));
2964         if (fglog == NULL)
2965                 RETURN(NULL);
2966         fglog->group = group;
2967
2968         OBD_ALLOC(fglog->llogs, sizeof(struct obd_llogs));
2969         if (fglog->llogs == NULL) {
2970                 OBD_FREE(fglog, sizeof(*fglog));
2971                 RETURN(NULL);
2972         }
2973
2974         spin_lock(&filter->fo_llog_list_lock);
2975         list_for_each(cur, &filter->fo_llog_list) {
2976                 nlog = list_entry(cur, struct filter_group_llog, list);
2977                 LASSERT(nlog->group != group);
2978         }
2979         list_add(&fglog->list, &filter->fo_llog_list);
2980         spin_unlock(&filter->fo_llog_list_lock);
2981
2982         rc = obd_llog_cat_initialize(obd, fglog->llogs, 1, name);
2983         if (rc) {
2984                 OBD_FREE(fglog->llogs, sizeof(*(fglog->llogs)));
2985                 OBD_FREE(fglog, sizeof(*fglog));
2986                 RETURN(NULL);
2987         }
2988
2989 init:
2990         if (export) {
2991                 fglog->exp = export;
2992                 ctxt = llog_get_context(fglog->llogs, LLOG_UNLINK_REPL_CTXT);
2993                 LASSERT(ctxt != NULL);
2994
2995                 llog_receptor_accept(ctxt, export->exp_imp_reverse);
2996         }
2997         CDEBUG(D_OTHER, "%s: new llog 0x%p for group %u\n",
2998                obd->obd_name, fglog->llogs, group);
2999
3000         RETURN(fglog->llogs);
3001 }
3002
3003 int filter_iocontrol(unsigned int cmd, struct obd_export *exp,
3004                      int len, void *karg, void *uarg)
3005 {
3006         struct obd_device *obd = exp->exp_obd;
3007         struct obd_ioctl_data *data = karg;
3008         int rc = 0;
3009
3010         switch (cmd) {
3011         case OBD_IOC_ABORT_RECOVERY:
3012                 target_stop_recovery_thread(obd);
3013                 RETURN(0);
3014
3015         case OBD_IOC_SET_READONLY: {
3016                 void *handle;
3017                 struct super_block *sb = obd->u.filter.fo_sb;
3018                 struct inode *inode = sb->s_root->d_inode;
3019                 BDEVNAME_DECLARE_STORAGE(tmp);
3020                 CERROR("setting device %s read-only\n",
3021                        ll_bdevname(sb, tmp));
3022
3023                 handle = fsfilt_start(obd, inode, FSFILT_OP_MKNOD, NULL);
3024                 LASSERT(handle);
3025                 (void)fsfilt_commit(obd, sb, inode, handle, 1);
3026
3027                 ll_set_rdonly(ll_sbdev(obd->u.filter.fo_sb));
3028                 RETURN(0);
3029         }
3030
3031         case OBD_IOC_CATLOGLIST: {
3032                 rc = llog_catalog_list(obd, 1, data);
3033                 RETURN(rc);
3034         }
3035         case OBD_IOC_LLOG_CANCEL:
3036         case OBD_IOC_LLOG_REMOVE:
3037         case OBD_IOC_LLOG_INFO:
3038         case OBD_IOC_LLOG_PRINT: {
3039                 /* FIXME to be finished */
3040                 RETURN(-EOPNOTSUPP);
3041 /*
3042                 struct llog_ctxt *ctxt = NULL;
3043
3044                 push_ctxt(&saved, &ctxt->loc_ctxt, NULL);
3045                 rc = llog_ioctl(ctxt, cmd, data);
3046                 pop_ctxt(&saved, &ctxt->loc_ctxt, NULL);
3047
3048                 RETURN(rc);
3049 */
3050         }
3051
3052
3053         default:
3054                 RETURN(-EINVAL);
3055         }
3056         RETURN(0);
3057 }
3058
3059 static struct llog_operations filter_unlink_repl_logops;
3060 static struct llog_operations filter_size_orig_logops = {
3061         lop_setup: llog_obd_origin_setup,
3062         lop_cleanup: llog_catalog_cleanup,
3063         lop_add: llog_catalog_add,
3064 };
3065
3066 static int filter_llog_init(struct obd_device *obd, struct obd_llogs *llogs,
3067                             struct obd_device *tgt, int count,
3068                             struct llog_catid *catid)
3069 {
3070         struct llog_ctxt *ctxt;
3071         int rc;
3072         ENTRY;
3073
3074         filter_unlink_repl_logops = llog_client_ops;
3075         filter_unlink_repl_logops.lop_cancel = llog_obd_repl_cancel;
3076         filter_unlink_repl_logops.lop_connect = llog_repl_connect;
3077         filter_unlink_repl_logops.lop_sync = llog_obd_repl_sync;
3078
3079         rc = obd_llog_setup(obd, llogs, LLOG_UNLINK_REPL_CTXT, tgt, 0, NULL,
3080                         &filter_unlink_repl_logops);
3081         if (rc)
3082                 RETURN(rc);
3083         /* FIXME - assign unlink_cb for filter's recovery */
3084         ctxt = llog_get_context(llogs, LLOG_UNLINK_REPL_CTXT);
3085         ctxt->llog_proc_cb = filter_recov_log_unlink_cb;
3086
3087         filter_size_orig_logops = llog_lvfs_ops;
3088 #if 0
3089         filter_size_orig_logops.lop_setup = llog_obd_origin_setup;
3090         filter_size_orig_logops.lop_cleanup = llog_catalog_cleanup;
3091         filter_size_orig_logops.lop_add = llog_catalog_add;
3092 #endif
3093         rc = obd_llog_setup(obd, llogs, LLOG_SIZE_ORIG_CTXT, tgt, 1, 
3094                             &catid->lci_logid, &filter_size_orig_logops);
3095         RETURN(rc);
3096 }
3097
3098 static int filter_llog_finish(struct obd_device *obd,
3099                               struct obd_llogs *llogs, int count)
3100 {
3101         int rc;
3102         ENTRY;
3103
3104         rc = obd_llog_cleanup(llog_get_context(llogs, LLOG_UNLINK_REPL_CTXT));
3105         if (rc)
3106                 RETURN(rc);
3107
3108         rc = obd_llog_cleanup(llog_get_context(llogs, LLOG_SIZE_ORIG_CTXT));
3109         RETURN(rc);
3110 }
3111
3112 static int filter_llog_connect(struct obd_export *exp,
3113                                struct llogd_conn_body *body) 
3114 {
3115         struct obd_device *obd = exp->exp_obd;
3116         struct llog_ctxt *ctxt;
3117         struct obd_llogs *llog;
3118         int rc;
3119         ENTRY;
3120
3121         CDEBUG(D_OTHER, "handle connect for %s: %u/%u/%u\n", obd->obd_name,
3122                (unsigned) body->lgdc_logid.lgl_ogr,
3123                (unsigned) body->lgdc_logid.lgl_oid,
3124                (unsigned) body->lgdc_logid.lgl_ogen);
3125         llog = filter_grab_llog_for_group(obd, body->lgdc_logid.lgl_ogr, exp);
3126         LASSERT(llog != NULL);
3127         ctxt = llog_get_context(llog, body->lgdc_ctxt_idx);
3128         rc = llog_connect(ctxt, 1, &body->lgdc_logid,
3129                           &body->lgdc_gen, NULL);
3130         if (rc != 0)
3131                 CERROR("failed to connect\n");
3132
3133         RETURN(rc);
3134 }
3135
3136 static struct dentry *filter_lvfs_id2dentry(__u64 id, __u32 gen,
3137                                             __u64 gr, void *data)
3138 {
3139         return filter_id2dentry(data, NULL, gr, id);
3140 }
3141
3142 static struct lvfs_callback_ops filter_lvfs_ops = {
3143         l_id2dentry:     filter_lvfs_id2dentry,
3144 };
3145
3146 static struct obd_ops filter_obd_ops = {
3147         .o_owner          = THIS_MODULE,
3148         .o_attach         = filter_attach,
3149         .o_detach         = filter_detach,
3150         .o_set_info       = filter_set_info,
3151         .o_get_info       = filter_get_info,
3152         .o_setup          = filter_setup,
3153         .o_precleanup     = filter_precleanup,
3154         .o_cleanup        = filter_cleanup,
3155         .o_process_config = filter_process_config,
3156         .o_connect        = filter_connect,
3157         .o_connect_post   = filter_connect_post,
3158         .o_disconnect     = filter_disconnect,
3159         .o_statfs         = filter_statfs,
3160         .o_getattr        = filter_getattr,
3161         .o_unpackmd       = filter_unpackmd,
3162         .o_create         = filter_create,
3163         .o_setattr        = filter_setattr,
3164         .o_destroy        = filter_destroy,
3165         .o_brw            = filter_brw,
3166         .o_punch          = filter_truncate,
3167         .o_sync           = filter_sync,
3168         .o_preprw         = filter_preprw,
3169         .o_commitrw       = filter_commitrw,
3170         .o_do_cow         = filter_do_cow,
3171         .o_write_extents  = filter_write_extents,
3172         .o_destroy_export = filter_destroy_export,
3173         .o_llog_init      = filter_llog_init,
3174         .o_llog_finish    = filter_llog_finish,
3175         .o_llog_connect   = filter_llog_connect,
3176         .o_iocontrol      = filter_iocontrol,
3177 };
3178
3179 static struct obd_ops filter_sanobd_ops = {
3180         .o_owner          = THIS_MODULE,
3181         .o_attach         = filter_attach,
3182         .o_detach         = filter_detach,
3183         .o_get_info       = filter_get_info,
3184         .o_setup          = filter_san_setup,
3185         .o_precleanup     = filter_precleanup,
3186         .o_cleanup        = filter_cleanup,
3187         .o_connect        = filter_connect,
3188         .o_connect_post   = filter_connect_post,
3189         .o_disconnect     = filter_disconnect,
3190         .o_statfs         = filter_statfs,
3191         .o_getattr        = filter_getattr,
3192         .o_unpackmd       = filter_unpackmd,
3193         .o_create         = filter_create,
3194         .o_setattr        = filter_setattr,
3195         .o_destroy        = filter_destroy,
3196         .o_brw            = filter_brw,
3197         .o_punch          = filter_truncate,
3198         .o_sync           = filter_sync,
3199         .o_preprw         = filter_preprw,
3200         .o_commitrw       = filter_commitrw,
3201         .o_do_cow         = filter_do_cow,
3202         .o_write_extents  = filter_write_extents,
3203         .o_san_preprw     = filter_san_preprw,
3204         .o_destroy_export = filter_destroy_export,
3205         .o_llog_init      = filter_llog_init,
3206         .o_llog_finish    = filter_llog_finish,
3207         .o_llog_connect   = filter_llog_connect,
3208         .o_iocontrol      = filter_iocontrol,
3209 };
3210
3211 static int __init obdfilter_init(void)
3212 {
3213         struct lprocfs_static_vars lvars;
3214         int size, rc;
3215
3216         printk(KERN_INFO "Lustre: Filtering OBD driver; info@clusterfs.com\n");
3217
3218         lprocfs_init_vars(filter, &lvars);
3219
3220         size = OBDFILTER_CREATED_SCRATCHPAD_ENTRIES * 
3221                 sizeof(*obdfilter_created_scratchpad);
3222         
3223         OBD_ALLOC(obdfilter_created_scratchpad, size);
3224         if (obdfilter_created_scratchpad == NULL) {
3225                 CERROR ("Can't allocate scratchpad\n");
3226                 return -ENOMEM;
3227         }
3228
3229         rc = class_register_type(&filter_obd_ops, NULL, lvars.module_vars,
3230                                  OBD_FILTER_DEVICENAME);
3231         if (rc) {
3232                 OBD_FREE(obdfilter_created_scratchpad, size);
3233                 return rc;
3234         }
3235
3236         rc = class_register_type(&filter_sanobd_ops, NULL, lvars.module_vars,
3237                                  OBD_FILTER_SAN_DEVICENAME);
3238         if (rc) {
3239                 class_unregister_type(OBD_FILTER_DEVICENAME);
3240                 OBD_FREE(obdfilter_created_scratchpad, size);
3241         }
3242         return rc;
3243 }
3244
3245 static void __exit obdfilter_exit(void)
3246 {
3247         class_unregister_type(OBD_FILTER_SAN_DEVICENAME);
3248         class_unregister_type(OBD_FILTER_DEVICENAME);
3249         OBD_FREE(obdfilter_created_scratchpad,
3250                  OBDFILTER_CREATED_SCRATCHPAD_ENTRIES * 
3251                  sizeof(*obdfilter_created_scratchpad));
3252 }
3253
3254 MODULE_AUTHOR("Cluster File Systems, Inc. <info@clusterfs.com>");
3255 MODULE_DESCRIPTION("Lustre Filtering OBD driver");
3256 MODULE_LICENSE("GPL");
3257
3258 module_init(obdfilter_init);
3259 module_exit(obdfilter_exit);