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