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