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