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