Whamcloud - gitweb
36d126dcef39edc32d7791c3c6e0439105f0f1e1
[fs/lustre-release.git] / lustre / lvfs / fsfilt_ext3.c
1 /* -*- mode: c; c-basic-offset: 8; indent-tabs-mode: nil; -*-
2  * vim:expandtab:shiftwidth=8:tabstop=8:
3  *
4  * GPL HEADER START
5  *
6  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License version 2 only,
10  * as published by the Free Software Foundation.
11  *
12  * This program is distributed in the hope that it will be useful, but
13  * WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * General Public License version 2 for more details (a copy is included
16  * in the LICENSE file that accompanied this code).
17  *
18  * You should have received a copy of the GNU General Public License
19  * version 2 along with this program; If not, see
20  * http://www.sun.com/software/products/lustre/docs/GPLv2.pdf
21  *
22  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
23  * CA 95054 USA or visit www.sun.com if you need additional information or
24  * have any questions.
25  *
26  * GPL HEADER END
27  */
28 /*
29  * Copyright  2008 Sun Microsystems, Inc. All rights reserved
30  * Use is subject to license terms.
31  */
32 /*
33  * This file is part of Lustre, http://www.lustre.org/
34  * Lustre is a trademark of Sun Microsystems, Inc.
35  *
36  * lustre/lvfs/fsfilt_ext3.c
37  *
38  * Author: Andreas Dilger <adilger@clusterfs.com>
39  */
40
41 #define DEBUG_SUBSYSTEM S_FILTER
42
43 #include <linux/init.h>
44 #include <linux/module.h>
45 #include <linux/fs.h>
46 #include <linux/slab.h>
47 #include <linux/pagemap.h>
48 #include <linux/quotaops.h>
49 #ifdef HAVE_EXT4_LDISKFS
50 #include <ext4/ext4.h>
51 #include <ext4/ext4_jbd2.h>
52 #else
53 #include <linux/jbd.h>
54 #include <linux/ext3_fs.h>
55 #include <linux/ext3_jbd.h>
56 #endif
57 #include <linux/version.h>
58 #include <linux/bitops.h>
59 #include <linux/quota.h>
60 #include <linux/quotaio_v1.h>
61 #include <linux/quotaio_v2.h>
62 #if defined(HAVE_EXT3_XATTR_H)
63 #include <ext3/xattr.h>
64 #else
65 /* ext3 xattr.h not available in rh style kernel-devel rpm */
66 extern int ext3_xattr_get(struct inode *, int, const char *, void *, size_t);
67 extern int ext3_xattr_set_handle(handle_t *, struct inode *, int, const char *, const void *, size_t, int);
68 #endif
69
70 #include <libcfs/libcfs.h>
71 #include <lustre_fsfilt.h>
72 #include <obd.h>
73 #include <lustre_quota.h>
74 #include <linux/lustre_compat25.h>
75 #include <linux/lprocfs_status.h>
76
77 #ifdef EXT3_MULTIBLOCK_ALLOCATOR
78 #ifdef HAVE_EXT4_LDISKFS
79 #include <ext4/ext4_extents.h>
80 #else
81 #include <linux/ext3_extents.h>
82 #endif
83 #endif
84
85 #include "lustre_quota_fmt.h"
86
87 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,15)
88 #define FSFILT_DATA_TRANS_BLOCKS(sb)      EXT3_DATA_TRANS_BLOCKS
89 #define FSFILT_DELETE_TRANS_BLOCKS(sb)    EXT3_DELETE_TRANS_BLOCKS
90 #else
91 #define FSFILT_DATA_TRANS_BLOCKS(sb)      EXT3_DATA_TRANS_BLOCKS(sb)
92 #define FSFILT_DELETE_TRANS_BLOCKS(sb)    EXT3_DELETE_TRANS_BLOCKS(sb)
93 #endif
94
95 #ifdef EXT3_SINGLEDATA_TRANS_BLOCKS_HAS_SB
96 /* for kernels 2.6.18 and later */
97 #define FSFILT_SINGLEDATA_TRANS_BLOCKS(sb) EXT3_SINGLEDATA_TRANS_BLOCKS(sb)
98 #else
99 #define FSFILT_SINGLEDATA_TRANS_BLOCKS(sb) EXT3_SINGLEDATA_TRANS_BLOCKS
100 #endif
101
102 static cfs_mem_cache_t *fcb_cache;
103
104 struct fsfilt_cb_data {
105         struct journal_callback cb_jcb; /* jbd private data - MUST BE FIRST */
106         fsfilt_cb_t cb_func;            /* MDS/OBD completion function */
107         struct obd_device *cb_obd;      /* MDS/OBD completion device */
108         __u64 cb_last_rcvd;             /* MDS/OST last committed operation */
109         void *cb_data;                  /* MDS/OST completion function data */
110 };
111
112 #ifndef EXT3_XATTR_INDEX_TRUSTED        /* temporary until we hit l28 kernel */
113 #define EXT3_XATTR_INDEX_TRUSTED        4
114 #endif
115
116 #ifdef HAVE_EXT4_LDISKFS
117 #define fsfilt_log_start_commit(journal, tid) jbd2_log_start_commit(journal, tid)
118 #define fsfilt_log_wait_commit(journal, tid) jbd2_log_wait_commit(journal, tid)
119 #define fsfilt_journal_callback_set(handle, func, jcb) jbd2_journal_callback_set(handle, func, jcb)
120 #else
121 #define fsfilt_log_start_commit(journal, tid) log_start_commit(journal, tid)
122 #define fsfilt_log_wait_commit(journal, tid) log_wait_commit(journal, tid)
123 #define fsfilt_journal_callback_set(handle, func, jcb) journal_callback_set(handle, func, jcb)
124 #define ext_pblock(ex) le32_to_cpu((ex)->ee_start)
125 #define ext3_ext_store_pblock(ex, pblock)  ((ex)->ee_start = cpu_to_le32(pblock))
126 #define ext3_inode_bitmap(sb,desc) le32_to_cpu((desc)->bg_inode_bitmap)
127 #endif
128
129 static char *fsfilt_ext3_get_label(struct super_block *sb)
130 {
131         return EXT3_SB(sb)->s_es->s_volume_name;
132 }
133
134 static int fsfilt_ext3_set_label(struct super_block *sb, char *label)
135 {
136         /* see e.g. fsfilt_ext3_write_record() */
137         journal_t *journal;
138         handle_t *handle;
139         int err;
140
141         journal = EXT3_SB(sb)->s_journal;
142         handle = ext3_journal_start_sb(sb, 1);
143         if (IS_ERR(handle)) {
144                 CERROR("can't start transaction\n");
145                 return(PTR_ERR(handle));
146         }
147
148         err = ext3_journal_get_write_access(handle, EXT3_SB(sb)->s_sbh);
149         if (err)
150                 goto out;
151
152         memcpy(EXT3_SB(sb)->s_es->s_volume_name, label,
153                sizeof(EXT3_SB(sb)->s_es->s_volume_name));
154
155         err = ext3_journal_dirty_metadata(handle, EXT3_SB(sb)->s_sbh);
156
157 out:
158         ext3_journal_stop(handle);
159
160         return(err);
161 }
162
163 static char *fsfilt_ext3_uuid(struct super_block *sb)
164 {
165         return EXT3_SB(sb)->s_es->s_uuid;
166 }
167
168 #ifdef HAVE_DISK_INODE_VERSION
169
170 static __u64 get_i_version(struct inode *inode)
171 {
172 #if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,27)) && defined(HAVE_EXT4_LDISKFS)
173         return inode->i_version;
174 #else
175         return EXT3_I(inode)->i_fs_version;
176 #endif
177 }
178
179 static void set_i_version(struct inode *inode, __u64 new_version)
180 {
181 #if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,27)) && defined(HAVE_EXT4_LDISKFS)
182         inode->i_version = new_version;
183 #else
184         (EXT3_I(inode))->i_fs_version = new_version;
185 #endif
186 }
187
188 /*
189  * Get the 64-bit version for an inode.
190  */
191 static __u64 fsfilt_ext3_get_version(struct inode *inode)
192 {
193         CDEBUG(D_INFO, "Get version "LPX64" for inode %lu\n",
194                get_i_version(inode), inode->i_ino);
195         return get_i_version(inode);
196 }
197
198 /*
199  * Set the 64-bit version and return the old version.
200  */
201 static __u64 fsfilt_ext3_set_version(struct inode *inode, __u64 new_version)
202 {
203         __u64 old_version = get_i_version(inode);
204
205         CDEBUG(D_INFO, "Set version "LPX64" (old "LPX64") for inode %lu\n",
206                new_version, old_version, inode->i_ino);
207         set_i_version(inode, new_version);
208         /* version is set after all inode operations are finished, so we should
209          * mark it dirty here */
210         inode->i_sb->s_op->dirty_inode(inode);
211         return old_version;
212 }
213
214 #endif
215
216 /*
217  * We don't currently need any additional blocks for rmdir and
218  * unlink transactions because we are storing the OST oa_id inside
219  * the inode (which we will be changing anyways as part of this
220  * transaction).
221  */
222 static void *fsfilt_ext3_start(struct inode *inode, int op, void *desc_private,
223                                int logs)
224 {
225         /* For updates to the last received file */
226         int nblocks = FSFILT_SINGLEDATA_TRANS_BLOCKS(inode->i_sb);
227         journal_t *journal;
228         void *handle;
229
230         if (current->journal_info) {
231                 CDEBUG(D_INODE, "increasing refcount on %p\n",
232                        current->journal_info);
233                 goto journal_start;
234         }
235
236         switch(op) {
237         case FSFILT_OP_RMDIR:
238         case FSFILT_OP_UNLINK:
239                 /* delete one file + create/update logs for each stripe */
240                 nblocks += FSFILT_DELETE_TRANS_BLOCKS(inode->i_sb);
241                 nblocks += (EXT3_INDEX_EXTRA_TRANS_BLOCKS +
242                             FSFILT_SINGLEDATA_TRANS_BLOCKS(inode->i_sb)) * logs;
243                 break;
244         case FSFILT_OP_RENAME:
245                 /* modify additional directory */
246                 nblocks += FSFILT_SINGLEDATA_TRANS_BLOCKS(inode->i_sb);
247                 /* no break */
248         case FSFILT_OP_SYMLINK:
249                 /* additional block + block bitmap + GDT for long symlink */
250                 nblocks += 3;
251                 /* no break */
252         case FSFILT_OP_CREATE: {
253 #if defined(EXT3_EXTENTS_FL) && defined(EXT3_INDEX_FL) && !defined(HAVE_EXT4_LDISKFS)
254                 static int warned;
255                 if (!warned) {
256                         if (!test_opt(inode->i_sb, EXTENTS)) {
257                                 warned = 1;
258                         } else if (((EXT3_I(inode)->i_flags &
259                               cpu_to_le32(EXT3_EXTENTS_FL | EXT3_INDEX_FL)) ==
260                               cpu_to_le32(EXT3_EXTENTS_FL | EXT3_INDEX_FL))) {
261                                 CWARN("extent-mapped directory found with "
262                                       "ext3-based ldiskfs - contact "
263                                       "http://bugzilla.lustre.org/\n");
264                                 warned = 1;
265                         }
266                 }
267 #endif
268                 /* no break */
269         }
270         case FSFILT_OP_MKDIR:
271         case FSFILT_OP_MKNOD:
272                 /* modify one inode + block bitmap + GDT */
273                 nblocks += 3;
274                 /* no break */
275         case FSFILT_OP_LINK:
276                 /* modify parent directory */
277                 nblocks += EXT3_INDEX_EXTRA_TRANS_BLOCKS +
278                          FSFILT_DATA_TRANS_BLOCKS(inode->i_sb);
279                 /* create/update logs for each stripe */
280                 nblocks += (EXT3_INDEX_EXTRA_TRANS_BLOCKS +
281                             FSFILT_SINGLEDATA_TRANS_BLOCKS(inode->i_sb)) * logs;
282                 break;
283         case FSFILT_OP_SETATTR:
284                 /* Setattr on inode */
285                 nblocks += 1;
286                 nblocks += EXT3_INDEX_EXTRA_TRANS_BLOCKS +
287                          FSFILT_DATA_TRANS_BLOCKS(inode->i_sb);
288                 /* quota chown log for each stripe */
289                 nblocks += (EXT3_INDEX_EXTRA_TRANS_BLOCKS +
290                             FSFILT_SINGLEDATA_TRANS_BLOCKS(inode->i_sb)) * logs;
291                 break;
292         case FSFILT_OP_CANCEL_UNLINK:
293                 /* blocks for log header bitmap update OR
294                  * blocks for catalog header bitmap update + unlink of logs */
295                 nblocks = (LLOG_CHUNK_SIZE >> inode->i_blkbits) +
296                         FSFILT_DELETE_TRANS_BLOCKS(inode->i_sb) * logs;
297                 break;
298         case FSFILT_OP_JOIN:
299                 /* delete 2 file(file + array id) + create 1 file (array id)
300                  * create/update logs for each stripe */
301                 nblocks += 2 * FSFILT_DELETE_TRANS_BLOCKS(inode->i_sb);
302
303                 /*create array log for head file*/
304                 nblocks += 3;
305                 nblocks += (EXT3_INDEX_EXTRA_TRANS_BLOCKS +
306                             FSFILT_SINGLEDATA_TRANS_BLOCKS(inode->i_sb));
307                 /*update head file array */
308                 nblocks += EXT3_INDEX_EXTRA_TRANS_BLOCKS +
309                          FSFILT_DATA_TRANS_BLOCKS(inode->i_sb);
310                 break;
311         default: CERROR("unknown transaction start op %d\n", op);
312                 LBUG();
313         }
314
315         LASSERT(current->journal_info == desc_private);
316         journal = EXT3_SB(inode->i_sb)->s_journal;
317         if (nblocks > journal->j_max_transaction_buffers) {
318                 CWARN("too many credits %d for op %ux%u using %d instead\n",
319                        nblocks, op, logs, journal->j_max_transaction_buffers);
320                 nblocks = journal->j_max_transaction_buffers;
321         }
322
323  journal_start:
324         LASSERTF(nblocks > 0, "can't start %d credit transaction\n", nblocks);
325         handle = ext3_journal_start(inode, nblocks);
326
327         if (!IS_ERR(handle))
328                 LASSERT(current->journal_info == handle);
329         else
330                 CERROR("error starting handle for op %u (%u credits): rc %ld\n",
331                        op, nblocks, PTR_ERR(handle));
332         return handle;
333 }
334
335 /*
336  * Calculate the number of buffer credits needed to write multiple pages in
337  * a single ext3 transaction.  No, this shouldn't be here, but as yet ext3
338  * doesn't have a nice API for calculating this sort of thing in advance.
339  *
340  * See comment above ext3_writepage_trans_blocks for details.  We assume
341  * no data journaling is being done, but it does allow for all of the pages
342  * being non-contiguous.  If we are guaranteed contiguous pages we could
343  * reduce the number of (d)indirect blocks a lot.
344  *
345  * With N blocks per page and P pages, for each inode we have at most:
346  * N*P indirect
347  * min(N*P, blocksize/4 + 1) dindirect blocks
348  * niocount tindirect
349  *
350  * For the entire filesystem, we have at most:
351  * min(sum(nindir + P), ngroups) bitmap blocks (from the above)
352  * min(sum(nindir + P), gdblocks) group descriptor blocks (from the above)
353  * objcount inode blocks
354  * 1 superblock
355  * 2 * EXT3_SINGLEDATA_TRANS_BLOCKS for the quota files
356  *
357  * 1 EXT3_DATA_TRANS_BLOCKS for the last_rcvd update.
358  */
359 static int fsfilt_ext3_credits_needed(int objcount, struct fsfilt_objinfo *fso,
360                                       int niocount, struct niobuf_local *nb)
361 {
362         struct super_block *sb = fso->fso_dentry->d_inode->i_sb;
363         __u64 next_indir;
364         const int blockpp = 1 << (CFS_PAGE_SHIFT - sb->s_blocksize_bits);
365         int nbitmaps = 0, ngdblocks;
366         int needed = objcount + 1; /* inodes + superblock */
367         int i, j;
368
369         for (i = 0, j = 0; i < objcount; i++, fso++) {
370                 /* two or more dindirect blocks in case we cross boundary */
371                 int ndind = (long)((nb[j + fso->fso_bufcnt - 1].offset -
372                                     nb[j].offset) >>
373                                    sb->s_blocksize_bits) /
374                         (EXT3_ADDR_PER_BLOCK(sb) * EXT3_ADDR_PER_BLOCK(sb));
375                 nbitmaps += min(fso->fso_bufcnt, ndind > 0 ? ndind : 2);
376
377                 /* leaf, indirect, tindirect blocks for first block */
378                 nbitmaps += blockpp + 2;
379
380                 j += fso->fso_bufcnt;
381         }
382
383         next_indir = nb[0].offset +
384                 (EXT3_ADDR_PER_BLOCK(sb) << sb->s_blocksize_bits);
385         for (i = 1; i < niocount; i++) {
386                 if (nb[i].offset >= next_indir) {
387                         nbitmaps++;     /* additional indirect */
388                         next_indir = nb[i].offset +
389                                 (EXT3_ADDR_PER_BLOCK(sb)<<sb->s_blocksize_bits);
390                 } else if (nb[i].offset != nb[i - 1].offset + sb->s_blocksize) {
391                         nbitmaps++;     /* additional indirect */
392                 }
393                 nbitmaps += blockpp;    /* each leaf in different group? */
394         }
395
396         ngdblocks = nbitmaps;
397         if (nbitmaps > EXT3_SB(sb)->s_groups_count)
398                 nbitmaps = EXT3_SB(sb)->s_groups_count;
399         if (ngdblocks > EXT3_SB(sb)->s_gdb_count)
400                 ngdblocks = EXT3_SB(sb)->s_gdb_count;
401
402         needed += nbitmaps + ngdblocks;
403
404         /* last_rcvd update */
405         needed += FSFILT_DATA_TRANS_BLOCKS(sb);
406
407 #if defined(CONFIG_QUOTA)
408         /* We assume that there will be 1 bit set in s_dquot.flags for each
409          * quota file that is active.  This is at least true for now.
410          */
411         needed += hweight32(sb_any_quota_enabled(sb)) *
412                 FSFILT_SINGLEDATA_TRANS_BLOCKS(sb);
413 #endif
414
415         return needed;
416 }
417
418 /* We have to start a huge journal transaction here to hold all of the
419  * metadata for the pages being written here.  This is necessitated by
420  * the fact that we do lots of prepare_write operations before we do
421  * any of the matching commit_write operations, so even if we split
422  * up to use "smaller" transactions none of them could complete until
423  * all of them were opened.  By having a single journal transaction,
424  * we eliminate duplicate reservations for common blocks like the
425  * superblock and group descriptors or bitmaps.
426  *
427  * We will start the transaction here, but each prepare_write will
428  * add a refcount to the transaction, and each commit_write will
429  * remove a refcount.  The transaction will be closed when all of
430  * the pages have been written.
431  */
432 static void *fsfilt_ext3_brw_start(int objcount, struct fsfilt_objinfo *fso,
433                                    int niocount, struct niobuf_local *nb,
434                                    void *desc_private, int logs)
435 {
436         journal_t *journal;
437         handle_t *handle;
438         int needed;
439         ENTRY;
440
441         LASSERT(current->journal_info == desc_private);
442         journal = EXT3_SB(fso->fso_dentry->d_inode->i_sb)->s_journal;
443         needed = fsfilt_ext3_credits_needed(objcount, fso, niocount, nb);
444
445         /* The number of blocks we could _possibly_ dirty can very large.
446          * We reduce our request if it is absurd (and we couldn't get that
447          * many credits for a single handle anyways).
448          *
449          * At some point we have to limit the size of I/Os sent at one time,
450          * increase the size of the journal, or we have to calculate the
451          * actual journal requirements more carefully by checking all of
452          * the blocks instead of being maximally pessimistic.  It remains to
453          * be seen if this is a real problem or not.
454          */
455         if (needed > journal->j_max_transaction_buffers) {
456                 CERROR("want too many journal credits (%d) using %d instead\n",
457                        needed, journal->j_max_transaction_buffers);
458                 needed = journal->j_max_transaction_buffers;
459         }
460
461         LASSERTF(needed > 0, "can't start %d credit transaction\n", needed);
462         handle = ext3_journal_start(fso->fso_dentry->d_inode, needed);
463         if (IS_ERR(handle)) {
464                 CERROR("can't get handle for %d credits: rc = %ld\n", needed,
465                        PTR_ERR(handle));
466         } else {
467                 LASSERT(handle->h_buffer_credits >= needed);
468                 LASSERT(current->journal_info == handle);
469         }
470
471         RETURN(handle);
472 }
473
474 static int fsfilt_ext3_extend(struct inode *inode, unsigned int nblocks,void *h)
475 {
476        handle_t *handle = h;
477
478        /* fsfilt_extend called with nblocks = 0 for testing in special cases */
479        if (nblocks == 0) {
480                handle->h_buffer_credits = 0;
481                CWARN("setting credits of handle %p to zero by request\n", h);
482        }
483
484        if (handle->h_buffer_credits > nblocks)
485                 return 0;
486        if (ext3_journal_extend(handle, nblocks) == 0)
487                 return 0;
488
489        ext3_mark_inode_dirty(handle, inode);
490        return ext3_journal_restart(handle, nblocks);
491 }
492
493 static int fsfilt_ext3_commit(struct inode *inode, void *h, int force_sync)
494 {
495         int rc;
496         handle_t *handle = h;
497
498         LASSERT(current->journal_info == handle);
499         if (force_sync)
500                 handle->h_sync = 1; /* recovery likes this */
501
502         rc = ext3_journal_stop(handle);
503
504         return rc;
505 }
506
507 static int fsfilt_ext3_commit_async(struct inode *inode, void *h,
508                                     void **wait_handle)
509 {
510         unsigned long tid;
511         transaction_t *transaction;
512         handle_t *handle = h;
513         journal_t *journal;
514         int rc;
515
516         LASSERT(current->journal_info == handle);
517
518         transaction = handle->h_transaction;
519         journal = transaction->t_journal;
520         tid = transaction->t_tid;
521         /* we don't want to be blocked */
522         handle->h_sync = 0;
523         rc = ext3_journal_stop(handle);
524         if (rc) {
525                 CERROR("error while stopping transaction: %d\n", rc);
526                 return rc;
527         }
528         fsfilt_log_start_commit(journal, tid);
529
530         *wait_handle = (void *) tid;
531         CDEBUG(D_INODE, "commit async: %lu\n", (unsigned long) tid);
532         return 0;
533 }
534
535 static int fsfilt_ext3_commit_wait(struct inode *inode, void *h)
536 {
537         journal_t *journal = EXT3_JOURNAL(inode);
538         tid_t tid = (tid_t)(long)h;
539
540         CDEBUG(D_INODE, "commit wait: %lu\n", (unsigned long) tid);
541         if (unlikely(is_journal_aborted(journal)))
542                 return -EIO;
543
544         fsfilt_log_wait_commit(EXT3_JOURNAL(inode), tid);
545
546         if (unlikely(is_journal_aborted(journal)))
547                 return -EIO;
548         return 0;
549 }
550
551 static int fsfilt_ext3_setattr(struct dentry *dentry, void *handle,
552                                struct iattr *iattr, int do_trunc)
553 {
554         struct inode *inode = dentry->d_inode;
555         int rc = 0;
556
557         /* Avoid marking the inode dirty on the superblock list unnecessarily.
558          * We are already writing the inode to disk as part of this
559          * transaction and want to avoid a lot of extra inode writeout
560          * later on. b=9828 */
561         if (iattr->ia_valid & ATTR_SIZE && !do_trunc) {
562                 /* ATTR_SIZE would invoke truncate: clear it */
563                 iattr->ia_valid &= ~ATTR_SIZE;
564                 EXT3_I(inode)->i_disksize = iattr->ia_size;
565                 i_size_write(inode, iattr->ia_size);
566
567                 if (iattr->ia_valid & ATTR_UID)
568                         inode->i_uid = iattr->ia_uid;
569                 if (iattr->ia_valid & ATTR_GID)
570                         inode->i_gid = iattr->ia_gid;
571                 if (iattr->ia_valid & ATTR_ATIME)
572                         inode->i_atime = iattr->ia_atime;
573                 if (iattr->ia_valid & ATTR_MTIME)
574                         inode->i_mtime = iattr->ia_mtime;
575                 if (iattr->ia_valid & ATTR_CTIME)
576                         inode->i_ctime = iattr->ia_ctime;
577                 if (iattr->ia_valid & ATTR_MODE) {
578                         inode->i_mode = iattr->ia_mode;
579
580                         if (!in_group_p(inode->i_gid) &&
581                             !cfs_capable(CFS_CAP_FSETID))
582                                 inode->i_mode &= ~S_ISGID;
583                 }
584
585                 inode->i_sb->s_op->dirty_inode(inode);
586
587                 goto out;
588         }
589
590         /* Don't allow setattr to change file type */
591         if (iattr->ia_valid & ATTR_MODE)
592                 iattr->ia_mode = (inode->i_mode & S_IFMT) |
593                                  (iattr->ia_mode & ~S_IFMT);
594
595         /* We set these flags on the client, but have already checked perms
596          * so don't confuse inode_change_ok. */
597         iattr->ia_valid &= ~(ATTR_MTIME_SET | ATTR_ATIME_SET);
598
599         if (inode->i_op->setattr) {
600                 rc = inode->i_op->setattr(dentry, iattr);
601         } else {
602                 rc = inode_change_ok(inode, iattr);
603                 if (!rc)
604                         rc = inode_setattr(inode, iattr);
605         }
606
607  out:
608         RETURN(rc);
609 }
610
611 static int fsfilt_ext3_iocontrol(struct inode *inode, struct file *file,
612                                  unsigned int cmd, unsigned long arg)
613 {
614         int rc = 0;
615         ENTRY;
616
617         /* FIXME: Can't do this because of nested transaction deadlock */
618         if (cmd == EXT3_IOC_SETFLAGS && (*(int *)arg) & EXT3_JOURNAL_DATA_FL) {
619                 CERROR("can't set data journal flag on file\n");
620                 RETURN(-EPERM);
621         }
622
623 #ifdef HAVE_EXT4_LDISKFS
624         /* ext4_ioctl does not have a inode argument */
625         if (inode->i_fop->unlocked_ioctl)
626                 rc = inode->i_fop->unlocked_ioctl(file, cmd, arg);
627 #else
628         if (inode->i_fop->ioctl)
629                 rc = inode->i_fop->ioctl(inode, file, cmd, arg);
630 #endif
631         else
632                 RETURN(-ENOTTY);
633
634         RETURN(rc);
635 }
636
637 static int fsfilt_ext3_set_md(struct inode *inode, void *handle,
638                               void *lmm, int lmm_size, const char *name)
639 {
640         int rc;
641
642         LASSERT(TRYLOCK_INODE_MUTEX(inode) == 0);
643
644         rc = ext3_xattr_set_handle(handle, inode, EXT3_XATTR_INDEX_TRUSTED,
645                                    name, lmm, lmm_size, XATTR_NO_CTIME);
646
647
648         if (rc && rc != -EROFS)
649                 CERROR("error adding MD data to inode %lu: rc = %d\n",
650                        inode->i_ino, rc);
651         return rc;
652 }
653
654 /* Must be called with i_mutex held */
655 static int fsfilt_ext3_get_md(struct inode *inode, void *lmm, int lmm_size,
656                               const char *name)
657 {
658         int rc;
659
660         LASSERT(TRYLOCK_INODE_MUTEX(inode) == 0);
661
662         rc = ext3_xattr_get(inode, EXT3_XATTR_INDEX_TRUSTED,
663                             name, lmm, lmm_size);
664
665         /* This gives us the MD size */
666         if (lmm == NULL)
667                 return (rc == -ENODATA) ? 0 : rc;
668
669         if (rc < 0) {
670                 CDEBUG(D_INFO, "error getting EA %d/%s from inode %lu: rc %d\n",
671                        EXT3_XATTR_INDEX_TRUSTED, name,
672                        inode->i_ino, rc);
673                 memset(lmm, 0, lmm_size);
674                 return (rc == -ENODATA) ? 0 : rc;
675         }
676
677         return rc;
678 }
679
680 static int fsfilt_ext3_send_bio(int rw, struct inode *inode, struct bio *bio)
681 {
682         submit_bio(rw, bio);
683         return 0;
684 }
685
686 static ssize_t fsfilt_ext3_readpage(struct file *file, char *buf, size_t count,
687                                     loff_t *off)
688 {
689         struct inode *inode = file->f_dentry->d_inode;
690         int rc = 0;
691
692         if (S_ISREG(inode->i_mode))
693                 rc = file->f_op->read(file, buf, count, off);
694         else {
695                 const int blkbits = inode->i_sb->s_blocksize_bits;
696                 const int blksize = inode->i_sb->s_blocksize;
697
698                 CDEBUG(D_EXT2, "reading %lu at dir %lu+%llu\n",
699                        (unsigned long)count, inode->i_ino, *off);
700                 while (count > 0) {
701                         struct buffer_head *bh;
702
703                         bh = NULL;
704                         if (*off < i_size_read(inode)) {
705                                 int err = 0;
706
707                                 bh = ext3_bread(NULL, inode, *off >> blkbits,
708                                                 0, &err);
709
710                                 CDEBUG(D_EXT2, "read %u@%llu\n", blksize, *off);
711
712                                 if (bh) {
713                                         memcpy(buf, bh->b_data, blksize);
714                                         brelse(bh);
715                                 } else if (err) {
716                                         /* XXX in theory we should just fake
717                                          * this buffer and continue like ext3,
718                                          * especially if this is a partial read
719                                          */
720                                         CERROR("error read dir %lu+%llu: %d\n",
721                                                inode->i_ino, *off, err);
722                                         RETURN(err);
723                                 }
724                         }
725                         if (!bh) {
726                                 struct ext3_dir_entry_2 *fake = (void *)buf;
727
728                                 CDEBUG(D_EXT2, "fake %u@%llu\n", blksize, *off);
729                                 memset(fake, 0, sizeof(*fake));
730                                 fake->rec_len = cpu_to_le16(blksize);
731                         }
732                         count -= blksize;
733                         buf += blksize;
734                         *off += blksize;
735                         rc += blksize;
736                 }
737         }
738
739         return rc;
740 }
741
742 static void fsfilt_ext3_cb_func(struct journal_callback *jcb, int error)
743 {
744         struct fsfilt_cb_data *fcb = (struct fsfilt_cb_data *)jcb;
745
746         fcb->cb_func(fcb->cb_obd, fcb->cb_last_rcvd, fcb->cb_data, error);
747
748         OBD_SLAB_FREE(fcb, fcb_cache, sizeof *fcb);
749 }
750
751 static int fsfilt_ext3_add_journal_cb(struct obd_device *obd, __u64 last_rcvd,
752                                       void *handle, fsfilt_cb_t cb_func,
753                                       void *cb_data)
754 {
755         struct fsfilt_cb_data *fcb;
756
757         OBD_SLAB_ALLOC_PTR_GFP(fcb, fcb_cache, CFS_ALLOC_IO);
758         if (fcb == NULL)
759                 RETURN(-ENOMEM);
760
761         fcb->cb_func = cb_func;
762         fcb->cb_obd = obd;
763         fcb->cb_last_rcvd = last_rcvd;
764         fcb->cb_data = cb_data;
765
766         CDEBUG(D_EXT2, "set callback for last_rcvd: "LPD64"\n", last_rcvd);
767         fsfilt_journal_callback_set(handle, fsfilt_ext3_cb_func,
768                                     (struct journal_callback *)fcb);
769
770         return 0;
771 }
772
773 /*
774  * We need to hack the return value for the free inode counts because
775  * the current EA code requires one filesystem block per inode with EAs,
776  * so it is possible to run out of blocks before we run out of inodes.
777  *
778  * This can be removed when the ext3 EA code is fixed.
779  */
780 static int fsfilt_ext3_statfs(struct super_block *sb, struct obd_statfs *osfs)
781 {
782         struct kstatfs sfs;
783         int rc;
784
785         memset(&sfs, 0, sizeof(sfs));
786         rc = ll_do_statfs(sb, &sfs);
787         if (!rc && sfs.f_bfree < sfs.f_ffree) {
788                 sfs.f_files = (sfs.f_files - sfs.f_ffree) + sfs.f_bfree;
789                 sfs.f_ffree = sfs.f_bfree;
790         }
791
792         statfs_pack(osfs, &sfs);
793         return rc;
794 }
795
796 static int fsfilt_ext3_sync(struct super_block *sb)
797 {
798         return ext3_force_commit(sb);
799 }
800
801 #if defined(EXT3_MULTIBLOCK_ALLOCATOR) && (!defined(EXT3_EXT_CACHE_NO) || defined(EXT_CACHE_MARK))
802 #warning "kernel code has old extents/mballoc patch, disabling"
803 #undef EXT3_MULTIBLOCK_ALLOCATOR
804 #endif
805 #ifndef EXT3_EXTENTS_FL
806 #define EXT3_EXTENTS_FL                 0x00080000 /* Inode uses extents */
807 #endif
808
809 #ifdef EXT3_MULTIBLOCK_ALLOCATOR
810 #if (LINUX_VERSION_CODE < KERNEL_VERSION(2,6,17))
811 #define fsfilt_up_truncate_sem(inode)  up(&EXT3_I(inode)->truncate_sem);
812 #define fsfilt_down_truncate_sem(inode)  down(&EXT3_I(inode)->truncate_sem);
813 #else
814 #ifdef HAVE_EXT4_LDISKFS
815 #define fsfilt_up_truncate_sem(inode) up_write((&EXT4_I(inode)->i_data_sem));
816 #define fsfilt_down_truncate_sem(inode) down_write((&EXT4_I(inode)->i_data_sem));
817 #else
818 #define fsfilt_up_truncate_sem(inode)  mutex_unlock(&EXT3_I(inode)->truncate_mutex);
819 #define fsfilt_down_truncate_sem(inode)  mutex_lock(&EXT3_I(inode)->truncate_mutex);
820 #endif
821 #endif
822
823 #ifndef EXT_ASSERT
824 #define EXT_ASSERT(cond)  BUG_ON(!(cond))
825 #endif
826
827 #ifdef EXT3_EXT_HAS_NO_TREE
828 /* for kernels 2.6.18 and later */
829 #ifdef HAVE_EXT4_LDISKFS
830 #define EXT_GENERATION(inode)           (EXT4_I(inode)->i_ext_generation)
831 #else
832 #define EXT_GENERATION(inode)           ext_generation(inode)
833 #endif
834 #define ext3_ext_base                   inode
835 #define ext3_ext_base2inode(inode)      (inode)
836 #define EXT_DEPTH(inode)                ext_depth(inode)
837 #define fsfilt_ext3_ext_walk_space(inode, block, num, cb, cbdata) \
838                         ext3_ext_walk_space(inode, block, num, cb, cbdata);
839 #else
840 #define ext3_ext_base                   ext3_extents_tree
841 #define ext3_ext_base2inode(tree)       (tree->inode)
842 #define fsfilt_ext3_ext_walk_space(tree, block, num, cb, cbdata) \
843                         ext3_ext_walk_space(tree, block, num, cb);
844 #endif
845
846 #include <linux/lustre_version.h>
847
848 struct bpointers {
849         unsigned long *blocks;
850         int *created;
851         unsigned long start;
852         int num;
853         int init_num;
854         int create;
855 };
856
857 static long ext3_ext_find_goal(struct inode *inode, struct ext3_ext_path *path,
858                                unsigned long block, int *aflags)
859 {
860         struct ext3_inode_info *ei = EXT3_I(inode);
861         unsigned long bg_start;
862         unsigned long colour;
863         int depth;
864
865         if (path) {
866                 struct ext3_extent *ex;
867                 depth = path->p_depth;
868
869                 /* try to predict block placement */
870                 if ((ex = path[depth].p_ext))
871                         return ext_pblock(ex) + (block - le32_to_cpu(ex->ee_block));
872
873                 /* it looks index is empty
874                  * try to find starting from index itself */
875                 if (path[depth].p_bh)
876                         return path[depth].p_bh->b_blocknr;
877         }
878
879         /* OK. use inode's group */
880         bg_start = (ei->i_block_group * EXT3_BLOCKS_PER_GROUP(inode->i_sb)) +
881                 le32_to_cpu(EXT3_SB(inode->i_sb)->s_es->s_first_data_block);
882         colour = (current->pid % 16) *
883                 (EXT3_BLOCKS_PER_GROUP(inode->i_sb) / 16);
884         return bg_start + colour + block;
885 }
886
887 #define ll_unmap_underlying_metadata(sb, blocknr) \
888         unmap_underlying_metadata((sb)->s_bdev, blocknr)
889
890 #ifndef EXT3_MB_HINT_GROUP_ALLOC
891 static unsigned long new_blocks(handle_t *handle, struct ext3_ext_base *base,
892                                 struct ext3_ext_path *path, unsigned long block,
893                                 unsigned long *count, int *err)
894 {
895         unsigned long pblock, goal;
896         int aflags = 0;
897         struct inode *inode = ext3_ext_base2inode(base);
898
899         goal = ext3_ext_find_goal(inode, path, block, &aflags);
900         aflags |= 2; /* block have been already reserved */
901         pblock = ext3_mb_new_blocks(handle, inode, goal, count, aflags, err);
902         return pblock;
903
904 }
905 #else
906 static unsigned long new_blocks(handle_t *handle, struct ext3_ext_base *base,
907                                 struct ext3_ext_path *path, unsigned long block,
908                                 unsigned long *count, int *err)
909 {
910         struct inode *inode = ext3_ext_base2inode(base);
911         struct ext3_allocation_request ar;
912         unsigned long pblock;
913         int aflags;
914
915         /* find neighbour allocated blocks */
916         ar.lleft = block;
917         *err = ext3_ext_search_left(base, path, &ar.lleft, &ar.pleft);
918         if (*err)
919                 return 0;
920         ar.lright = block;
921         *err = ext3_ext_search_right(base, path, &ar.lright, &ar.pright);
922         if (*err)
923                 return 0;
924
925         /* allocate new block */
926         ar.goal = ext3_ext_find_goal(inode, path, block, &aflags);
927         ar.inode = inode;
928         ar.logical = block;
929         ar.len = *count;
930         ar.flags = EXT3_MB_HINT_DATA;
931         pblock = ext3_mb_new_blocks(handle, &ar, err);
932         *count = ar.len;
933         return pblock;
934 }
935 #endif
936
937 #ifdef EXT3_EXT_HAS_NO_TREE
938 static int ext3_ext_new_extent_cb(struct ext3_ext_base *base,
939                                   struct ext3_ext_path *path,
940                                   struct ext3_ext_cache *cex,
941 #ifdef HAVE_EXT_PREPARE_CB_EXTENT
942                                    struct ext3_extent *ex,
943 #endif
944                                   void *cbdata)
945 {
946         struct bpointers *bp = cbdata;
947 #else
948 static int ext3_ext_new_extent_cb(struct ext3_ext_base *base,
949                                   struct ext3_ext_path *path,
950                                   struct ext3_ext_cache *cex
951 #ifdef HAVE_EXT_PREPARE_CB_EXTENT
952                                   , struct ext3_extent *ex
953 #endif
954                                  )
955 {
956         struct bpointers *bp = base->private;
957 #endif
958         struct inode *inode = ext3_ext_base2inode(base);
959         struct ext3_extent nex;
960         unsigned long pblock;
961         unsigned long tgen;
962         int err, i;
963         unsigned long count;
964         handle_t *handle;
965
966         i = EXT_DEPTH(base);
967         EXT_ASSERT(i == path->p_depth);
968         EXT_ASSERT(path[i].p_hdr);
969
970         if (cex->ec_type == EXT3_EXT_CACHE_EXTENT) {
971                 err = EXT_CONTINUE;
972                 goto map;
973         }
974
975         if (bp->create == 0) {
976                 i = 0;
977                 if (cex->ec_block < bp->start)
978                         i = bp->start - cex->ec_block;
979                 if (i >= cex->ec_len)
980                         CERROR("nothing to do?! i = %d, e_num = %u\n",
981                                         i, cex->ec_len);
982                 for (; i < cex->ec_len && bp->num; i++) {
983                         *(bp->created) = 0;
984                         bp->created++;
985                         *(bp->blocks) = 0;
986                         bp->blocks++;
987                         bp->num--;
988                         bp->start++;
989                 }
990
991                 return EXT_CONTINUE;
992         }
993
994         tgen = EXT_GENERATION(base);
995         count = ext3_ext_calc_credits_for_insert(base, path);
996         fsfilt_up_truncate_sem(inode);
997
998         handle = ext3_journal_start(inode, count+EXT3_ALLOC_NEEDED+1);
999         if (IS_ERR(handle)) {
1000                 fsfilt_down_truncate_sem(inode);
1001                 return PTR_ERR(handle);
1002         }
1003
1004         fsfilt_down_truncate_sem(inode);
1005         if (tgen != EXT_GENERATION(base)) {
1006                 /* the tree has changed. so path can be invalid at moment */
1007                 ext3_journal_stop(handle);
1008                 return EXT_REPEAT;
1009         }
1010
1011         count = cex->ec_len;
1012         pblock = new_blocks(handle, base, path, cex->ec_block, &count, &err);
1013         if (!pblock)
1014                 goto out;
1015         EXT_ASSERT(count <= cex->ec_len);
1016
1017         /* insert new extent */
1018         nex.ee_block = cpu_to_le32(cex->ec_block);
1019         ext3_ext_store_pblock(&nex, pblock);
1020         nex.ee_len = cpu_to_le16(count);
1021         err = ext3_ext_insert_extent(handle, base, path, &nex);
1022         if (err) {
1023                 /* free data blocks we just allocated */
1024                 /* not a good idea to call discard here directly,
1025                  * but otherwise we'd need to call it every free() */
1026 #ifdef EXT3_MB_HINT_GROUP_ALLOC
1027                 ext3_mb_discard_inode_preallocations(inode);
1028 #endif
1029                 ext3_free_blocks(handle, inode, ext_pblock(&nex),
1030                                  cpu_to_le16(nex.ee_len), 0);
1031                 goto out;
1032         }
1033
1034         /*
1035          * Putting len of the actual extent we just inserted,
1036          * we are asking ext3_ext_walk_space() to continue
1037          * scaning after that block
1038          */
1039         cex->ec_len = le16_to_cpu(nex.ee_len);
1040         cex->ec_start = ext_pblock(&nex);
1041         BUG_ON(le16_to_cpu(nex.ee_len) == 0);
1042         BUG_ON(le32_to_cpu(nex.ee_block) != cex->ec_block);
1043
1044 out:
1045         ext3_journal_stop(handle);
1046 map:
1047         if (err >= 0) {
1048                 /* map blocks */
1049                 if (bp->num == 0) {
1050                         CERROR("hmm. why do we find this extent?\n");
1051                         CERROR("initial space: %lu:%u\n",
1052                                 bp->start, bp->init_num);
1053                         CERROR("current extent: %u/%u/%llu %d\n",
1054                                 cex->ec_block, cex->ec_len,
1055                                 (unsigned long long)cex->ec_start,
1056                                 cex->ec_type);
1057                 }
1058                 i = 0;
1059                 if (cex->ec_block < bp->start)
1060                         i = bp->start - cex->ec_block;
1061                 if (i >= cex->ec_len)
1062                         CERROR("nothing to do?! i = %d, e_num = %u\n",
1063                                         i, cex->ec_len);
1064                 for (; i < cex->ec_len && bp->num; i++) {
1065                         *(bp->blocks) = cex->ec_start + i;
1066                         if (cex->ec_type == EXT3_EXT_CACHE_EXTENT) {
1067                                 *(bp->created) = 0;
1068                         } else {
1069                                 *(bp->created) = 1;
1070                                 /* unmap any possible underlying metadata from
1071                                  * the block device mapping.  bug 6998. */
1072                                 ll_unmap_underlying_metadata(inode->i_sb,
1073                                                              *(bp->blocks));
1074                         }
1075                         bp->created++;
1076                         bp->blocks++;
1077                         bp->num--;
1078                         bp->start++;
1079                 }
1080         }
1081         return err;
1082 }
1083
1084 int fsfilt_map_nblocks(struct inode *inode, unsigned long block,
1085                        unsigned long num, unsigned long *blocks,
1086                        int *created, int create)
1087 {
1088 #ifdef EXT3_EXT_HAS_NO_TREE
1089         struct ext3_ext_base *base = inode;
1090 #else
1091         struct ext3_extents_tree tree;
1092         struct ext3_ext_base *base = &tree;
1093 #endif
1094         struct bpointers bp;
1095         int err;
1096
1097         CDEBUG(D_OTHER, "blocks %lu-%lu requested for inode %u\n",
1098                block, block + num - 1, (unsigned) inode->i_ino);
1099
1100 #ifndef EXT3_EXT_HAS_NO_TREE
1101         ext3_init_tree_desc(base, inode);
1102         tree.private = &bp;
1103 #endif
1104         bp.blocks = blocks;
1105         bp.created = created;
1106         bp.start = block;
1107         bp.init_num = bp.num = num;
1108         bp.create = create;
1109
1110         fsfilt_down_truncate_sem(inode);
1111         err = fsfilt_ext3_ext_walk_space(base, block, num,
1112                                          ext3_ext_new_extent_cb, &bp);
1113         ext3_ext_invalidate_cache(base);
1114         fsfilt_up_truncate_sem(inode);
1115
1116         return err;
1117 }
1118
1119 int fsfilt_ext3_map_ext_inode_pages(struct inode *inode, struct page **page,
1120                                     int pages, unsigned long *blocks,
1121                                     int *created, int create)
1122 {
1123         int blocks_per_page = CFS_PAGE_SIZE >> inode->i_blkbits;
1124         int rc = 0, i = 0;
1125         struct page *fp = NULL;
1126         int clen = 0;
1127
1128         CDEBUG(D_OTHER, "inode %lu: map %d pages from %lu\n",
1129                 inode->i_ino, pages, (*page)->index);
1130
1131         /* pages are sorted already. so, we just have to find
1132          * contig. space and process them properly */
1133         while (i < pages) {
1134                 if (fp == NULL) {
1135                         /* start new extent */
1136                         fp = *page++;
1137                         clen = 1;
1138                         i++;
1139                         continue;
1140                 } else if (fp->index + clen == (*page)->index) {
1141                         /* continue the extent */
1142                         page++;
1143                         clen++;
1144                         i++;
1145                         continue;
1146                 }
1147
1148                 /* process found extent */
1149                 rc = fsfilt_map_nblocks(inode, fp->index * blocks_per_page,
1150                                         clen * blocks_per_page, blocks,
1151                                         created, create);
1152                 if (rc)
1153                         GOTO(cleanup, rc);
1154
1155                 /* look for next extent */
1156                 fp = NULL;
1157                 blocks += blocks_per_page * clen;
1158                 created += blocks_per_page * clen;
1159         }
1160
1161         if (fp)
1162                 rc = fsfilt_map_nblocks(inode, fp->index * blocks_per_page,
1163                                         clen * blocks_per_page, blocks,
1164                                         created, create);
1165 cleanup:
1166         return rc;
1167 }
1168 #endif /* EXT3_MULTIBLOCK_ALLOCATOR */
1169
1170 extern int ext3_map_inode_page(struct inode *inode, struct page *page,
1171                                unsigned long *blocks, int *created, int create);
1172 int fsfilt_ext3_map_bm_inode_pages(struct inode *inode, struct page **page,
1173                                    int pages, unsigned long *blocks,
1174                                    int *created, int create)
1175 {
1176         int blocks_per_page = CFS_PAGE_SIZE >> inode->i_blkbits;
1177         unsigned long *b;
1178         int rc = 0, i, *cr;
1179
1180         for (i = 0, cr = created, b = blocks; i < pages; i++, page++) {
1181                 rc = ext3_map_inode_page(inode, *page, b, cr, create);
1182                 if (rc) {
1183                         CERROR("ino %lu, blk %lu cr %u create %d: rc %d\n",
1184                                inode->i_ino, *b, *cr, create, rc);
1185                         break;
1186                 }
1187
1188                 b += blocks_per_page;
1189                 cr += blocks_per_page;
1190         }
1191         return rc;
1192 }
1193
1194 int fsfilt_ext3_map_inode_pages(struct inode *inode, struct page **page,
1195                                 int pages, unsigned long *blocks,
1196                                 int *created, int create,
1197                                 struct semaphore *optional_sem)
1198 {
1199         int rc;
1200 #ifdef EXT3_MULTIBLOCK_ALLOCATOR
1201         if (EXT3_I(inode)->i_flags & EXT3_EXTENTS_FL) {
1202                 rc = fsfilt_ext3_map_ext_inode_pages(inode, page, pages,
1203                                                      blocks, created, create);
1204                 return rc;
1205         }
1206 #endif
1207         if (optional_sem != NULL)
1208                 down(optional_sem);
1209         rc = fsfilt_ext3_map_bm_inode_pages(inode, page, pages, blocks,
1210                                             created, create);
1211         if (optional_sem != NULL)
1212                 up(optional_sem);
1213
1214         return rc;
1215 }
1216
1217 int fsfilt_ext3_read(struct inode *inode, void *buf, int size, loff_t *offs)
1218 {
1219         unsigned long block;
1220         struct buffer_head *bh;
1221         int err, blocksize, csize, boffs, osize = size;
1222
1223         /* prevent reading after eof */
1224         lock_kernel();
1225         if (i_size_read(inode) < *offs + size) {
1226                 size = i_size_read(inode) - *offs;
1227                 unlock_kernel();
1228                 if (size < 0) {
1229                         CERROR("size %llu is too short for read %u@%llu\n",
1230                                i_size_read(inode), size, *offs);
1231                         return -EIO;
1232                 } else if (size == 0) {
1233                         return 0;
1234                 }
1235         } else {
1236                 unlock_kernel();
1237         }
1238
1239         blocksize = 1 << inode->i_blkbits;
1240
1241         while (size > 0) {
1242                 block = *offs >> inode->i_blkbits;
1243                 boffs = *offs & (blocksize - 1);
1244                 csize = min(blocksize - boffs, size);
1245                 bh = ext3_bread(NULL, inode, block, 0, &err);
1246                 if (!bh) {
1247                         CERROR("can't read block: %d\n", err);
1248                         return err;
1249                 }
1250
1251                 memcpy(buf, bh->b_data + boffs, csize);
1252                 brelse(bh);
1253
1254                 *offs += csize;
1255                 buf += csize;
1256                 size -= csize;
1257         }
1258         return osize;
1259 }
1260 EXPORT_SYMBOL(fsfilt_ext3_read);
1261
1262 static int fsfilt_ext3_read_record(struct file * file, void *buf,
1263                                    int size, loff_t *offs)
1264 {
1265         int rc;
1266         rc = fsfilt_ext3_read(file->f_dentry->d_inode, buf, size, offs);
1267         if (rc > 0)
1268                 rc = 0;
1269         return rc;
1270 }
1271
1272 int fsfilt_ext3_write_handle(struct inode *inode, void *buf, int bufsize,
1273                                 loff_t *offs, handle_t *handle)
1274 {
1275         struct buffer_head *bh = NULL;
1276         loff_t old_size = i_size_read(inode), offset = *offs;
1277         loff_t new_size = i_size_read(inode);
1278         unsigned long block;
1279         int err = 0, blocksize = 1 << inode->i_blkbits, size, boffs;
1280
1281         while (bufsize > 0) {
1282                 if (bh != NULL)
1283                         brelse(bh);
1284
1285                 block = offset >> inode->i_blkbits;
1286                 boffs = offset & (blocksize - 1);
1287                 size = min(blocksize - boffs, bufsize);
1288                 bh = ext3_bread(handle, inode, block, 1, &err);
1289                 if (!bh) {
1290                         CERROR("can't read/create block: %d\n", err);
1291                         break;
1292                 }
1293
1294                 err = ext3_journal_get_write_access(handle, bh);
1295                 if (err) {
1296                         CERROR("journal_get_write_access() returned error %d\n",
1297                                err);
1298                         break;
1299                 }
1300                 LASSERT(bh->b_data + boffs + size <= bh->b_data + bh->b_size);
1301                 memcpy(bh->b_data + boffs, buf, size);
1302                 err = ext3_journal_dirty_metadata(handle, bh);
1303                 if (err) {
1304                         CERROR("journal_dirty_metadata() returned error %d\n",
1305                                err);
1306                         break;
1307                 }
1308                 if (offset + size > new_size)
1309                         new_size = offset + size;
1310                 offset += size;
1311                 bufsize -= size;
1312                 buf += size;
1313         }
1314         if (bh)
1315                 brelse(bh);
1316
1317         /* correct in-core and on-disk sizes */
1318         if (new_size > i_size_read(inode)) {
1319                 lock_kernel();
1320                 if (new_size > i_size_read(inode))
1321                         i_size_write(inode, new_size);
1322                 if (i_size_read(inode) > EXT3_I(inode)->i_disksize)
1323                         EXT3_I(inode)->i_disksize = i_size_read(inode);
1324                 if (i_size_read(inode) > old_size)
1325                         mark_inode_dirty(inode);
1326                 unlock_kernel();
1327         }
1328
1329         if (err == 0)
1330                 *offs = offset;
1331         return err;
1332 }
1333 EXPORT_SYMBOL(fsfilt_ext3_write_handle);
1334
1335 static int fsfilt_ext3_write_record(struct file *file, void *buf, int bufsize,
1336                                     loff_t *offs, int force_sync)
1337 {
1338         struct inode *inode = file->f_dentry->d_inode;
1339         handle_t *handle;
1340         int err, block_count = 0, blocksize;
1341
1342         /* Determine how many transaction credits are needed */
1343         blocksize = 1 << inode->i_blkbits;
1344         block_count = (*offs & (blocksize - 1)) + bufsize;
1345         block_count = (block_count + blocksize - 1) >> inode->i_blkbits;
1346
1347         handle = ext3_journal_start(inode,
1348                                block_count * FSFILT_DATA_TRANS_BLOCKS(inode->i_sb) + 2);
1349         if (IS_ERR(handle)) {
1350                 CERROR("can't start transaction for %d blocks (%d bytes)\n",
1351                        block_count * FSFILT_DATA_TRANS_BLOCKS(inode->i_sb) + 2, bufsize);
1352                 return PTR_ERR(handle);
1353         }
1354
1355         err = fsfilt_ext3_write_handle(inode, buf, bufsize, offs, handle);
1356
1357         if (!err && force_sync)
1358                 handle->h_sync = 1; /* recovery likes this */
1359
1360         ext3_journal_stop(handle);
1361
1362         return err;
1363 }
1364
1365 static int fsfilt_ext3_setup(struct super_block *sb)
1366 {
1367 #if ((LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,6)) && \
1368      defined(HAVE_QUOTA_SUPPORT)) || defined(S_PDIROPS)
1369         struct ext3_sb_info *sbi = EXT3_SB(sb);
1370 #if 0
1371         sbi->dx_lock = fsfilt_ext3_dx_lock;
1372         sbi->dx_unlock = fsfilt_ext3_dx_unlock;
1373 #endif
1374 #endif
1375 #ifdef S_PDIROPS
1376         CWARN("Enabling PDIROPS\n");
1377         set_opt(sbi->s_mount_opt, PDIROPS);
1378         sb->s_flags |= S_PDIROPS;
1379 #endif
1380         if (!EXT3_HAS_COMPAT_FEATURE(sb, EXT3_FEATURE_COMPAT_DIR_INDEX))
1381                 CWARN("filesystem doesn't have dir_index feature enabled\n");
1382 #if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,6)) && defined(HAVE_QUOTA_SUPPORT)
1383         /* enable journaled quota support */
1384         /* kfreed in ext3_put_super() */
1385         sbi->s_qf_names[USRQUOTA] = kstrdup("lquota.user.reserved", GFP_KERNEL);
1386         if (!sbi->s_qf_names[USRQUOTA])
1387                 return -ENOMEM;
1388         sbi->s_qf_names[GRPQUOTA] = kstrdup("lquota.group.reserved", GFP_KERNEL);
1389         if (!sbi->s_qf_names[GRPQUOTA]) {
1390                 kfree(sbi->s_qf_names[USRQUOTA]);
1391                 sbi->s_qf_names[USRQUOTA] = NULL;
1392                 return -ENOMEM;
1393         }
1394         sbi->s_jquota_fmt = QFMT_VFS_V0;
1395 #if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,13))
1396         set_opt(sbi->s_mount_opt, QUOTA);
1397 #endif
1398 #endif
1399         return 0;
1400 }
1401
1402 /* If fso is NULL, op is FSFILT operation, otherwise op is number of fso
1403    objects. Logs is number of logfiles to update */
1404 static int fsfilt_ext3_get_op_len(int op, struct fsfilt_objinfo *fso, int logs)
1405 {
1406         if ( !fso ) {
1407                 switch(op) {
1408                 case FSFILT_OP_CREATE:
1409                                  /* directory leaf, index & indirect & EA*/
1410                         return 4 + 3 * logs;
1411                 case FSFILT_OP_UNLINK:
1412                         return 3 * logs;
1413                 }
1414         } else {
1415                 int i;
1416                 int needed = 0;
1417                 struct super_block *sb = fso->fso_dentry->d_inode->i_sb;
1418                 int blockpp = 1 << (CFS_PAGE_SHIFT - sb->s_blocksize_bits);
1419                 int addrpp = EXT3_ADDR_PER_BLOCK(sb) * blockpp;
1420                 for (i = 0; i < op; i++, fso++) {
1421                         int nblocks = fso->fso_bufcnt * blockpp;
1422                         int ndindirect = min(nblocks, addrpp + 1);
1423                         int nindir = nblocks + ndindirect + 1;
1424
1425                         needed += nindir;
1426                 }
1427                 return needed + 3 * logs;
1428         }
1429
1430         return 0;
1431 }
1432
1433 #ifdef HAVE_QUOTA_SUPPORT
1434 #define DQINFO_COPY(out, in)                    \
1435 do {                                            \
1436         Q_COPY(out, in, dqi_bgrace);            \
1437         Q_COPY(out, in, dqi_igrace);            \
1438         Q_COPY(out, in, dqi_flags);             \
1439         Q_COPY(out, in, dqi_valid);             \
1440 } while (0)
1441
1442 #define DQBLK_COPY(out, in)                     \
1443 do {                                            \
1444         Q_COPY(out, in, dqb_bhardlimit);        \
1445         Q_COPY(out, in, dqb_bsoftlimit);        \
1446         Q_COPY(out, in, dqb_curspace);          \
1447         Q_COPY(out, in, dqb_ihardlimit);        \
1448         Q_COPY(out, in, dqb_isoftlimit);        \
1449         Q_COPY(out, in, dqb_curinodes);         \
1450         Q_COPY(out, in, dqb_btime);             \
1451         Q_COPY(out, in, dqb_itime);             \
1452         Q_COPY(out, in, dqb_valid);             \
1453 } while (0)
1454
1455 static int fsfilt_ext3_quotactl(struct super_block *sb,
1456                                 struct obd_quotactl *oqc)
1457 {
1458         int i, rc = 0, error = 0;
1459         struct quotactl_ops *qcop;
1460         struct if_dqinfo *info;
1461         struct if_dqblk *dqblk;
1462         ENTRY;
1463
1464         if (!sb->s_qcop)
1465                 RETURN(-ENOSYS);
1466
1467         OBD_ALLOC_PTR(info);
1468         if (!info)
1469                 RETURN(-ENOMEM);
1470         OBD_ALLOC_PTR(dqblk);
1471         if (!dqblk) {
1472                 OBD_FREE_PTR(info);
1473                 RETURN(-ENOMEM);
1474         }
1475
1476         DQINFO_COPY(info, &oqc->qc_dqinfo);
1477         DQBLK_COPY(dqblk, &oqc->qc_dqblk);
1478
1479         qcop = sb->s_qcop;
1480         if (oqc->qc_cmd == Q_QUOTAON || oqc->qc_cmd == Q_QUOTAOFF) {
1481                 for (i = 0; i < MAXQUOTAS; i++) {
1482                         if (!Q_TYPESET(oqc, i))
1483                                 continue;
1484
1485                         if (oqc->qc_cmd == Q_QUOTAON) {
1486                                 char *name[MAXQUOTAS] = LUSTRE_OPQFILES_NAMES_V2;
1487
1488                                 LASSERT(oqc->qc_id == LUSTRE_QUOTA_V2);
1489
1490                                 if (!qcop->quota_on)
1491                                         GOTO(out, rc = -ENOSYS);
1492
1493                                 rc = qcop->quota_on(sb, i, QFMT_VFS_V0,
1494                                                     name[i]);
1495                         } else if (oqc->qc_cmd == Q_QUOTAOFF) {
1496                                 if (!qcop->quota_off)
1497                                         GOTO(out, rc = -ENOSYS);
1498                                 rc = qcop->quota_off(sb, i);
1499                         }
1500
1501                         if (rc == -EBUSY)
1502                                 error = rc;
1503                         else if (rc)
1504                                 GOTO(out, rc);
1505                 }
1506                 GOTO(out, rc ?: error);
1507         }
1508
1509         switch (oqc->qc_cmd) {
1510         case Q_GETOINFO:
1511         case Q_GETINFO:
1512                 if (!qcop->get_info)
1513                         GOTO(out, rc = -ENOSYS);
1514                 rc = qcop->get_info(sb, oqc->qc_type, info);
1515                 break;
1516         case Q_SETQUOTA:
1517         case Q_INITQUOTA:
1518                 if (!qcop->set_dqblk)
1519                         GOTO(out, rc = -ENOSYS);
1520                 rc = qcop->set_dqblk(sb, oqc->qc_type, oqc->qc_id, dqblk);
1521                 break;
1522         case Q_GETOQUOTA:
1523         case Q_GETQUOTA:
1524                 if (!qcop->get_dqblk)
1525                         GOTO(out, rc = -ENOSYS);
1526                 rc = qcop->get_dqblk(sb, oqc->qc_type, oqc->qc_id, dqblk);
1527                 if (!rc)
1528                         dqblk->dqb_valid = QIF_LIMITS | QIF_USAGE;
1529                 break;
1530         case Q_SYNC:
1531                 if (!sb->s_qcop->quota_sync)
1532                         GOTO(out, rc = -ENOSYS);
1533                 qcop->quota_sync(sb, oqc->qc_type);
1534                 break;
1535         case Q_FINVALIDATE:
1536                 CDEBUG(D_WARNING, "invalidating operational quota files\n");
1537                 for (i = 0; i < MAXQUOTAS; i++) {
1538                         struct file *fp;
1539                         char *name[MAXQUOTAS] = LUSTRE_OPQFILES_NAMES_V2;
1540
1541                         LASSERT(oqc->qc_id == LUSTRE_QUOTA_V2);
1542
1543                         if (!Q_TYPESET(oqc, i))
1544                                 continue;
1545
1546                         fp = filp_open(name[i], O_CREAT | O_TRUNC | O_RDWR, 0644);
1547                         if (IS_ERR(fp)) {
1548                                 rc = PTR_ERR(fp);
1549                                 CERROR("error invalidating operational quota file"
1550                                        " %s (rc:%d)\n", name[i], rc);
1551                         } else {
1552                                 filp_close(fp, 0);
1553                         }
1554
1555                 }
1556                 break;
1557         default:
1558                 CERROR("unsupported quotactl command: %d\n", oqc->qc_cmd);
1559                 LBUG();
1560         }
1561 out:
1562         DQINFO_COPY(&oqc->qc_dqinfo, info);
1563         DQBLK_COPY(&oqc->qc_dqblk, dqblk);
1564
1565         OBD_FREE_PTR(info);
1566         OBD_FREE_PTR(dqblk);
1567
1568         if (rc)
1569                 CDEBUG(D_QUOTA, "quotactl command %#x, id %u, type %u "
1570                                 "failed: %d\n",
1571                        oqc->qc_cmd, oqc->qc_id, oqc->qc_type, rc);
1572         RETURN(rc);
1573 }
1574
1575 struct chk_dqblk{
1576         struct hlist_node       dqb_hash;        /** quotacheck hash */
1577         struct list_head        dqb_list;        /** in list also */
1578         qid_t                   dqb_id;          /** uid/gid */
1579         short                   dqb_type;        /** USRQUOTA/GRPQUOTA */
1580         qsize_t                 dqb_bhardlimit;  /** block hard limit */
1581         qsize_t                 dqb_bsoftlimit;  /** block soft limit */
1582         qsize_t                 dqb_curspace;    /** current space */
1583         qsize_t                 dqb_ihardlimit;  /** inode hard limit */
1584         qsize_t                 dqb_isoftlimit;  /** inode soft limit */
1585         qsize_t                 dqb_curinodes;   /** current inodes */
1586         __u64                   dqb_btime;       /** block grace time */
1587         __u64                   dqb_itime;       /** inode grace time */
1588         __u32                   dqb_valid;       /** flag for above fields */
1589 };
1590
1591 static inline unsigned int chkquot_hash(qid_t id, int type)
1592                                         __attribute__((__const__));
1593
1594 static inline unsigned int chkquot_hash(qid_t id, int type)
1595 {
1596         return (id * (MAXQUOTAS - type)) % NR_DQHASH;
1597 }
1598
1599 static inline struct chk_dqblk *
1600 find_chkquot(struct hlist_head *head, qid_t id, int type)
1601 {
1602         struct hlist_node *node;
1603         struct chk_dqblk *cdqb;
1604
1605         hlist_for_each(node, head) {
1606                 cdqb = hlist_entry(node, struct chk_dqblk, dqb_hash);
1607                 if (cdqb->dqb_id == id && cdqb->dqb_type == type)
1608                         return cdqb;
1609         }
1610
1611         return NULL;
1612 }
1613
1614 static struct chk_dqblk *alloc_chkquot(qid_t id, int type)
1615 {
1616         struct chk_dqblk *cdqb;
1617
1618         OBD_ALLOC_PTR(cdqb);
1619         if (cdqb) {
1620                 INIT_HLIST_NODE(&cdqb->dqb_hash);
1621                 INIT_LIST_HEAD(&cdqb->dqb_list);
1622                 cdqb->dqb_id = id;
1623                 cdqb->dqb_type = type;
1624         }
1625
1626         return cdqb;
1627 }
1628
1629 static struct chk_dqblk *
1630 cqget(struct super_block *sb, struct hlist_head *hash, struct list_head *list,
1631       qid_t id, int type, int first_check)
1632 {
1633         struct hlist_head *head = hash + chkquot_hash(id, type);
1634         struct if_dqblk dqb;
1635         struct chk_dqblk *cdqb;
1636         int rc;
1637
1638         cdqb = find_chkquot(head, id, type);
1639         if (cdqb)
1640                 return cdqb;
1641
1642         cdqb = alloc_chkquot(id, type);
1643         if (!cdqb)
1644                 return NULL;
1645
1646         if (!first_check) {
1647                 rc = sb->s_qcop->get_dqblk(sb, type, id, &dqb);
1648                 if (rc) {
1649                         CERROR("get_dqblk of id %u, type %d failed: %d\n",
1650                                id, type, rc);
1651                 } else {
1652                         DQBLK_COPY(cdqb, &dqb);
1653                         cdqb->dqb_curspace = 0;
1654                         cdqb->dqb_curinodes = 0;
1655                 }
1656         }
1657
1658         hlist_add_head(&cdqb->dqb_hash, head);
1659         list_add_tail(&cdqb->dqb_list, list);
1660
1661         return cdqb;
1662 }
1663
1664 static inline int quota_onoff(struct super_block *sb, int cmd, int type, int qfmt)
1665 {
1666         struct obd_quotactl *oqctl;
1667         int rc;
1668
1669         OBD_ALLOC_PTR(oqctl);
1670         if (!oqctl)
1671                 RETURN(-ENOMEM);
1672
1673         oqctl->qc_cmd = cmd;
1674         oqctl->qc_id = qfmt;
1675         oqctl->qc_type = type;
1676         rc = fsfilt_ext3_quotactl(sb, oqctl);
1677
1678         OBD_FREE_PTR(oqctl);
1679         return rc;
1680 }
1681
1682 static inline int read_old_dqinfo(struct super_block *sb, int type,
1683                                   struct if_dqinfo *dqinfo)
1684 {
1685         struct obd_quotactl *oqctl;
1686         int rc;
1687         ENTRY;
1688
1689         OBD_ALLOC_PTR(oqctl);
1690         if (!oqctl)
1691                 RETURN(-ENOMEM);
1692
1693         oqctl->qc_cmd = Q_GETINFO;
1694         oqctl->qc_type = type;
1695         rc = fsfilt_ext3_quotactl(sb, oqctl);
1696         if (!rc)
1697                 ((struct obd_dqinfo *)dqinfo)[type] = oqctl->qc_dqinfo;
1698
1699         OBD_FREE_PTR(oqctl);
1700         RETURN(rc);
1701 }
1702
1703 static inline struct ext3_group_desc *
1704 get_group_desc(struct super_block *sb, int group)
1705 {
1706         unsigned long desc_block, desc;
1707         struct ext3_group_desc *gdp;
1708
1709         desc_block = group / EXT3_DESC_PER_BLOCK(sb);
1710         desc = group % EXT3_DESC_PER_BLOCK(sb);
1711         gdp = (struct ext3_group_desc *)
1712               EXT3_SB(sb)->s_group_desc[desc_block]->b_data;
1713
1714         return gdp + desc;
1715 }
1716
1717
1718 #ifndef HAVE_EXT4_LDISKFS
1719 static inline struct buffer_head *
1720 ext3_read_inode_bitmap(struct super_block *sb, unsigned long group)
1721 {
1722         struct ext3_group_desc *desc;
1723         struct buffer_head *bh;
1724
1725         desc = get_group_desc(sb, group);
1726         bh = sb_bread(sb, ext3_inode_bitmap(sb, desc));
1727         return bh;
1728 }
1729 #endif
1730
1731 static inline struct inode *ext3_iget_inuse(struct super_block *sb,
1732                                      struct buffer_head *bitmap_bh,
1733                                      int index, unsigned long ino)
1734 {
1735         struct inode *inode = NULL;
1736
1737
1738         if (ext3_test_bit(index, bitmap_bh->b_data))
1739 #ifdef HAVE_EXT4_LDISKFS
1740                 inode = ext4_iget(sb, ino);
1741                 if (IS_ERR(inode))
1742                 /* Newer kernels return an error instead of a NULL pointer */
1743                         inode = NULL;
1744 #else
1745                 inode = iget(sb, ino);
1746 #endif
1747         return inode;
1748 }
1749
1750 struct qchk_ctxt {
1751         struct hlist_head       qckt_hash[NR_DQHASH];        /* quotacheck hash */
1752         struct list_head        qckt_list;                   /* quotacheck list */
1753         int                     qckt_first_check[MAXQUOTAS]; /* 1 if no old quotafile */
1754         struct if_dqinfo        qckt_dqinfo[MAXQUOTAS];      /* old dqinfo */
1755 };
1756
1757 static int add_inode_quota(struct inode *inode, struct qchk_ctxt *qctxt,
1758                            struct obd_quotactl *oqc)
1759 {
1760         struct chk_dqblk *cdqb[MAXQUOTAS] = { NULL, };
1761         loff_t size = 0;
1762         qid_t qid[MAXQUOTAS];
1763         int cnt, i, rc = 0;
1764
1765         if (!inode)
1766                 return 0;
1767
1768         qid[USRQUOTA] = inode->i_uid;
1769         qid[GRPQUOTA] = inode->i_gid;
1770
1771         if (S_ISDIR(inode->i_mode) ||
1772             S_ISREG(inode->i_mode) ||
1773             S_ISLNK(inode->i_mode))
1774                 size = inode_get_bytes(inode);
1775
1776         for (cnt = 0; cnt < MAXQUOTAS; cnt++) {
1777                 if (!Q_TYPESET(oqc, cnt))
1778                         continue;
1779
1780                 cdqb[cnt] = cqget(inode->i_sb, qctxt->qckt_hash,
1781                                 &qctxt->qckt_list, qid[cnt], cnt,
1782                                 qctxt->qckt_first_check[cnt]);
1783                 if (!cdqb[cnt]) {
1784                         rc = -ENOMEM;
1785                         break;
1786                 }
1787
1788                 cdqb[cnt]->dqb_curspace += size;
1789                 cdqb[cnt]->dqb_curinodes++;
1790         }
1791
1792         if (rc) {
1793                 for (i = 0; i < cnt; i++) {
1794                         if (!Q_TYPESET(oqc, i))
1795                                 continue;
1796                         LASSERT(cdqb[i]);
1797                         cdqb[i]->dqb_curspace -= size;
1798                         cdqb[i]->dqb_curinodes--;
1799                 }
1800         }
1801
1802         return rc;
1803 }
1804
1805 /* write dqinfo struct in a new quota file */
1806 static int v3_write_dqinfo(struct file *f, int type, struct if_dqinfo *info)
1807 {
1808         struct v2_disk_dqinfo dqinfo;
1809         __u32 blocks = V2_DQTREEOFF + 1;
1810         loff_t offset = V2_DQINFOOFF;
1811
1812         if (info) {
1813                 dqinfo.dqi_bgrace = cpu_to_le32(info->dqi_bgrace);
1814                 dqinfo.dqi_igrace = cpu_to_le32(info->dqi_igrace);
1815                 dqinfo.dqi_flags = cpu_to_le32(info->dqi_flags & DQF_MASK &
1816                                                ~DQF_INFO_DIRTY);
1817         } else {
1818                 dqinfo.dqi_bgrace = cpu_to_le32(MAX_DQ_TIME);
1819                 dqinfo.dqi_igrace = cpu_to_le32(MAX_IQ_TIME);
1820                 dqinfo.dqi_flags = 0;
1821         }
1822
1823         dqinfo.dqi_blocks = cpu_to_le32(blocks);
1824         dqinfo.dqi_free_blk = 0;
1825         dqinfo.dqi_free_entry = 0;
1826
1827         return cfs_user_write(f, (char *)&dqinfo, sizeof(dqinfo), &offset);
1828 }
1829
1830 static int v3_write_dqheader(struct file *f, int type)
1831 {
1832         static const __u32 quota_magics[] = V2_INITQMAGICS;
1833         static const __u32 quota_versions[] = V2_INITQVERSIONS_R1;
1834         struct v2_disk_dqheader dqhead;
1835         loff_t offset = 0;
1836
1837         CLASSERT(ARRAY_SIZE(quota_magics) == ARRAY_SIZE(quota_versions));
1838         LASSERT(0 <= type && type < ARRAY_SIZE(quota_magics));
1839
1840         dqhead.dqh_magic = cpu_to_le32(quota_magics[type]);
1841         dqhead.dqh_version = cpu_to_le32(quota_versions[type]);
1842
1843         return cfs_user_write(f, (char *)&dqhead, sizeof(dqhead), &offset);
1844 }
1845
1846 static int create_new_quota_files(struct qchk_ctxt *qctxt,
1847                                   struct obd_quotactl *oqc)
1848 {
1849         int i, rc = 0;
1850         ENTRY;
1851
1852         for (i = 0; i < MAXQUOTAS; i++) {
1853                 struct if_dqinfo *info = qctxt->qckt_first_check[i]?
1854                                          NULL : &qctxt->qckt_dqinfo[i];
1855                 struct file *file;
1856                 const char *name[MAXQUOTAS] = LUSTRE_OPQFILES_NAMES_V2;
1857
1858                 if (!Q_TYPESET(oqc, i))
1859                         continue;
1860
1861                 LASSERT(oqc->qc_id == LUSTRE_QUOTA_V2);
1862
1863                 file = filp_open(name[i], O_RDWR | O_CREAT | O_TRUNC, 0644);
1864                 if (IS_ERR(file)) {
1865                         rc = PTR_ERR(file);
1866                         CERROR("can't create %s file: rc = %d\n",
1867                                name[i], rc);
1868                         GOTO(out, rc);
1869                 }
1870
1871                 if (!S_ISREG(file->f_dentry->d_inode->i_mode)) {
1872                         CERROR("file %s is not regular", name[i]);
1873                         filp_close(file, 0);
1874                         GOTO(out, rc = -EINVAL);
1875                 }
1876
1877                 DQUOT_DROP(file->f_dentry->d_inode);
1878
1879                 rc = v3_write_dqheader(file, i);
1880                 if (rc) {
1881                         filp_close(file, 0);
1882                         GOTO(out, rc);
1883                 }
1884
1885                 rc = v3_write_dqinfo(file, i, info);
1886                 filp_close(file, 0);
1887                 if (rc)
1888                         GOTO(out, rc);
1889         }
1890
1891 out:
1892         RETURN(rc);
1893 }
1894
1895
1896 static int commit_chkquot(struct super_block *sb, struct qchk_ctxt *qctxt,
1897                           struct chk_dqblk *cdqb)
1898 {
1899         struct obd_quotactl *oqc;
1900         long now;
1901         int rc;
1902         ENTRY;
1903
1904         OBD_ALLOC_PTR(oqc);
1905         if (!oqc)
1906                 RETURN(-ENOMEM);
1907
1908         now = cfs_time_current_sec();
1909
1910         if (cdqb->dqb_bsoftlimit &&
1911             toqb(cdqb->dqb_curspace) >= cdqb->dqb_bsoftlimit &&
1912             !cdqb->dqb_btime)
1913                 cdqb->dqb_btime =
1914                         now + qctxt->qckt_dqinfo[cdqb->dqb_type].dqi_bgrace;
1915
1916         if (cdqb->dqb_isoftlimit &&
1917             cdqb->dqb_curinodes >= cdqb->dqb_isoftlimit &&
1918             !cdqb->dqb_itime)
1919                 cdqb->dqb_itime =
1920                         now + qctxt->qckt_dqinfo[cdqb->dqb_type].dqi_igrace;
1921
1922         cdqb->dqb_valid = QIF_ALL;
1923
1924         oqc->qc_cmd = Q_SETQUOTA;
1925         oqc->qc_type = cdqb->dqb_type;
1926         oqc->qc_id = cdqb->dqb_id;
1927         DQBLK_COPY(&oqc->qc_dqblk, cdqb);
1928
1929         rc = fsfilt_ext3_quotactl(sb, oqc);
1930         OBD_FREE_PTR(oqc);
1931         RETURN(rc);
1932 }
1933
1934 static int prune_chkquots(struct super_block *sb,
1935                           struct qchk_ctxt *qctxt, int error)
1936 {
1937         struct chk_dqblk *cdqb, *tmp;
1938         int rc;
1939
1940         list_for_each_entry_safe(cdqb, tmp, &qctxt->qckt_list, dqb_list) {
1941                 if (!error) {
1942                         rc = commit_chkquot(sb, qctxt, cdqb);
1943                         if (rc)
1944                                 error = rc;
1945                 }
1946                 hlist_del_init(&cdqb->dqb_hash);
1947                 list_del(&cdqb->dqb_list);
1948                 OBD_FREE_PTR(cdqb);
1949         }
1950
1951         return error;
1952 }
1953
1954 static int fsfilt_ext3_quotacheck(struct super_block *sb,
1955                                   struct obd_quotactl *oqc)
1956 {
1957         struct ext3_sb_info *sbi = EXT3_SB(sb);
1958         int i, group;
1959         struct qchk_ctxt *qctxt;
1960         struct buffer_head *bitmap_bh = NULL;
1961         unsigned long ino;
1962         struct inode *inode;
1963         int rc = 0;
1964         ENTRY;
1965
1966         /* turn on quota and read dqinfo if existed */
1967         OBD_ALLOC_PTR(qctxt);
1968         if (!qctxt) {
1969                 oqc->qc_stat = -ENOMEM;
1970                 RETURN(-ENOMEM);
1971         }
1972
1973         for (i = 0; i < NR_DQHASH; i++)
1974                 INIT_HLIST_HEAD(&qctxt->qckt_hash[i]);
1975         INIT_LIST_HEAD(&qctxt->qckt_list);
1976
1977         for (i = 0; i < MAXQUOTAS; i++) {
1978                 if (!Q_TYPESET(oqc, i))
1979                         continue;
1980
1981                 rc = quota_onoff(sb, Q_QUOTAON, i, oqc->qc_id);
1982                 if (!rc || rc == -EBUSY) {
1983                         rc = read_old_dqinfo(sb, i, qctxt->qckt_dqinfo);
1984                         if (rc)
1985                                 GOTO(out, rc);
1986                 } else if (rc == -ENOENT || rc == -EINVAL || rc == -EEXIST) {
1987                         qctxt->qckt_first_check[i] = 1;
1988                 } else if (rc) {
1989                         GOTO(out, rc);
1990                 }
1991         }
1992
1993         /* check quota and update in hash */
1994         for (group = 0; group < sbi->s_groups_count; group++) {
1995                 struct ext3_group_desc *desc;
1996                 desc = get_group_desc(sb, group);
1997                 if (!desc)
1998                         GOTO(out, -EIO);
1999
2000                 spin_lock(sb_bgl_lock(sbi, group));
2001                 if (desc->bg_flags & cpu_to_le16(EXT3_BG_INODE_UNINIT)) {
2002                         /* no inode in use in this group, just skip it */
2003                         spin_unlock(sb_bgl_lock(sbi, group));
2004                         continue;
2005                 }
2006                 spin_unlock(sb_bgl_lock(sbi, group));
2007
2008                 ino = group * sbi->s_inodes_per_group + 1;
2009                 bitmap_bh = ext3_read_inode_bitmap(sb, group);
2010                 if (!bitmap_bh) {
2011                         CERROR("ext3_read_inode_bitmap group %d failed", group);
2012                         GOTO(out, rc = -EIO);
2013                 }
2014
2015                 for (i = 0; i < sbi->s_inodes_per_group; i++, ino++) {
2016                         if (ino < sbi->s_first_ino)
2017                                 continue;
2018
2019                         inode = ext3_iget_inuse(sb, bitmap_bh, i, ino);
2020                         rc = add_inode_quota(inode, qctxt, oqc);
2021                         iput(inode);
2022                         if (rc) {
2023                                 brelse(bitmap_bh);
2024                                 GOTO(out, rc);
2025                         }
2026                 }
2027
2028                 brelse(bitmap_bh);
2029         }
2030
2031         /* read old quota limits from old quota file. (only for the user
2032          * has limits but hasn't file) */
2033 #ifdef HAVE_QUOTA_SUPPORT
2034         for (i = 0; i < MAXQUOTAS; i++) {
2035                 struct list_head id_list;
2036                 struct dquot_id *dqid, *tmp;
2037
2038                 if (!Q_TYPESET(oqc, i))
2039                         continue;
2040
2041                 if (qctxt->qckt_first_check[i])
2042                         continue;
2043
2044
2045                 LASSERT(sb_dqopt(sb)->files[i] != NULL);
2046                 INIT_LIST_HEAD(&id_list);
2047 #ifndef KERNEL_SUPPORTS_QUOTA_READ
2048                 rc = lustre_get_qids(sb_dqopt(sb)->files[i], NULL, i, &id_list);
2049 #else
2050                 rc = lustre_get_qids(NULL, sb_dqopt(sb)->files[i], i, &id_list);
2051 #endif
2052                 if (rc)
2053                         CERROR("read old limits failed. (rc:%d)\n", rc);
2054
2055                 list_for_each_entry_safe(dqid, tmp, &id_list, di_link) {
2056                         list_del_init(&dqid->di_link);
2057
2058                         if (!rc)
2059                                 cqget(sb, qctxt->qckt_hash, &qctxt->qckt_list,
2060                                       dqid->di_id, i,
2061                                       qctxt->qckt_first_check[i]);
2062                         OBD_FREE_PTR(dqid);
2063                 }
2064         }
2065 #endif
2066         /* turn off quota cause we are to dump chk_dqblk to files */
2067         quota_onoff(sb, Q_QUOTAOFF, oqc->qc_type, oqc->qc_id);
2068
2069         rc = create_new_quota_files(qctxt, oqc);
2070         if (rc)
2071                 GOTO(out, rc);
2072
2073         /* we use vfs functions to set dqblk, so turn quota on */
2074         rc = quota_onoff(sb, Q_QUOTAON, oqc->qc_type, oqc->qc_id);
2075 out:
2076         /* dump and free chk_dqblk */
2077         rc = prune_chkquots(sb, qctxt, rc);
2078         OBD_FREE_PTR(qctxt);
2079
2080         /* turn off quota, `lfs quotacheck` will turn on when all
2081          * nodes quotacheck finish. */
2082         quota_onoff(sb, Q_QUOTAOFF, oqc->qc_type, oqc->qc_id);
2083
2084         oqc->qc_stat = rc;
2085         if (rc)
2086                 CERROR("quotacheck failed: rc = %d\n", rc);
2087
2088         RETURN(rc);
2089 }
2090
2091 static int fsfilt_ext3_quotainfo(struct lustre_quota_info *lqi, int type,
2092                                  int cmd)
2093 {
2094         int rc = 0;
2095         ENTRY;
2096
2097         if (lqi->qi_files[type] == NULL) {
2098                 CERROR("operate qinfo before it's enabled!\n");
2099                 RETURN(-ESRCH);
2100         }
2101
2102         switch (cmd) {
2103         case QFILE_CHK:
2104                 rc = lustre_check_quota_file(lqi, type);
2105                 break;
2106         case QFILE_RD_INFO:
2107                 rc = lustre_read_quota_info(lqi, type);
2108                 break;
2109         case QFILE_WR_INFO:
2110                 rc = lustre_write_quota_info(lqi, type);
2111                 break;
2112         case QFILE_INIT_INFO:
2113                 rc = lustre_init_quota_info(lqi, type);
2114                 break;
2115         case QFILE_CONVERT:
2116                 rc = -ENOTSUPP;
2117                 CERROR("quota CONVERT command is not supported\n");
2118                 break;
2119         default:
2120                 rc = -ENOTSUPP;
2121                 CERROR("Unsupported admin quota file cmd %d\n"
2122                        "Are lquota.ko and fsfilt_ldiskfs.ko modules in sync?\n",
2123                        cmd);
2124                 break;
2125         }
2126         RETURN(rc);
2127 }
2128
2129 static int fsfilt_ext3_qids(struct file *file, struct inode *inode, int type,
2130                             struct list_head *list)
2131 {
2132         return lustre_get_qids(file, inode, type, list);
2133 }
2134
2135 static int fsfilt_ext3_dquot(struct lustre_dquot *dquot, int cmd)
2136 {
2137         int rc = 0;
2138         ENTRY;
2139
2140         if (dquot->dq_info->qi_files[dquot->dq_type] == NULL) {
2141                 CERROR("operate dquot before it's enabled!\n");
2142                 RETURN(-ESRCH);
2143         }
2144
2145         switch (cmd) {
2146         case QFILE_RD_DQUOT:
2147                 rc = lustre_read_dquot(dquot);
2148                 break;
2149         case QFILE_WR_DQUOT:
2150                 if (dquot->dq_dqb.dqb_ihardlimit ||
2151                     dquot->dq_dqb.dqb_isoftlimit ||
2152                     dquot->dq_dqb.dqb_bhardlimit ||
2153                     dquot->dq_dqb.dqb_bsoftlimit)
2154                         clear_bit(DQ_FAKE_B, &dquot->dq_flags);
2155                 else
2156                         set_bit(DQ_FAKE_B, &dquot->dq_flags);
2157
2158                 rc = lustre_commit_dquot(dquot);
2159                 if (rc >= 0)
2160                         rc = 0;
2161                 break;
2162         default:
2163                 CERROR("Unsupported admin quota file cmd %d\n", cmd);
2164                 LBUG();
2165                 break;
2166         }
2167         RETURN(rc);
2168 }
2169
2170 static int fsfilt_ext3_get_mblk(struct super_block *sb, int *count,
2171                                 struct inode *inode, int frags)
2172 {
2173 #ifdef EXT3_EXT_HAS_NO_TREE
2174         struct ext3_ext_base *base = inode;
2175 #else
2176         struct ext3_extents_tree tree;
2177         struct ext3_ext_base *base = &tree;
2178
2179         ext3_init_tree_desc(base, inode);
2180 #endif
2181         /* for an ost_write request, it needs <#fragments> * <tree depth + 1>
2182          * metablocks at maxium b=16542 */
2183         *count = frags * (EXT_DEPTH(base) + 1) * EXT3_BLOCK_SIZE(sb);
2184         return 0;
2185 }
2186
2187 #endif
2188
2189 lvfs_sbdev_type fsfilt_ext3_journal_sbdev(struct super_block *sb)
2190 {
2191         return (EXT3_SB(sb)->journal_bdev);
2192 }
2193 EXPORT_SYMBOL(fsfilt_ext3_journal_sbdev);
2194
2195 static struct fsfilt_operations fsfilt_ext3_ops = {
2196         .fs_type                = "ext3",
2197         .fs_owner               = THIS_MODULE,
2198         .fs_getlabel            = fsfilt_ext3_get_label,
2199         .fs_setlabel            = fsfilt_ext3_set_label,
2200         .fs_uuid                = fsfilt_ext3_uuid,
2201         .fs_start               = fsfilt_ext3_start,
2202         .fs_brw_start           = fsfilt_ext3_brw_start,
2203         .fs_extend              = fsfilt_ext3_extend,
2204         .fs_commit              = fsfilt_ext3_commit,
2205         .fs_commit_async        = fsfilt_ext3_commit_async,
2206         .fs_commit_wait         = fsfilt_ext3_commit_wait,
2207         .fs_setattr             = fsfilt_ext3_setattr,
2208         .fs_iocontrol           = fsfilt_ext3_iocontrol,
2209         .fs_set_md              = fsfilt_ext3_set_md,
2210         .fs_get_md              = fsfilt_ext3_get_md,
2211         .fs_readpage            = fsfilt_ext3_readpage,
2212         .fs_add_journal_cb      = fsfilt_ext3_add_journal_cb,
2213         .fs_statfs              = fsfilt_ext3_statfs,
2214         .fs_sync                = fsfilt_ext3_sync,
2215         .fs_map_inode_pages     = fsfilt_ext3_map_inode_pages,
2216         .fs_write_record        = fsfilt_ext3_write_record,
2217         .fs_read_record         = fsfilt_ext3_read_record,
2218         .fs_setup               = fsfilt_ext3_setup,
2219         .fs_send_bio            = fsfilt_ext3_send_bio,
2220         .fs_get_op_len          = fsfilt_ext3_get_op_len,
2221 #ifdef HAVE_DISK_INODE_VERSION
2222         .fs_get_version         = fsfilt_ext3_get_version,
2223         .fs_set_version         = fsfilt_ext3_set_version,
2224 #endif
2225 #ifdef HAVE_QUOTA_SUPPORT
2226         .fs_quotactl            = fsfilt_ext3_quotactl,
2227         .fs_quotacheck          = fsfilt_ext3_quotacheck,
2228         .fs_quotainfo           = fsfilt_ext3_quotainfo,
2229         .fs_qids                = fsfilt_ext3_qids,
2230         .fs_dquot               = fsfilt_ext3_dquot,
2231         .fs_get_mblk            = fsfilt_ext3_get_mblk,
2232 #endif
2233         .fs_journal_sbdev       = fsfilt_ext3_journal_sbdev,
2234 };
2235
2236 static int __init fsfilt_ext3_init(void)
2237 {
2238         int rc;
2239
2240         fcb_cache = cfs_mem_cache_create("fsfilt_ext3_fcb",
2241                                          sizeof(struct fsfilt_cb_data), 0, 0);
2242         if (!fcb_cache) {
2243                 CERROR("error allocating fsfilt journal callback cache\n");
2244                 GOTO(out, rc = -ENOMEM);
2245         }
2246
2247         rc = fsfilt_register_ops(&fsfilt_ext3_ops);
2248
2249         if (rc) {
2250                 int err = cfs_mem_cache_destroy(fcb_cache);
2251                 LASSERTF(err == 0, "error destroying new cache: rc %d\n", err);
2252         }
2253 out:
2254         return rc;
2255 }
2256
2257 static void __exit fsfilt_ext3_exit(void)
2258 {
2259         int rc;
2260
2261         fsfilt_unregister_ops(&fsfilt_ext3_ops);
2262         rc = cfs_mem_cache_destroy(fcb_cache);
2263         LASSERTF(rc == 0, "couldn't destroy fcb_cache slab\n");
2264 }
2265
2266 module_init(fsfilt_ext3_init);
2267 module_exit(fsfilt_ext3_exit);
2268
2269 MODULE_AUTHOR("Sun Microsystems, Inc. <http://www.lustre.org/>");
2270 MODULE_DESCRIPTION("Lustre ext3 Filesystem Helper v0.1");
2271 MODULE_LICENSE("GPL");