Whamcloud - gitweb
1. Fixed cleanup issue where I was *indeed* accesing a zapped pointer.
[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, 2002 Cluster File Systems, Inc.
7  *
8  * This code is issued under the GNU General Public License.
9  * See the file COPYING in this distribution
10  *
11  * by Peter Braam <braam@clusterfs.com>
12  * and Andreas Dilger <adilger@clusterfs.com>
13  */
14
15 #define EXPORT_SYMTAB
16 #define DEBUG_SUBSYSTEM S_FILTER
17
18 #include <linux/module.h>
19 #include <linux/pagemap.h>
20 #include <linux/fs.h>
21 #include <linux/dcache.h>
22 #include <linux/obd_class.h>
23 #include <linux/lustre_dlm.h>
24 #include <linux/obd_filter.h>
25 #include <linux/ext3_jbd.h>
26 #if (LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0))
27 #include <linux/extN_jbd.h>
28 #endif
29 #include <linux/quotaops.h>
30 #include <linux/init.h>
31 #include <linux/random.h>
32 #include <linux/stringify.h>
33 #include <linux/lprocfs_status.h>
34
35 extern struct lprocfs_vars status_class_var[];
36 extern struct lprocfs_vars status_var_nm_1[];
37
38 static kmem_cache_t *filter_open_cache;
39 static kmem_cache_t *filter_dentry_cache;
40
41 #define FILTER_ROOTINO 2
42 #define FILTER_ROOTINO_STR __stringify(FILTER_ROOTINO)
43
44 #define S_SHIFT 12
45 static char *obd_type_by_mode[S_IFMT >> S_SHIFT] = {
46         [0]                     NULL,
47         [S_IFREG >> S_SHIFT]    "R",
48         [S_IFDIR >> S_SHIFT]    "D",
49         [S_IFCHR >> S_SHIFT]    "C",
50         [S_IFBLK >> S_SHIFT]    "B",
51         [S_IFIFO >> S_SHIFT]    "F",
52         [S_IFSOCK >> S_SHIFT]   "S",
53         [S_IFLNK >> S_SHIFT]    "L"
54 };
55
56 static inline const char *obd_mode_to_type(int mode)
57 {
58         return obd_type_by_mode[(mode & S_IFMT) >> S_SHIFT];
59 }
60
61 /* write the pathname into the string */
62 static int filter_id(char *buf, obd_id id, obd_mode mode)
63 {
64         return sprintf(buf, "O/%s/"LPU64, obd_mode_to_type(mode), id);
65 }
66
67 static inline void f_dput(struct dentry *dentry)
68 {
69         /* Can't go inside filter_ddelete because it can block */
70         CDEBUG(D_INODE, "putting %s: %p, count = %d\n",
71                dentry->d_name.name, dentry, atomic_read(&dentry->d_count) - 1);
72         LASSERT(atomic_read(&dentry->d_count) > 0);
73
74         dput(dentry);
75 }
76
77 /* Not racy w.r.t. others, because we are the only user of this dentry */
78 static void filter_drelease(struct dentry *dentry)
79 {
80         if (dentry->d_fsdata)
81                 kmem_cache_free(filter_dentry_cache, dentry->d_fsdata);
82 }
83
84 struct dentry_operations filter_dops = {
85         .d_release = filter_drelease,
86 };
87
88 /* setup the object store with correct subdirectories */
89 static int filter_prep(struct obd_device *obd)
90 {
91         struct obd_run_ctxt saved;
92         struct filter_obd *filter = &obd->u.filter;
93         struct dentry *dentry;
94         struct dentry *root;
95         struct file *file;
96         struct inode *inode;
97         int rc = 0;
98         __u64 lastobjid = 2;
99         int mode = 0;
100
101         push_ctxt(&saved, &filter->fo_ctxt, NULL);
102         dentry = simple_mkdir(current->fs->pwd, "O", 0700);
103         CDEBUG(D_INODE, "got/created O: %p\n", dentry);
104         if (IS_ERR(dentry)) {
105                 rc = PTR_ERR(dentry);
106                 CERROR("cannot open/create O: rc = %d\n", rc);
107                 GOTO(out, rc);
108         }
109         filter->fo_dentry_O = dentry;
110         dentry = simple_mkdir(current->fs->pwd, "P", 0700);
111         CDEBUG(D_INODE, "got/created P: %p\n", dentry);
112         if (IS_ERR(dentry)) {
113                 rc = PTR_ERR(dentry);
114                 CERROR("cannot open/create P: rc = %d\n", rc);
115                 GOTO(out_O, rc);
116         }
117         f_dput(dentry);
118         dentry = simple_mkdir(current->fs->pwd, "D", 0700);
119         CDEBUG(D_INODE, "got/created D: %p\n", dentry);
120         if (IS_ERR(dentry)) {
121                 rc = PTR_ERR(dentry);
122                 CERROR("cannot open/create D: rc = %d\n", rc);
123                 GOTO(out_O, rc);
124         }
125
126         root = simple_mknod(dentry, FILTER_ROOTINO_STR, S_IFREG | 0755);
127         f_dput(dentry);
128         if (IS_ERR(root)) {
129                 rc = PTR_ERR(root);
130                 CERROR("OBD filter: cannot open/create root %d: rc = %d\n",
131                        FILTER_ROOTINO, rc);
132                 GOTO(out_O, rc);
133         }
134         f_dput(root);
135
136         /*
137          * Create directories and/or get dentries for each object type.
138          * This saves us from having to do multiple lookups for each one.
139          */
140         for (mode = 0; mode < (S_IFMT >> S_SHIFT); mode++) {
141                 char *type = obd_type_by_mode[mode];
142
143                 if (!type) {
144                         filter->fo_dentry_O_mode[mode] = NULL;
145                         continue;
146                 }
147                 dentry = simple_mkdir(filter->fo_dentry_O, type, 0700);
148                 CDEBUG(D_INODE, "got/created O/%s: %p\n", type, dentry);
149                 if (IS_ERR(dentry)) {
150                         rc = PTR_ERR(dentry);
151                         CERROR("cannot create O/%s: rc = %d\n", type, rc);
152                         GOTO(out_O_mode, rc);
153                 }
154                 filter->fo_dentry_O_mode[mode] = dentry;
155         }
156
157         file = filp_open("D/status", O_RDWR | O_CREAT, 0700);
158         if ( !file || IS_ERR(file) ) {
159                 rc = PTR_ERR(file);
160                 CERROR("OBD filter: cannot open/create status %s: rc = %d\n",
161                        "D/status", rc);
162                 GOTO(out_O_mode, rc);
163         }
164
165         /* steal operations */
166         inode = file->f_dentry->d_inode;
167         filter->fo_fop = file->f_op;
168         filter->fo_iop = inode->i_op;
169         filter->fo_aops = inode->i_mapping->a_ops;
170
171         if (inode->i_size == 0) {
172                 __u64 disk_lastobjid = cpu_to_le64(lastobjid);
173                 ssize_t retval = file->f_op->write(file,(char *)&disk_lastobjid,
174                                                    sizeof(disk_lastobjid),
175                                                    &file->f_pos);
176                 if (retval != sizeof(disk_lastobjid)) {
177                         CDEBUG(D_INODE,"OBD filter: error writing lastobjid\n");
178                         filp_close(file, 0);
179                         GOTO(out_O_mode, rc = -EIO);
180                 }
181         } else {
182                 __u64 disk_lastobjid;
183                 ssize_t retval = file->f_op->read(file, (char *)&disk_lastobjid,
184                                                   sizeof(disk_lastobjid),
185                                                   &file->f_pos);
186                 if (retval != sizeof(disk_lastobjid)) {
187                         CDEBUG(D_INODE,"OBD filter: error reading lastobjid\n");
188                         filp_close(file, 0);
189                         GOTO(out_O_mode, rc = -EIO);
190                 }
191                 lastobjid = le64_to_cpu(disk_lastobjid);
192         }
193         filter->fo_lastobjid = lastobjid;
194         filp_close(file, 0);
195
196         rc = 0;
197  out:
198         pop_ctxt(&saved);
199
200         return(rc);
201
202 out_O_mode:
203         while (mode-- > 0) {
204                 struct dentry *dentry = filter->fo_dentry_O_mode[mode];
205                 if (dentry) {
206                         f_dput(dentry);
207                         filter->fo_dentry_O_mode[mode] = NULL;
208                 }
209         }
210 out_O:
211         f_dput(filter->fo_dentry_O);
212         filter->fo_dentry_O = NULL;
213         goto out;
214 }
215
216 /* cleanup the filter: write last used object id to status file */
217 static void filter_post(struct obd_device *obd)
218 {
219         struct obd_run_ctxt saved;
220         struct filter_obd *filter = &obd->u.filter;
221         __u64 disk_lastobjid;
222         long rc;
223         struct file *file;
224         int mode;
225
226         push_ctxt(&saved, &filter->fo_ctxt, NULL);
227         file = filp_open("D/status", O_RDWR | O_CREAT, 0700);
228         if (IS_ERR(file)) {
229                 CERROR("OBD filter: cannot create status file\n");
230                 goto out;
231         }
232
233         file->f_pos = 0;
234         disk_lastobjid = cpu_to_le64(filter->fo_lastobjid);
235         rc = file->f_op->write(file, (char *)&disk_lastobjid,
236                        sizeof(disk_lastobjid), &file->f_pos);
237         if (rc != sizeof(disk_lastobjid))
238                 CERROR("OBD filter: error writing lastobjid: rc = %ld\n", rc);
239
240         rc = filp_close(file, NULL);
241         if (rc)
242                 CERROR("OBD filter: cannot close status file: rc = %ld\n", rc);
243
244         for (mode = 0; mode < (S_IFMT >> S_SHIFT); mode++) {
245                 struct dentry *dentry = filter->fo_dentry_O_mode[mode];
246                 if (dentry) {
247                         f_dput(dentry);
248                         filter->fo_dentry_O_mode[mode] = NULL;
249                 }
250         }
251         f_dput(filter->fo_dentry_O);
252 out:
253         pop_ctxt(&saved);
254 }
255
256
257 static __u64 filter_next_id(struct obd_device *obd)
258 {
259         obd_id id;
260
261         spin_lock(&obd->u.filter.fo_objidlock);
262         id = ++obd->u.filter.fo_lastobjid;
263         spin_unlock(&obd->u.filter.fo_objidlock);
264
265         /* FIXME: write the lastobjid to disk here */
266         return id;
267 }
268
269 /* how to get files, dentries, inodes from object id's */
270 /* parent i_sem is already held if needed for exclusivity */
271 static struct dentry *filter_fid2dentry(struct obd_device *obd,
272                                         struct dentry *dparent,
273                                         __u64 id, __u32 type)
274 {
275         struct super_block *sb = obd->u.filter.fo_sb;
276         struct dentry *dchild;
277         char name[32];
278         int len;
279         ENTRY;
280
281         if (!sb || !sb->s_dev) {
282                 CERROR("fatal: device not initialized.\n");
283                 RETURN(ERR_PTR(-ENXIO));
284         }
285
286         if (id == 0) {
287                 CERROR("fatal: invalid object #0\n");
288                 LBUG();
289                 RETURN(ERR_PTR(-ESTALE));
290         }
291
292         if (!(type & S_IFMT)) {
293                 CERROR("OBD %s, object "LPU64" has bad type: %o\n",
294                        __FUNCTION__, id, type);
295                 RETURN(ERR_PTR(-EINVAL));
296         }
297
298         len = sprintf(name, LPU64, id);
299         CDEBUG(D_INODE, "opening object O/%s/%s\n", obd_mode_to_type(type),
300                name);
301         dchild = lookup_one_len(name, dparent, len);
302         if (IS_ERR(dchild)) {
303                 CERROR("child lookup error %ld\n", PTR_ERR(dchild));
304                 RETURN(dchild);
305         }
306
307         CDEBUG(D_INODE, "got child obj O/%s/%s: %p, count = %d\n",
308                obd_mode_to_type(type), name, dchild,
309                atomic_read(&dchild->d_count));
310
311         LASSERT(atomic_read(&dchild->d_count) > 0);
312
313         RETURN(dchild);
314 }
315
316 static inline struct dentry *filter_parent(struct obd_device *obd,
317                                            obd_mode mode)
318 {
319         struct filter_obd *filter = &obd->u.filter;
320
321         return filter->fo_dentry_O_mode[(mode & S_IFMT) >> S_SHIFT];
322 }
323
324 static struct file *filter_obj_open(struct obd_export *export,
325                                     __u64 id, __u32 type)
326 {
327         struct filter_obd *filter = &export->exp_obd->u.filter;
328         struct super_block *sb = filter->fo_sb;
329         struct dentry *dentry;
330         struct filter_export_data *fed = &export->exp_filter_data;
331         struct filter_dentry_data *fdd;
332         struct filter_file_data *ffd;
333         struct obd_run_ctxt saved;
334         char name[24];
335         struct file *file;
336         ENTRY;
337
338         if (!sb || !sb->s_dev) {
339                 CERROR("fatal: device not initialized.\n");
340                 RETURN(ERR_PTR(-ENXIO));
341         }
342
343         if (!id) {
344                 CERROR("fatal: invalid obdo "LPU64"\n", id);
345                 RETURN(ERR_PTR(-ESTALE));
346         }
347
348         if (!(type & S_IFMT)) {
349                 CERROR("OBD %s, object "LPU64" has bad type: %o\n",
350                        __FUNCTION__, id, type);
351                 RETURN(ERR_PTR(-EINVAL));
352         }
353
354         ffd = kmem_cache_alloc(filter_open_cache, SLAB_KERNEL);
355         if (!ffd) {
356                 CERROR("obdfilter: out of memory\n");
357                 RETURN(ERR_PTR(-ENOMEM));
358         }
359
360         /* We preallocate this to avoid blocking while holding fo_fddlock */
361         fdd = kmem_cache_alloc(filter_dentry_cache, SLAB_KERNEL);
362         if (!fdd) {
363                 CERROR("obdfilter: out of memory\n");
364                 GOTO(out_ffd, file = ERR_PTR(-ENOMEM));
365         }
366
367         filter_id(name, id, type);
368         push_ctxt(&saved, &filter->fo_ctxt, NULL);
369         file = filp_open(name, O_RDONLY | O_LARGEFILE, 0 /* type? */);
370         pop_ctxt(&saved);
371
372         if (IS_ERR(file))
373                 GOTO(out_fdd, file);
374
375         dentry = file->f_dentry;
376         spin_lock(&filter->fo_fddlock);
377         if (dentry->d_fsdata) {
378                 spin_unlock(&filter->fo_fddlock);
379                 kmem_cache_free(filter_dentry_cache, fdd);
380                 fdd = dentry->d_fsdata;
381                 LASSERT(kmem_cache_validate(filter_dentry_cache, fdd));
382                 /* should only happen during client recovery */
383                 if (fdd->fdd_flags & FILTER_FLAG_DESTROY)
384                         CDEBUG(D_INODE,"opening destroyed object "LPX64"\n",id);
385                 atomic_inc(&fdd->fdd_open_count);
386         } else {
387                 atomic_set(&fdd->fdd_open_count, 1);
388                 fdd->fdd_flags = 0;
389                 /* If this is racy, then we can use {cmp}xchg and atomic_add */
390                 dentry->d_fsdata = fdd;
391                 spin_unlock(&filter->fo_fddlock);
392         }
393
394         get_random_bytes(&ffd->ffd_servercookie, sizeof(ffd->ffd_servercookie));
395         ffd->ffd_file = file;
396         file->private_data = ffd;
397
398         if (!dentry->d_op)
399                 dentry->d_op = &filter_dops;
400         else
401                 LASSERT(dentry->d_op == &filter_dops);
402
403         spin_lock(&fed->fed_lock);
404         list_add(&ffd->ffd_export_list, &fed->fed_open_head);
405         spin_unlock(&fed->fed_lock);
406
407         CDEBUG(D_INODE, "opening objid "LPX64": rc = %p\n", id, file);
408
409 out:
410         RETURN(file);
411
412 out_fdd:
413         kmem_cache_free(filter_dentry_cache, fdd);
414 out_ffd:
415         ffd->ffd_servercookie = DEAD_HANDLE_MAGIC;
416         kmem_cache_free(filter_open_cache, ffd);
417         goto out;
418 }
419
420 /* Caller must hold i_sem on dir_dentry->d_inode */
421 static int filter_destroy_internal(struct obd_device *obd,
422                                    struct dentry *dir_dentry,
423                                    struct dentry *object_dentry)
424 {
425         struct obd_run_ctxt saved;
426         struct inode *inode = object_dentry->d_inode;
427         int rc;
428         ENTRY;
429
430         if (inode->i_nlink != 1 || atomic_read(&inode->i_count) != 1) {
431                 CERROR("destroying objid %*s nlink = %d, count = %d\n",
432                        object_dentry->d_name.len,
433                        object_dentry->d_name.name,
434                        inode->i_nlink, atomic_read(&inode->i_count));
435         }
436
437         push_ctxt(&saved, &obd->u.filter.fo_ctxt, NULL);
438         rc = vfs_unlink(dir_dentry->d_inode, object_dentry);
439         /* XXX unlink from PENDING directory now too */
440         pop_ctxt(&saved);
441
442         if (rc)
443                 CERROR("error unlinking objid %*s: rc %d\n",
444                        object_dentry->d_name.len,
445                        object_dentry->d_name.name, rc);
446
447         RETURN(rc);
448 }
449
450 static int filter_close_internal(struct obd_device *obd,
451                                  struct filter_file_data *ffd)
452 {
453         struct file *filp = ffd->ffd_file;
454         struct dentry *object_dentry = dget(filp->f_dentry);
455         struct filter_dentry_data *fdd = object_dentry->d_fsdata;
456         int rc, rc2 = 0;
457         ENTRY;
458
459         LASSERT(filp->private_data == ffd);
460         LASSERT(fdd);
461
462         rc = filp_close(filp, 0);
463
464         if (atomic_dec_and_test(&fdd->fdd_open_count) &&
465             fdd->fdd_flags & FILTER_FLAG_DESTROY) {
466                 struct dentry *dir_dentry = filter_parent(obd, S_IFREG);
467
468                 down(&dir_dentry->d_inode->i_sem);
469                 rc2 = filter_destroy_internal(obd, dir_dentry, object_dentry);
470                 if (rc2 && !rc)
471                         rc = rc2;
472                 up(&dir_dentry->d_inode->i_sem);
473         }
474
475         f_dput(object_dentry);
476         kmem_cache_free(filter_open_cache, ffd);
477
478         RETURN(rc);
479 }
480
481 /* obd methods */
482 static int filter_connect(struct lustre_handle *conn, struct obd_device *obd,
483                           obd_uuid_t cluuid, struct recovd_obd *recovd,
484                           ptlrpc_recovery_cb_t recover)
485 {
486         struct obd_export *exp;
487         int rc;
488
489         ENTRY;
490         MOD_INC_USE_COUNT;
491         rc = class_connect(conn, obd, cluuid);
492         if (rc)
493                 GOTO(out_dec, rc);
494         exp = class_conn2export(conn);
495         LASSERT(exp);
496
497         INIT_LIST_HEAD(&exp->exp_filter_data.fed_open_head);
498         spin_lock_init(&exp->exp_filter_data.fed_lock);
499 out:
500         RETURN(rc);
501
502 out_dec:
503         MOD_DEC_USE_COUNT;
504         goto out;
505 }
506
507 static int filter_disconnect(struct lustre_handle *conn)
508 {
509         struct obd_export *exp = class_conn2export(conn);
510         struct filter_export_data *fed;
511         int rc;
512         ENTRY;
513
514         LASSERT(exp);
515         fed = &exp->exp_filter_data;
516         spin_lock(&fed->fed_lock);
517         while (!list_empty(&fed->fed_open_head)) {
518                 struct filter_file_data *ffd;
519
520                 ffd = list_entry(fed->fed_open_head.next, typeof(*ffd),
521                                  ffd_export_list);
522                 list_del(&ffd->ffd_export_list);
523                 spin_unlock(&fed->fed_lock);
524
525                 CERROR("force closing file %*s on disconnect\n",
526                        ffd->ffd_file->f_dentry->d_name.len,
527                        ffd->ffd_file->f_dentry->d_name.name);
528
529                 filter_close_internal(exp->exp_obd, ffd);
530                 spin_lock(&fed->fed_lock);
531         }
532         spin_unlock(&fed->fed_lock);
533
534         ldlm_cancel_locks_for_export(exp);
535         rc = class_disconnect(conn);
536         if (!rc)
537                 MOD_DEC_USE_COUNT;
538
539         /* XXX cleanup preallocated inodes */
540         RETURN(rc);
541 }
542
543 /* mount the file system (secretly) */
544 static int filter_setup(struct obd_device *obd, obd_count len, void *buf)
545 {
546         struct obd_ioctl_data* data = buf;
547         struct filter_obd *filter;
548         struct vfsmount *mnt;
549         int err = 0;
550         ENTRY;
551
552         if (!data->ioc_inlbuf1 || !data->ioc_inlbuf2)
553                 RETURN(-EINVAL);
554
555         MOD_INC_USE_COUNT;
556         mnt = do_kern_mount(data->ioc_inlbuf2, 0, data->ioc_inlbuf1, NULL);
557         err = PTR_ERR(mnt);
558         if (IS_ERR(mnt))
559                 GOTO(err_dec, err);
560
561         filter = &obd->u.filter;;
562         filter->fo_vfsmnt = mnt;
563         filter->fo_fstype = strdup(data->ioc_inlbuf2);
564         filter->fo_sb = mnt->mnt_root->d_inode->i_sb;
565         CERROR("%s: mnt is %p\n", data->ioc_inlbuf1, filter->fo_vfsmnt);
566         /* XXX is this even possible if do_kern_mount succeeded? */
567         if (!filter->fo_sb)
568                 GOTO(err_kfree, err = -ENODEV);
569
570         OBD_SET_CTXT_MAGIC(&filter->fo_ctxt);
571         filter->fo_ctxt.pwdmnt = mnt;
572         filter->fo_ctxt.pwd = mnt->mnt_root;
573         filter->fo_ctxt.fs = get_ds();
574
575         err = filter_prep(obd);
576         if (err)
577                 GOTO(err_kfree, err);
578         spin_lock_init(&filter->fo_fddlock);
579         spin_lock_init(&filter->fo_objidlock);
580         INIT_LIST_HEAD(&filter->fo_export_list);
581
582         obd->obd_namespace =
583                 ldlm_namespace_new("filter-tgt", LDLM_NAMESPACE_SERVER);
584         if (obd->obd_namespace == NULL)
585                 LBUG();
586
587         ptlrpc_init_client(LDLM_CB_REQUEST_PORTAL, LDLM_CB_REPLY_PORTAL,
588                            "filter_ldlm_cb_client", &obd->obd_ldlm_cb_client);
589         ptlrpc_init_client(LDLM_CANCEL_REQUEST_PORTAL, LDLM_CANCEL_REPLY_PORTAL,
590                            "filter_ldlm_cancel_client", &obd->obd_ldlm_cancel_client);
591
592         RETURN(0);
593
594 err_kfree:
595         kfree(filter->fo_fstype);
596         unlock_kernel();
597         mntput(filter->fo_vfsmnt);
598         filter->fo_sb = 0;
599         lock_kernel();
600
601 err_dec:
602         MOD_DEC_USE_COUNT;
603         return err;
604 }
605
606
607 static int filter_cleanup(struct obd_device *obd)
608 {
609         struct super_block *sb;
610         ENTRY;
611
612         if (!list_empty(&obd->obd_exports)) {
613                 CERROR("still has clients!\n");
614                 class_disconnect_all(obd);
615                 if (!list_empty(&obd->obd_exports)) {
616                         CERROR("still has exports after forced cleanup?\n");
617                         RETURN(-EBUSY);
618                 }
619         }
620
621         ldlm_namespace_free(obd->obd_namespace);
622
623         sb = obd->u.filter.fo_sb;
624         if (!obd->u.filter.fo_sb)
625                 RETURN(0);
626
627         filter_post(obd);
628
629         shrink_dcache_parent(sb->s_root);
630         unlock_kernel();
631         mntput(obd->u.filter.fo_vfsmnt);
632         obd->u.filter.fo_sb = 0;
633         kfree(obd->u.filter.fo_fstype);
634
635         lock_kernel();
636
637         MOD_DEC_USE_COUNT;
638         RETURN(0);
639 }
640
641
642 static void filter_from_inode(struct obdo *oa, struct inode *inode, int valid)
643 {
644         int type = oa->o_mode & S_IFMT;
645         ENTRY;
646
647         CDEBUG(D_INFO, "src inode %ld (%p), dst obdo %ld valid 0x%08x\n",
648                inode->i_ino, inode, (long)oa->o_id, valid);
649         /* Don't copy the inode number in place of the object ID */
650         obdo_from_inode(oa, inode, valid);
651         oa->o_mode &= ~S_IFMT;
652         oa->o_mode |= type;
653
654         if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) {
655                 obd_rdev rdev = kdev_t_to_nr(inode->i_rdev);
656                 oa->o_rdev = rdev;
657                 oa->o_valid |= OBD_MD_FLRDEV;
658         }
659
660         EXIT;
661 }
662
663 static struct filter_file_data *filter_handle2ffd(struct lustre_handle *handle)
664 {
665         struct filter_file_data *ffd = NULL;
666         ENTRY;
667
668         if (!handle || !handle->addr)
669                 RETURN(NULL);
670
671         ffd = (struct filter_file_data *)(unsigned long)(handle->addr);
672         if (!kmem_cache_validate(filter_open_cache, (void *)ffd))
673                 RETURN(NULL);
674
675         if (ffd->ffd_servercookie != handle->cookie)
676                 RETURN(NULL);
677
678         LASSERT(ffd->ffd_file->private_data == ffd);
679         RETURN(ffd);
680 }
681
682 static struct dentry *__filter_oa2dentry(struct lustre_handle *conn,
683                                          struct obdo *oa, char *what)
684 {
685         struct dentry *dentry = NULL;
686
687         if (oa->o_valid & OBD_MD_FLHANDLE) {
688                 struct lustre_handle *ost_handle = obdo_handle(oa);
689                 struct filter_file_data *ffd = filter_handle2ffd(ost_handle);
690
691                 if (ffd)
692                         dentry = dget(ffd->ffd_file->f_dentry);
693         }
694
695         if (!dentry) {
696                 struct obd_device *obd = class_conn2obd(conn);
697                 if (!obd) {
698                         CERROR("invalid client "LPX64"\n", conn->addr);
699                         RETURN(ERR_PTR(-EINVAL));
700                 }
701                 dentry = filter_fid2dentry(obd, filter_parent(obd, oa->o_mode),
702                                            oa->o_id, oa->o_mode);
703         }
704
705         if (!dentry->d_inode) {
706                 CERROR("%s on non-existent object: "LPU64"\n", what, oa->o_id);
707                 f_dput(dentry);
708                 dentry = ERR_PTR(-ENOENT);
709         }
710
711         return dentry;
712 }
713
714 #define filter_oa2dentry(conn, oa) __filter_oa2dentry(conn, oa, __FUNCTION__)
715
716 static int filter_getattr(struct lustre_handle *conn, struct obdo *oa,
717                           struct lov_stripe_md *md)
718 {
719         struct dentry *dentry = NULL;
720         int rc = 0;
721         ENTRY;
722
723         dentry = filter_oa2dentry(conn, oa);
724         if (IS_ERR(dentry))
725                 RETURN(PTR_ERR(dentry));
726
727         filter_from_inode(oa, dentry->d_inode, oa->o_valid);
728
729         f_dput(dentry);
730         RETURN(rc);
731 }
732
733 static int filter_setattr(struct lustre_handle *conn, struct obdo *oa,
734                           struct lov_stripe_md *md)
735 {
736         struct obd_run_ctxt saved;
737         struct obd_device *obd = class_conn2obd(conn);
738         struct dentry *dentry;
739         struct iattr iattr;
740         struct inode *inode;
741         int rc;
742         ENTRY;
743
744         dentry = filter_oa2dentry(conn, oa);
745
746         if (IS_ERR(dentry))
747                 RETURN(PTR_ERR(dentry));
748
749         iattr_from_obdo(&iattr, oa, oa->o_valid);
750         iattr.ia_mode = (iattr.ia_mode & ~S_IFMT) | S_IFREG;
751         inode = dentry->d_inode;
752
753         lock_kernel();
754         if (iattr.ia_valid & ATTR_SIZE)
755                 down(&inode->i_sem);
756         push_ctxt(&saved, &obd->u.filter.fo_ctxt, NULL);
757         if (inode->i_op->setattr)
758                 rc = inode->i_op->setattr(dentry, &iattr);
759         else
760                 rc = inode_setattr(inode, &iattr);
761         pop_ctxt(&saved);
762         if (iattr.ia_valid & ATTR_SIZE) {
763                 up(&inode->i_sem);
764                 oa->o_valid = OBD_MD_FLBLOCKS | OBD_MD_FLCTIME | OBD_MD_FLMTIME;
765                 obdo_from_inode(oa, inode, oa->o_valid);
766         }
767         unlock_kernel();
768
769         f_dput(dentry);
770         RETURN(rc);
771 }
772
773 static int filter_open(struct lustre_handle *conn, struct obdo *oa,
774                        struct lov_stripe_md *ea)
775 {
776         struct obd_export *export;
777         struct lustre_handle *handle;
778         struct filter_file_data *ffd;
779         struct file *filp;
780         int rc = 0;
781         ENTRY;
782
783         export = class_conn2export(conn);
784         if (!export) {
785                 CDEBUG(D_IOCTL, "fatal: invalid client "LPX64"\n", conn->addr);
786                 RETURN(-EINVAL);
787         }
788
789         filp = filter_obj_open(export, oa->o_id, oa->o_mode);
790         if (IS_ERR(filp))
791                 GOTO(out, rc = PTR_ERR(filp));
792
793         filter_from_inode(oa, filp->f_dentry->d_inode, oa->o_valid);
794
795         ffd = filp->private_data;
796         handle = obdo_handle(oa);
797         handle->addr = (__u64)(unsigned long)ffd;
798         handle->cookie = ffd->ffd_servercookie;
799         oa->o_valid |= OBD_MD_FLHANDLE;
800 out:
801         RETURN(rc);
802 } /* filter_open */
803
804 static int filter_close(struct lustre_handle *conn, struct obdo *oa,
805                         struct lov_stripe_md *ea)
806 {
807         struct obd_export *exp;
808         struct filter_file_data *ffd;
809         struct filter_export_data *fed;
810         int rc;
811         ENTRY;
812
813         exp = class_conn2export(conn);
814         if (!exp) {
815                 CDEBUG(D_IOCTL, "fatal: invalid client "LPX64"\n", conn->addr);
816                 RETURN(-EINVAL);
817         }
818
819         if (!(oa->o_valid & OBD_MD_FLHANDLE)) {
820                 CERROR("no handle for close of objid "LPX64"\n", oa->o_id);
821                 RETURN(-EINVAL);
822         }
823
824         ffd = filter_handle2ffd(obdo_handle(oa));
825         if (!ffd) {
826                 struct lustre_handle *handle = obdo_handle(oa);
827                 CERROR("bad handle ("LPX64") or cookie ("LPX64") for close\n",
828                        handle->addr, handle->cookie);
829                 RETURN(-ESTALE);
830         }
831
832         fed = &exp->exp_filter_data;
833         spin_lock(&fed->fed_lock);
834         list_del(&ffd->ffd_export_list);
835         spin_unlock(&fed->fed_lock);
836
837         rc = filter_close_internal(exp->exp_obd, ffd);
838
839         RETURN(rc);
840 } /* filter_close */
841
842 static int filter_create(struct lustre_handle *conn, struct obdo *oa,
843                          struct lov_stripe_md **ea)
844 {
845         struct obd_device *obd = class_conn2obd(conn);
846         char name[64];
847         struct obd_run_ctxt saved;
848         struct dentry *new;
849         struct iattr;
850         ENTRY;
851
852         if (!obd) {
853                 CERROR("invalid client "LPX64"\n", conn->addr);
854                 return -EINVAL;
855         }
856
857         if (!(oa->o_mode & S_IFMT)) {
858                 CERROR("OBD %s, object "LPU64" has bad type: %o\n",
859                        __FUNCTION__, oa->o_id, oa->o_mode);
860                 return -ENOENT;
861         }
862
863         oa->o_id = filter_next_id(obd);
864
865         //filter_id(name, oa->o_id, oa->o_mode);
866         sprintf(name, LPU64, oa->o_id);
867         push_ctxt(&saved, &obd->u.filter.fo_ctxt, NULL);
868         new = simple_mknod(filter_parent(obd, oa->o_mode), name, oa->o_mode);
869         pop_ctxt(&saved);
870         if (IS_ERR(new)) {
871                 CERROR("Error mknod obj %s, err %ld\n", name, PTR_ERR(new));
872                 return -ENOENT;
873         }
874
875         /* Set flags for fields we have set in the inode struct */
876         oa->o_valid = OBD_MD_FLID | OBD_MD_FLBLKSZ | OBD_MD_FLBLOCKS |
877                  OBD_MD_FLMTIME | OBD_MD_FLATIME | OBD_MD_FLCTIME;
878         filter_from_inode(oa, new->d_inode, oa->o_valid);
879         f_dput(new);
880
881         return 0;
882 }
883
884 static int filter_destroy(struct lustre_handle *conn, struct obdo *oa,
885                           struct lov_stripe_md *ea)
886 {
887         struct obd_device *obd = class_conn2obd(conn);
888         struct dentry *dir_dentry, *object_dentry;
889         struct filter_dentry_data *fdd;
890         int rc;
891         ENTRY;
892
893         if (!obd) {
894                 CERROR("invalid client "LPX64"\n", conn->addr);
895                 RETURN(-EINVAL);
896         }
897
898         CDEBUG(D_INODE, "destroying objid "LPX64"\n", oa->o_id);
899
900         dir_dentry = filter_parent(obd, oa->o_mode);
901         down(&dir_dentry->d_inode->i_sem);
902
903         object_dentry = filter_oa2dentry(conn, oa);
904         if (IS_ERR(object_dentry))
905                 GOTO(out, rc = -ENOENT);
906
907         fdd = object_dentry->d_fsdata;
908         if (fdd && atomic_read(&fdd->fdd_open_count)) {
909                 if (!(fdd->fdd_flags & FILTER_FLAG_DESTROY)) {
910                         fdd->fdd_flags |= FILTER_FLAG_DESTROY;
911                         /* XXX put into PENDING directory in case of crash */
912                         CDEBUG(D_INODE,
913                                "defer destroy of %dx open objid "LPX64"\n",
914                                atomic_read(&fdd->fdd_open_count), oa->o_id);
915                 } else
916                         CDEBUG(D_INODE,
917                                "repeat destroy of %dx open objid "LPX64"\n",
918                                atomic_read(&fdd->fdd_open_count), oa->o_id);
919                 GOTO(out_dput, rc = 0);
920         }
921
922         rc = filter_destroy_internal(obd, dir_dentry, object_dentry);
923 out_dput:
924         f_dput(object_dentry);
925
926         EXIT;
927 out:
928         up(&dir_dentry->d_inode->i_sem);
929         return rc;
930 }
931
932 /* NB count and offset are used for punch, but not truncate */
933 static int filter_truncate(struct lustre_handle *conn, struct obdo *oa,
934                            struct lov_stripe_md *lsm,
935                            obd_off start, obd_off end)
936 {
937         int error;
938         ENTRY;
939
940         if (end != OBD_OBJECT_EOF)
941                 CERROR("PUNCH not supported, only truncate works\n");
942
943         CDEBUG(D_INODE, "calling truncate for object "LPX64", valid = %x, "
944                "o_size = "LPD64"\n", oa->o_id, oa->o_valid, start);
945         oa->o_size = start;
946         error = filter_setattr(conn, oa, NULL);
947         RETURN(error);
948 }
949
950 static int filter_pgcache_brw(int cmd, struct lustre_handle *conn,
951                               struct lov_stripe_md *lsm, obd_count oa_bufs,
952                               struct brw_page *pga, brw_callback_t callback,
953                               struct io_cb_data *data)
954 {
955         struct obd_export       *export = class_conn2export(conn);
956         struct obd_run_ctxt      saved;
957         struct super_block      *sb;
958         int                      pnum;          /* index to pages (bufs) */
959         unsigned long            retval;
960         int                      error;
961         struct file             *file;
962         int pg;
963         ENTRY;
964
965         if (!export) {
966                 CDEBUG(D_IOCTL, "invalid client "LPX64"\n", conn->addr);
967                 RETURN(-EINVAL);
968         }
969
970         sb = export->exp_obd->u.filter.fo_sb;
971         push_ctxt(&saved, &export->exp_obd->u.filter.fo_ctxt, NULL);
972         pnum = 0; /* pnum indexes buf 0..num_pages */
973
974         file = filter_obj_open(export, lsm->lsm_object_id, S_IFREG);
975         if (IS_ERR(file))
976                 GOTO(out, retval = PTR_ERR(file));
977
978         /* count doubles as retval */
979         for (pg = 0; pg < oa_bufs; pg++) {
980                 CDEBUG(D_INODE, "OP %d obdo pgno: (%d) (%ld,"LPU64
981                        ") off count ("LPU64",%d)\n",
982                        cmd, pnum, file->f_dentry->d_inode->i_ino,
983                        pga[pnum].off >> PAGE_CACHE_SHIFT, pga[pnum].off,
984                        (int)pga[pnum].count);
985                 if (cmd & OBD_BRW_WRITE) {
986                         loff_t off;
987                         char *buffer;
988                         off = pga[pnum].off;
989                         buffer = kmap(pga[pnum].pg);
990                         retval = file->f_op->write(file, buffer,
991                                                    pga[pnum].count,
992                                                    &off);
993                         kunmap(pga[pnum].pg);
994                         CDEBUG(D_INODE, "retval %ld\n", retval);
995                 } else {
996                         loff_t off = pga[pnum].off;
997                         char *buffer = kmap(pga[pnum].pg);
998
999                         if (off >= file->f_dentry->d_inode->i_size) {
1000                                 memset(buffer, 0, pga[pnum].count);
1001                                 retval = pga[pnum].count;
1002                         } else {
1003                                 retval = file->f_op->read(file, buffer,
1004                                                           pga[pnum].count, &off);
1005                         }
1006                         kunmap(pga[pnum].pg);
1007
1008                         if (retval != pga[pnum].count) {
1009                                 filp_close(file, 0);
1010                                 GOTO(out, retval = -EIO);
1011                         }
1012                         CDEBUG(D_INODE, "retval %ld\n", retval);
1013                 }
1014                 pnum++;
1015         }
1016         /* sizes and blocks are set by generic_file_write */
1017         /* ctimes/mtimes will follow with a setattr call */
1018         filp_close(file, 0);
1019
1020         /* XXX: do something with callback if it is set? */
1021
1022         EXIT;
1023 out:
1024         pop_ctxt(&saved);
1025         error = (retval >= 0) ? 0 : retval;
1026         return error;
1027 }
1028
1029 /*
1030  * Calculate the number of buffer credits needed to write multiple pages in
1031  * a single ext3/extN transaction.  No, this shouldn't be here, but as yet
1032  * ext3 doesn't have a nice API for calculating this sort of thing in advance.
1033  *
1034  * See comment above ext3_writepage_trans_blocks for details.  We assume
1035  * no data journaling is being done, but it does allow for all of the pages
1036  * being non-contiguous.  If we are guaranteed contiguous pages we could
1037  * reduce the number of (d)indirect blocks a lot.
1038  *
1039  * With N blocks per page and P pages, for each inode we have at most:
1040  * N*P indirect
1041  * min(N*P, blocksize/4 + 1) dindirect blocks
1042  * 1 tindirect
1043  *
1044  * For the entire filesystem, we have at most:
1045  * min(sum(nindir + P), ngroups) bitmap blocks (from the above)
1046  * min(sum(nindir + P), gdblocks) group descriptor blocks (from the above)
1047  * 1 inode block
1048  * 1 superblock
1049  * 2 * EXT3_SINGLEDATA_TRANS_BLOCKS for the quota files
1050  */
1051 static int ext3_credits_needed(struct super_block *sb, int objcount,
1052                                struct obd_ioobj *obj)
1053 {
1054         struct obd_ioobj *o = obj;
1055         int blockpp = 1 << (PAGE_CACHE_SHIFT - sb->s_blocksize_bits);
1056         int addrpp = EXT3_ADDR_PER_BLOCK(sb) * blockpp;
1057         int nbitmaps = 0;
1058         int ngdblocks = 0;
1059         int needed = objcount + 1;
1060         int i;
1061
1062         for (i = 0; i < objcount; i++, o++) {
1063                 int nblocks = o->ioo_bufcnt * blockpp;
1064                 int ndindirect = min(nblocks, addrpp + 1);
1065                 int nindir = nblocks + ndindirect + 1;
1066
1067                 nbitmaps += nindir + nblocks;
1068                 ngdblocks += nindir + nblocks;
1069
1070                 needed += nindir;
1071         }
1072
1073         /* Assumes ext3 and extN have same sb_info layout at the start. */
1074         if (nbitmaps > EXT3_SB(sb)->s_groups_count)
1075                 nbitmaps = EXT3_SB(sb)->s_groups_count;
1076         if (ngdblocks > EXT3_SB(sb)->s_gdb_count)
1077                 ngdblocks = EXT3_SB(sb)->s_gdb_count;
1078
1079         needed += nbitmaps + ngdblocks;
1080
1081 #ifdef CONFIG_QUOTA
1082         /* We assume that there will be 1 bit set in s_dquot.flags for each
1083          * quota file that is active.  This is at least true for now.
1084          */
1085         needed += hweight32(sb_any_quota_enabled(sb)) *
1086                 EXT3_SINGLEDATA_TRANS_BLOCKS;
1087 #endif
1088
1089         return needed;
1090 }
1091
1092 /* We have to start a huge journal transaction here to hold all of the
1093  * metadata for the pages being written here.  This is necessitated by
1094  * the fact that we do lots of prepare_write operations before we do
1095  * any of the matching commit_write operations, so even if we split
1096  * up to use "smaller" transactions none of them could complete until
1097  * all of them were opened.  By having a single journal transaction,
1098  * we eliminate duplicate reservations for common blocks like the
1099  * superblock and group descriptors or bitmaps.
1100  *
1101  * We will start the transaction here, but each prepare_write will
1102  * add a refcount to the transaction, and each commit_write will
1103  * remove a refcount.  The transaction will be closed when all of
1104  * the pages have been written.
1105  */
1106 static void *ext3_filter_journal_start(struct filter_obd *filter,
1107                                        int objcount, struct obd_ioobj *obj,
1108                                        int niocount, struct niobuf_remote *nb)
1109 {
1110         journal_t *journal = NULL;
1111         handle_t *handle = NULL;
1112         int needed;
1113
1114         /* It appears that some kernels have different values for
1115          * EXT*_MAX_GROUP_LOADED (either 8 or 32), so we cannot
1116          * assume anything after s_inode_bitmap_number is the same.
1117          */
1118         if (!strcmp(filter->fo_fstype, "ext3"))
1119                 journal = EXT3_SB(filter->fo_sb)->s_journal;
1120 #if (LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0))
1121         else if (!strcmp(filter->fo_fstype, "extN"))
1122                 journal = EXTN_SB(filter->fo_sb)->s_journal;
1123 #endif
1124         needed = ext3_credits_needed(filter->fo_sb, objcount, obj);
1125
1126         /* The number of blocks we could _possibly_ dirty can very large.
1127          * We reduce our request if it is absurd (and we couldn't get that
1128          * many credits for a single handle anyways).
1129          *
1130          * At some point we have to limit the size of I/Os sent at one time,
1131          * increase the size of the journal, or we have to calculate the
1132          * actual journal requirements more carefully by checking all of
1133          * the blocks instead of being maximally pessimistic.  It remains to
1134          * be seen if this is a real problem or not.
1135          */
1136         if (needed > journal->j_max_transaction_buffers) {
1137                 CERROR("want too many journal credits (%d) using %d instead\n",
1138                        needed, journal->j_max_transaction_buffers);
1139                 needed = journal->j_max_transaction_buffers;
1140         }
1141
1142         lock_kernel();
1143         handle = journal_start(journal, needed);
1144         unlock_kernel();
1145         if (IS_ERR(handle))
1146                 CERROR("can't get handle for %d credits: rc = %ld\n", needed,
1147                        PTR_ERR(handle));
1148
1149         return(handle);
1150 }
1151
1152 static void *filter_journal_start(void **journal_save,
1153                                   struct filter_obd *filter,
1154                                   int objcount, struct obd_ioobj *obj,
1155                                   int niocount, struct niobuf_remote *nb)
1156 {
1157         void *handle = NULL;
1158
1159         /* This may not be necessary - we probably never have a
1160          * transaction started when we enter here, so we can
1161          * remove the saving of the journal state entirely.
1162          * For now leave it in just to see if it ever happens.
1163          */
1164         *journal_save = current->journal_info;
1165         if (*journal_save) {
1166                 CERROR("Already have handle %p???\n", *journal_save);
1167                 LBUG();
1168                 current->journal_info = NULL;
1169         }
1170
1171         if (!strcmp(filter->fo_fstype, "ext3") ||
1172             !strcmp(filter->fo_fstype, "extN"))
1173                 handle = ext3_filter_journal_start(filter, objcount, obj,
1174                                                    niocount, nb);
1175         return handle;
1176 }
1177
1178 static int ext3_filter_journal_stop(void *handle)
1179 {
1180         int rc;
1181
1182         /* We got a refcount on the handle for each call to prepare_write,
1183          * so we can drop the "parent" handle here to avoid the need for
1184          * osc to call back into filterobd to close the handle.  The
1185          * remaining references will be dropped in commit_write.
1186          */
1187         lock_kernel();
1188         rc = journal_stop((handle_t *)handle);
1189         unlock_kernel();
1190
1191         return rc;
1192 }
1193
1194 static int filter_journal_stop(void *journal_save, struct filter_obd *filter,
1195                                void *handle)
1196 {
1197         int rc = 0;
1198
1199         if (!strcmp(filter->fo_fstype, "ext3") ||
1200             !strcmp(filter->fo_fstype, "extN"))
1201                 rc = ext3_filter_journal_stop(handle);
1202
1203         if (rc)
1204                 CERROR("error on journal stop: rc = %d\n", rc);
1205
1206         current->journal_info = journal_save;
1207
1208         return rc;
1209 }
1210
1211 static inline void lustre_put_page(struct page *page)
1212 {
1213         kunmap(page);
1214         page_cache_release(page);
1215 }
1216
1217
1218 static struct page *
1219 lustre_get_page_read(struct inode *inode, struct niobuf_remote *rnb)
1220 {
1221         unsigned long index = rnb->offset >> PAGE_SHIFT;
1222         struct address_space *mapping = inode->i_mapping;
1223         struct page *page;
1224         int rc;
1225
1226         page = read_cache_page(mapping, index,
1227                                (filler_t*)mapping->a_ops->readpage, NULL);
1228         if (!IS_ERR(page)) {
1229                 wait_on_page(page);
1230                 kmap(page);
1231                 if (!PageUptodate(page)) {
1232                         CERROR("page index %lu not uptodate\n", index);
1233                         GOTO(err_page, rc = -EIO);
1234                 }
1235                 if (PageError(page)) {
1236                         CERROR("page index %lu has error\n", index);
1237                         GOTO(err_page, rc = -EIO);
1238                 }
1239         }
1240         return page;
1241
1242 err_page:
1243         lustre_put_page(page);
1244         return ERR_PTR(rc);
1245 }
1246
1247 static struct page *
1248 lustre_get_page_write(struct inode *inode, unsigned long index)
1249 {
1250         struct address_space *mapping = inode->i_mapping;
1251         struct page *page;
1252         int rc;
1253
1254         page = grab_cache_page(mapping, index); /* locked page */
1255
1256         if (!IS_ERR(page)) {
1257                 kmap(page);
1258                 /* Note: Called with "O" and "PAGE_SIZE" this is essentially
1259                  * a no-op for most filesystems, because we write the whole
1260                  * page.  For partial-page I/O this will read in the page.
1261                  */
1262                 rc = mapping->a_ops->prepare_write(NULL, page, 0, PAGE_SIZE);
1263                 if (rc) {
1264                         CERROR("page index %lu, rc = %d\n", index, rc);
1265                         if (rc != -ENOSPC)
1266                                 LBUG();
1267                         GOTO(err_unlock, rc);
1268                 }
1269                 /* XXX not sure if we need this if we are overwriting page */
1270                 if (PageError(page)) {
1271                         CERROR("error on page index %lu, rc = %d\n", index, rc);
1272                         LBUG();
1273                         GOTO(err_unlock, rc = -EIO);
1274                 }
1275         }
1276         return page;
1277
1278 err_unlock:
1279         unlock_page(page);
1280         lustre_put_page(page);
1281         return ERR_PTR(rc);
1282 }
1283
1284 static int lustre_commit_write(struct page *page, unsigned from, unsigned to)
1285 {
1286         struct inode *inode = page->mapping->host;
1287         int err;
1288
1289         err = page->mapping->a_ops->commit_write(NULL, page, from, to);
1290 #if (LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0))
1291         if (!err && IS_SYNC(inode))
1292                 err = waitfor_one_page(page);
1293 #else
1294 #warning ADD 2.5 waiting code here?
1295 #endif
1296         //SetPageUptodate(page); // the client commit_write will do this
1297
1298         SetPageReferenced(page);
1299         unlock_page(page);
1300         lustre_put_page(page);
1301         return err;
1302 }
1303
1304 struct page *filter_get_page_write(struct inode *inode,
1305                                    struct niobuf_remote *rnb,
1306                                    struct niobuf_local *lnb, int *pglocked)
1307 {
1308         unsigned long index = rnb->offset >> PAGE_SHIFT;
1309         struct address_space *mapping = inode->i_mapping;
1310
1311         struct page *page;
1312         int rc;
1313
1314         //ASSERT_PAGE_INDEX(index, GOTO(err, rc = -EINVAL));
1315         if (*pglocked)
1316                 page = grab_cache_page_nowait(mapping, index); /* locked page */
1317         else
1318                 page = grab_cache_page(mapping, index); /* locked page */
1319
1320
1321         /* This page is currently locked, so get a temporary page instead. */
1322         /* XXX I believe this is a very dangerous thing to do - consider if
1323          *     we had multiple writers for the same file (definitely the case
1324          *     if we are using this codepath).  If writer A locks the page,
1325          *     writer B writes to a copy (as here), writer A drops the page
1326          *     lock, and writer C grabs the lock before B does, then B will
1327          *     later overwrite the data from C, even if C had LDLM locked
1328          *     and initiated the write after B did.
1329          */
1330         if (!page) {
1331                 unsigned long addr;
1332                 CDEBUG(D_PAGE, "ino %ld page %ld locked\n", inode->i_ino,index);
1333                 addr = __get_free_pages(GFP_KERNEL, 0); /* locked page */
1334                 if (!addr) {
1335                         CERROR("no memory for a temp page\n");
1336                         LBUG();
1337                         GOTO(err, rc = -ENOMEM);
1338                 }
1339                 /* XXX debugging */
1340                 memset((void *)addr, 0xBA, PAGE_SIZE);
1341                 page = virt_to_page(addr);
1342                 kmap(page);
1343                 page->index = index;
1344                 lnb->flags |= N_LOCAL_TEMP_PAGE;
1345         } else if (!IS_ERR(page)) {
1346                 (*pglocked)++;
1347                 kmap(page);
1348
1349                 rc = mapping->a_ops->prepare_write(NULL, page,
1350                                                    rnb->offset % PAGE_SIZE,
1351                                                    rnb->len);
1352                 if (rc) {
1353                         CERROR("page index %lu, rc = %d\n", index, rc);
1354                         if (rc != -ENOSPC)
1355                                 LBUG();
1356                         GOTO(err_unlock, rc);
1357                 }
1358                 /* XXX not sure if we need this if we are overwriting page */
1359                 if (PageError(page)) {
1360                         CERROR("error on page index %lu, rc = %d\n", index, rc);
1361                         LBUG();
1362                         GOTO(err_unlock, rc = -EIO);
1363                 }
1364         }
1365         return page;
1366
1367 err_unlock:
1368         unlock_page(page);
1369         lustre_put_page(page);
1370 err:
1371         return ERR_PTR(rc);
1372 }
1373
1374 /*
1375  * We need to balance prepare_write() calls with commit_write() calls.
1376  * If the page has been prepared, but we have no data for it, we don't
1377  * want to overwrite valid data on disk, but we still need to zero out
1378  * data for space which was newly allocated.  Like part of what happens
1379  * in __block_prepare_write() for newly allocated blocks.
1380  *
1381  * XXX currently __block_prepare_write() creates buffers for all the
1382  *     pages, and the filesystems mark these buffers as BH_New if they
1383  *     were newly allocated from disk. We use the BH_New flag similarly.
1384  */
1385 static int filter_commit_write(struct page *page, unsigned from, unsigned to,
1386                                int err)
1387 {
1388 #if (LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0))
1389         if (err) {
1390                 unsigned block_start, block_end;
1391                 struct buffer_head *bh, *head = page->buffers;
1392                 unsigned blocksize = head->b_size;
1393                 void *addr = page_address(page);
1394
1395                 /* debugging: just seeing if this ever happens */
1396                 CERROR("called filter_commit_write for obj %ld:%ld on err %d\n",
1397                        page->index, page->mapping->host->i_ino, err);
1398
1399                 /* Currently one buffer per page, but in the future... */
1400                 for (bh = head, block_start = 0; bh != head || !block_start;
1401                      block_start = block_end, bh = bh->b_this_page) {
1402                         block_end = block_start + blocksize;
1403                         if (buffer_new(bh))
1404                                 memset(addr + block_start, 0, blocksize);
1405                 }
1406         }
1407 #endif
1408         return lustre_commit_write(page, from, to);
1409 }
1410
1411 static int filter_preprw(int cmd, struct lustre_handle *conn,
1412                          int objcount, struct obd_ioobj *obj,
1413                          int niocount, struct niobuf_remote *nb,
1414                          struct niobuf_local *res, void **desc_private)
1415 {
1416         struct obd_run_ctxt saved;
1417         struct obd_device *obd;
1418         struct obd_ioobj *o = obj;
1419         struct niobuf_remote *rnb = nb;
1420         struct niobuf_local *lnb = res;
1421         void *journal_save = NULL;
1422         int pglocked = 0;
1423         int rc = 0;
1424         int i;
1425         ENTRY;
1426
1427         obd = class_conn2obd(conn);
1428         if (!obd) {
1429                 CDEBUG(D_IOCTL, "invalid client "LPX64"\n", conn->addr);
1430                 RETURN(-EINVAL);
1431         }
1432         memset(res, 0, sizeof(*res) * niocount);
1433
1434         push_ctxt(&saved, &obd->u.filter.fo_ctxt, NULL);
1435
1436         if (cmd & OBD_BRW_WRITE) {
1437                 *desc_private = filter_journal_start(&journal_save,
1438                                                      &obd->u.filter,
1439                                                      objcount, obj, niocount,
1440                                                      nb);
1441                 if (IS_ERR(*desc_private))
1442                         GOTO(out_ctxt, rc = PTR_ERR(*desc_private));
1443         }
1444
1445         for (i = 0; i < objcount; i++, o++) {
1446                 struct dentry *dentry;
1447                 struct inode *inode;
1448                 int j;
1449
1450                 dentry = filter_fid2dentry(obd, filter_parent(obd, S_IFREG),
1451                                            o->ioo_id, S_IFREG);
1452                 if (IS_ERR(dentry))
1453                         GOTO(out_clean, rc = PTR_ERR(dentry));
1454                 inode = dentry->d_inode;
1455                 if (!inode) {
1456                         CERROR("trying to BRW to non-existent file "LPU64"\n",
1457                                o->ioo_id);
1458                         f_dput(dentry);
1459                         GOTO(out_clean, rc = -ENOENT);
1460                 }
1461
1462                 for (j = 0; j < o->ioo_bufcnt; j++, rnb++, lnb++) {
1463                         struct page *page;
1464
1465                         if (j == 0)
1466                                 lnb->dentry = dentry;
1467                         else
1468                                 lnb->dentry = dget(dentry);
1469
1470                         if (cmd & OBD_BRW_WRITE)
1471                                 page = filter_get_page_write(inode, rnb, lnb,
1472                                                              &pglocked);
1473                         else
1474                                 page = lustre_get_page_read(inode, rnb);
1475
1476                         if (IS_ERR(page)) {
1477                                 f_dput(dentry);
1478                                 GOTO(out_clean, rc = PTR_ERR(page));
1479                         }
1480
1481                         lnb->addr = page_address(page);
1482                         lnb->offset = rnb->offset;
1483                         lnb->page = page;
1484                         lnb->len = rnb->len;
1485                 }
1486         }
1487
1488 out_stop:
1489         if (cmd & OBD_BRW_WRITE) {
1490                 int err = filter_journal_stop(journal_save, &obd->u.filter,
1491                                               *desc_private);
1492                 if (!rc)
1493                         rc = err;
1494         }
1495 out_ctxt:
1496         pop_ctxt(&saved);
1497         RETURN(rc);
1498 out_clean:
1499         while (lnb-- > res) {
1500                 CERROR("error cleanup on brw\n");
1501                 f_dput(lnb->dentry);
1502                 if (cmd & OBD_BRW_WRITE)
1503                         filter_commit_write(lnb->page, 0, PAGE_SIZE, rc);
1504                 else
1505                         lustre_put_page(lnb->page);
1506         }
1507         goto out_stop;
1508 }
1509
1510 static int filter_write_locked_page(struct niobuf_local *lnb)
1511 {
1512         struct page *lpage;
1513         int rc;
1514
1515         lpage = lustre_get_page_write(lnb->dentry->d_inode, lnb->page->index);
1516         if (IS_ERR(lpage)) {
1517                 /* It is highly unlikely that we would ever get an error here.
1518                  * The page we want to get was previously locked, so it had to
1519                  * have already allocated the space, and we were just writing
1520                  * over the same data, so there would be no hole in the file.
1521                  *
1522                  * XXX: possibility of a race with truncate could exist, need
1523                  *      to check that.  There are no guarantees w.r.t.
1524                  *      write order even on a local filesystem, although the
1525                  *      normal response would be to return the number of bytes
1526                  *      successfully written and leave the rest to the app.
1527                  */
1528                 rc = PTR_ERR(lpage);
1529                 CERROR("error getting locked page index %ld: rc = %d\n",
1530                        lnb->page->index, rc);
1531                 GOTO(out, rc);
1532         }
1533
1534         /* lpage is kmapped in lustre_get_page_write() above and kunmapped in
1535          * lustre_commit_write() below, lnb->page was kmapped previously in
1536          * filter_get_page_write() and kunmapped in lustre_put_page() below.
1537          */
1538         memcpy(page_address(lpage), page_address(lnb->page), PAGE_SIZE);
1539         rc = lustre_commit_write(lpage, 0, PAGE_SIZE);
1540         if (rc)
1541                 CERROR("error committing locked page %ld: rc = %d\n",
1542                        lnb->page->index, rc);
1543 out:
1544         lustre_put_page(lnb->page);
1545
1546         return rc;
1547 }
1548
1549 static int filter_commitrw(int cmd, struct lustre_handle *conn,
1550                            int objcount, struct obd_ioobj *obj,
1551                            int niocount, struct niobuf_local *res,
1552                            void *private)
1553 {
1554         struct obd_run_ctxt saved;
1555         struct obd_ioobj *o;
1556         struct niobuf_local *r;
1557         struct obd_device *obd = class_conn2obd(conn);
1558         void *journal_save;
1559         int found_locked = 0;
1560         int rc = 0;
1561         int i;
1562         ENTRY;
1563
1564         push_ctxt(&saved, &obd->u.filter.fo_ctxt, NULL);
1565         lock_kernel();
1566         journal_save = current->journal_info;
1567         LASSERT(!journal_save);
1568
1569         current->journal_info = private;
1570         unlock_kernel();
1571         for (i = 0, o = obj, r = res; i < objcount; i++, o++) {
1572                 int j;
1573                 for (j = 0 ; j < o->ioo_bufcnt ; j++, r++) {
1574                         struct page *page = r->page;
1575
1576                         if (!page)
1577                                 LBUG();
1578
1579                         if (r->flags & N_LOCAL_TEMP_PAGE) {
1580                                 found_locked++;
1581                                 continue;
1582                         }
1583
1584                         if (cmd & OBD_BRW_WRITE) {
1585                                 int err = filter_commit_write(page, 0,
1586                                                               r->len, 0);
1587
1588                                 if (!rc)
1589                                         rc = err;
1590                         } else
1591                                 lustre_put_page(page);
1592
1593                         f_dput(r->dentry);
1594                 }
1595         }
1596         lock_kernel();
1597         current->journal_info = journal_save;
1598         unlock_kernel();
1599
1600         if (!found_locked)
1601                 goto out_ctxt;
1602
1603         for (i = 0, o = obj, r = res; i < objcount; i++, o++) {
1604                 int j;
1605                 for (j = 0 ; j < o->ioo_bufcnt ; j++, r++) {
1606                         int err;
1607                         if (!(r->flags & N_LOCAL_TEMP_PAGE))
1608                                 continue;
1609
1610                         err = filter_write_locked_page(r);
1611                         if (!rc)
1612                                 rc = err;
1613                         f_dput(r->dentry);
1614                 }
1615         }
1616
1617 out_ctxt:
1618         pop_ctxt(&saved);
1619         RETURN(rc);
1620 }
1621
1622 static int filter_statfs(struct lustre_handle *conn, struct obd_statfs *osfs)
1623 {
1624         struct obd_device *obd = class_conn2obd(conn);
1625         struct statfs sfs;
1626         int rc;
1627
1628         ENTRY;
1629         rc = vfs_statfs(obd->u.filter.fo_sb, &sfs);
1630         if (!rc)
1631                 statfs_pack(osfs, &sfs);
1632
1633         return rc;
1634 }
1635
1636 static int filter_get_info(struct lustre_handle *conn, obd_count keylen,
1637                            void *key, obd_count *vallen, void **val)
1638 {
1639         struct obd_device *obd;
1640         ENTRY;
1641
1642         obd = class_conn2obd(conn);
1643         if (!obd) {
1644                 CDEBUG(D_IOCTL, "invalid client "LPX64"\n", conn->addr);
1645                 RETURN(-EINVAL);
1646         }
1647
1648         if ( keylen == strlen("blocksize") &&
1649              memcmp(key, "blocksize", keylen) == 0 ) {
1650                 *vallen = sizeof(long);
1651                 *val = (void *)(long)obd->u.filter.fo_sb->s_blocksize;
1652                 RETURN(0);
1653         }
1654
1655         if ( keylen == strlen("blocksize_bits") &&
1656              memcmp(key, "blocksize_bits", keylen) == 0 ){
1657                 *vallen = sizeof(long);
1658                 *val = (void *)(long)obd->u.filter.fo_sb->s_blocksize_bits;
1659                 RETURN(0);
1660         }
1661
1662         if ( keylen == strlen("root_ino") &&
1663              memcmp(key, "root_ino", keylen) == 0 ){
1664                 *vallen = sizeof(obd_id);
1665                 *val = (void *)(obd_id)FILTER_ROOTINO;
1666                 RETURN(0);
1667         }
1668
1669         CDEBUG(D_IOCTL, "invalid key\n");
1670         RETURN(-EINVAL);
1671 }
1672
1673 int filter_copy_data(struct lustre_handle *dst_conn, struct obdo *dst,
1674                   struct lustre_handle *src_conn, struct obdo *src,
1675                   obd_size count, obd_off offset)
1676 {
1677         struct page *page;
1678         struct lov_stripe_md srcmd, dstmd;
1679         unsigned long index = 0;
1680         int err = 0;
1681
1682         memset(&srcmd, 0, sizeof(srcmd));
1683         memset(&dstmd, 0, sizeof(dstmd));
1684         srcmd.lsm_object_id = src->o_id;
1685         dstmd.lsm_object_id = dst->o_id;
1686
1687         ENTRY;
1688         CDEBUG(D_INFO, "src: ino "LPU64" blocks "LPU64", size "LPU64
1689                ", dst: ino "LPU64"\n",
1690                src->o_id, src->o_blocks, src->o_size, dst->o_id);
1691         page = alloc_page(GFP_USER);
1692         if (page == NULL)
1693                 RETURN(-ENOMEM);
1694
1695 #if (LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0))
1696         while (TryLockPage(page))
1697                 ___wait_on_page(page);
1698 #else
1699         wait_on_page_locked(page);
1700 #endif
1701
1702         /* XXX with brw vector I/O, we could batch up reads and writes here,
1703          *     all we need to do is allocate multiple pages to handle the I/Os
1704          *     and arrays to handle the request parameters.
1705          */
1706         while (index < ((src->o_size + PAGE_SIZE - 1) >> PAGE_SHIFT)) {
1707                 struct brw_page pg;
1708                 struct io_cb_data *cbd = ll_init_cb();
1709
1710                 if (!cbd) {
1711                         err = -ENOMEM;
1712                         EXIT;
1713                         break;
1714                 }
1715
1716                 pg.pg = page;
1717                 pg.count = PAGE_SIZE;
1718                 pg.off = (page->index) << PAGE_SHIFT;
1719                 pg.flag = 0;
1720
1721                 page->index = index;
1722                 err = obd_brw(OBD_BRW_READ, src_conn, &srcmd, 1, &pg,
1723                               ll_sync_io_cb, cbd);
1724
1725                 if ( err ) {
1726                         EXIT;
1727                         break;
1728                 }
1729
1730                 cbd = ll_init_cb();
1731                 if (!cbd) {
1732                         err = -ENOMEM;
1733                         EXIT;
1734                         break;
1735                 }
1736                 pg.flag = OBD_BRW_CREATE;
1737                 CDEBUG(D_INFO, "Read page %ld ...\n", page->index);
1738
1739                 err = obd_brw(OBD_BRW_WRITE, dst_conn, &dstmd, 1, &pg,
1740                               ll_sync_io_cb, cbd);
1741
1742                 /* XXX should handle dst->o_size, dst->o_blocks here */
1743                 if ( err ) {
1744                         EXIT;
1745                         break;
1746                 }
1747
1748                 CDEBUG(D_INFO, "Wrote page %ld ...\n", page->index);
1749
1750                 index++;
1751         }
1752         dst->o_size = src->o_size;
1753         dst->o_blocks = src->o_blocks;
1754         dst->o_valid |= OBD_MD_FLSIZE | OBD_MD_FLBLOCKS;
1755         unlock_page(page);
1756         __free_page(page);
1757
1758         RETURN(err);
1759 }
1760 int filter_attach(struct obd_device *dev, 
1761                    obd_count len, void *data)
1762 {
1763
1764         int rc;
1765         rc = lprocfs_reg_obd(dev, (struct lprocfs_vars*)status_var_nm_1, 
1766                              (void*)dev);
1767         return rc; 
1768 }
1769
1770 int filter_detach(struct obd_device *dev)
1771 {
1772         int rc;
1773         rc = lprocfs_dereg_obd(dev);
1774         return rc;
1775
1776 }
1777 static struct obd_ops filter_obd_ops = {
1778         o_attach:      filter_attach,
1779         o_detach:      filter_detach,
1780         o_get_info:    filter_get_info,
1781         o_setup:       filter_setup,
1782         o_cleanup:     filter_cleanup,
1783         o_connect:     filter_connect,
1784         o_disconnect:  filter_disconnect,
1785         o_statfs:      filter_statfs,
1786         o_getattr:     filter_getattr,
1787         o_create:      filter_create,
1788         o_setattr:     filter_setattr,
1789         o_destroy:     filter_destroy,
1790         o_open:        filter_open,
1791         o_close:       filter_close,
1792         o_brw:         filter_pgcache_brw,
1793         o_punch:       filter_truncate,
1794         o_preprw:      filter_preprw,
1795         o_commitrw:    filter_commitrw
1796 #if 0
1797         o_preallocate: filter_preallocate_inodes,
1798         o_migrate:     filter_migrate,
1799         o_copy:        filter_copy_data,
1800         o_iterate:     filter_iterate
1801 #endif
1802 };
1803
1804
1805 static int __init obdfilter_init(void)
1806 {
1807         printk(KERN_INFO "Filtering OBD driver  v0.001, info@clusterfs.com\n");
1808         filter_open_cache = kmem_cache_create("ll_filter_fdata",
1809                                               sizeof(struct filter_file_data),
1810                                               0, 0, NULL, NULL);
1811         if (!filter_open_cache)
1812                 RETURN(-ENOMEM);
1813
1814         filter_dentry_cache = kmem_cache_create("ll_filter_dentry",
1815                                         sizeof(struct filter_dentry_data),
1816                                         0, 0, NULL, NULL);
1817         if (!filter_dentry_cache) {
1818                 kmem_cache_destroy(filter_open_cache);
1819                 RETURN(-ENOMEM);
1820         }
1821
1822         return class_register_type(&filter_obd_ops, 
1823                                    (struct lprocfs_vars*)status_class_var,
1824                                    OBD_FILTER_DEVICENAME);
1825 }
1826
1827 static void __exit obdfilter_exit(void)
1828 {
1829         class_unregister_type(OBD_FILTER_DEVICENAME);
1830         if (kmem_cache_destroy(filter_dentry_cache))
1831                 CERROR("couldn't free obdfilter dentry cache\n");
1832         if (kmem_cache_destroy(filter_open_cache))
1833                 CERROR("couldn't free obdfilter open cache\n");
1834 }
1835
1836 MODULE_AUTHOR("Cluster File Systems, Inc. <info@clusterfs.com>");
1837 MODULE_DESCRIPTION("Lustre Filtering OBD driver v1.0");
1838 MODULE_LICENSE("GPL");
1839
1840 module_init(obdfilter_init);
1841 module_exit(obdfilter_exit);