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