GUI: Fix Tomato RAF theme for all builds. Compilation typo.
[tomato.git] / release / src-rt-6.x.4708 / linux / linux-2.6.36 / fs / ext4 / inode.c
blobc419beac9f3bdc46fa14271036c54a381139fbc0
1 /*
2 * linux/fs/ext4/inode.c
4 * Copyright (C) 1992, 1993, 1994, 1995
5 * Remy Card (card@masi.ibp.fr)
6 * Laboratoire MASI - Institut Blaise Pascal
7 * Universite Pierre et Marie Curie (Paris VI)
9 * from
11 * linux/fs/minix/inode.c
13 * Copyright (C) 1991, 1992 Linus Torvalds
15 * Goal-directed block allocation by Stephen Tweedie
16 * (sct@redhat.com), 1993, 1998
17 * Big-endian to little-endian byte-swapping/bitmaps by
18 * David S. Miller (davem@caip.rutgers.edu), 1995
19 * 64-bit file support on 64-bit platforms by Jakub Jelinek
20 * (jj@sunsite.ms.mff.cuni.cz)
22 * Assorted race fixes, rewrite of ext4_get_block() by Al Viro, 2000
25 #include <linux/module.h>
26 #include <linux/fs.h>
27 #include <linux/time.h>
28 #include <linux/jbd2.h>
29 #include <linux/highuid.h>
30 #include <linux/pagemap.h>
31 #include <linux/quotaops.h>
32 #include <linux/string.h>
33 #include <linux/buffer_head.h>
34 #include <linux/writeback.h>
35 #include <linux/pagevec.h>
36 #include <linux/mpage.h>
37 #include <linux/namei.h>
38 #include <linux/uio.h>
39 #include <linux/bio.h>
40 #include <linux/workqueue.h>
41 #include <linux/kernel.h>
42 #include <linux/slab.h>
44 #include "ext4_jbd2.h"
45 #include "xattr.h"
46 #include "acl.h"
47 #include "ext4_extents.h"
49 #include <trace/events/ext4.h>
51 #define MPAGE_DA_EXTENT_TAIL 0x01
53 static inline int ext4_begin_ordered_truncate(struct inode *inode,
54 loff_t new_size)
56 return jbd2_journal_begin_ordered_truncate(
57 EXT4_SB(inode->i_sb)->s_journal,
58 &EXT4_I(inode)->jinode,
59 new_size);
62 static void ext4_invalidatepage(struct page *page, unsigned long offset);
65 * Test whether an inode is a fast symlink.
67 static int ext4_inode_is_fast_symlink(struct inode *inode)
69 int ea_blocks = EXT4_I(inode)->i_file_acl ?
70 (inode->i_sb->s_blocksize >> 9) : 0;
72 return (S_ISLNK(inode->i_mode) && inode->i_blocks - ea_blocks == 0);
76 * Work out how many blocks we need to proceed with the next chunk of a
77 * truncate transaction.
79 static unsigned long blocks_for_truncate(struct inode *inode)
81 ext4_lblk_t needed;
83 needed = inode->i_blocks >> (inode->i_sb->s_blocksize_bits - 9);
85 /* Give ourselves just enough room to cope with inodes in which
86 * i_blocks is corrupt: we've seen disk corruptions in the past
87 * which resulted in random data in an inode which looked enough
88 * like a regular file for ext4 to try to delete it. Things
89 * will go a bit crazy if that happens, but at least we should
90 * try not to panic the whole kernel. */
91 if (needed < 2)
92 needed = 2;
94 /* But we need to bound the transaction so we don't overflow the
95 * journal. */
96 if (needed > EXT4_MAX_TRANS_DATA)
97 needed = EXT4_MAX_TRANS_DATA;
99 return EXT4_DATA_TRANS_BLOCKS(inode->i_sb) + needed;
103 * Truncate transactions can be complex and absolutely huge. So we need to
104 * be able to restart the transaction at a conventient checkpoint to make
105 * sure we don't overflow the journal.
107 * start_transaction gets us a new handle for a truncate transaction,
108 * and extend_transaction tries to extend the existing one a bit. If
109 * extend fails, we need to propagate the failure up and restart the
110 * transaction in the top-level truncate loop. --sct
112 static handle_t *start_transaction(struct inode *inode)
114 handle_t *result;
116 result = ext4_journal_start(inode, blocks_for_truncate(inode));
117 if (!IS_ERR(result))
118 return result;
120 ext4_std_error(inode->i_sb, PTR_ERR(result));
121 return result;
125 * Try to extend this transaction for the purposes of truncation.
127 * Returns 0 if we managed to create more room. If we can't create more
128 * room, and the transaction must be restarted we return 1.
130 static int try_to_extend_transaction(handle_t *handle, struct inode *inode)
132 if (!ext4_handle_valid(handle))
133 return 0;
134 if (ext4_handle_has_enough_credits(handle, EXT4_RESERVE_TRANS_BLOCKS+1))
135 return 0;
136 if (!ext4_journal_extend(handle, blocks_for_truncate(inode)))
137 return 0;
138 return 1;
142 * Restart the transaction associated with *handle. This does a commit,
143 * so before we call here everything must be consistently dirtied against
144 * this transaction.
146 int ext4_truncate_restart_trans(handle_t *handle, struct inode *inode,
147 int nblocks)
149 int ret;
152 * Drop i_data_sem to avoid deadlock with ext4_map_blocks. At this
153 * moment, get_block can be called only for blocks inside i_size since
154 * page cache has been already dropped and writes are blocked by
155 * i_mutex. So we can safely drop the i_data_sem here.
157 BUG_ON(EXT4_JOURNAL(inode) == NULL);
158 jbd_debug(2, "restarting handle %p\n", handle);
159 up_write(&EXT4_I(inode)->i_data_sem);
160 ret = ext4_journal_restart(handle, blocks_for_truncate(inode));
161 down_write(&EXT4_I(inode)->i_data_sem);
162 ext4_discard_preallocations(inode);
164 return ret;
168 * Called at the last iput() if i_nlink is zero.
170 void ext4_evict_inode(struct inode *inode)
172 handle_t *handle;
173 int err;
175 if (inode->i_nlink) {
176 truncate_inode_pages(&inode->i_data, 0);
177 goto no_delete;
180 if (!is_bad_inode(inode))
181 dquot_initialize(inode);
183 if (ext4_should_order_data(inode))
184 ext4_begin_ordered_truncate(inode, 0);
185 truncate_inode_pages(&inode->i_data, 0);
187 if (is_bad_inode(inode))
188 goto no_delete;
190 handle = ext4_journal_start(inode, blocks_for_truncate(inode)+3);
191 if (IS_ERR(handle)) {
192 ext4_std_error(inode->i_sb, PTR_ERR(handle));
194 * If we're going to skip the normal cleanup, we still need to
195 * make sure that the in-core orphan linked list is properly
196 * cleaned up.
198 ext4_orphan_del(NULL, inode);
199 goto no_delete;
202 if (IS_SYNC(inode))
203 ext4_handle_sync(handle);
204 inode->i_size = 0;
205 err = ext4_mark_inode_dirty(handle, inode);
206 if (err) {
207 ext4_warning(inode->i_sb,
208 "couldn't mark inode dirty (err %d)", err);
209 goto stop_handle;
211 if (inode->i_blocks)
212 ext4_truncate(inode);
215 * ext4_ext_truncate() doesn't reserve any slop when it
216 * restarts journal transactions; therefore there may not be
217 * enough credits left in the handle to remove the inode from
218 * the orphan list and set the dtime field.
220 if (!ext4_handle_has_enough_credits(handle, 3)) {
221 err = ext4_journal_extend(handle, 3);
222 if (err > 0)
223 err = ext4_journal_restart(handle, 3);
224 if (err != 0) {
225 ext4_warning(inode->i_sb,
226 "couldn't extend journal (err %d)", err);
227 stop_handle:
228 ext4_journal_stop(handle);
229 ext4_orphan_del(NULL, inode);
230 goto no_delete;
235 * Kill off the orphan record which ext4_truncate created.
236 * AKPM: I think this can be inside the above `if'.
237 * Note that ext4_orphan_del() has to be able to cope with the
238 * deletion of a non-existent orphan - this is because we don't
239 * know if ext4_truncate() actually created an orphan record.
240 * (Well, we could do this if we need to, but heck - it works)
242 ext4_orphan_del(handle, inode);
243 EXT4_I(inode)->i_dtime = get_seconds();
246 * One subtle ordering requirement: if anything has gone wrong
247 * (transaction abort, IO errors, whatever), then we can still
248 * do these next steps (the fs will already have been marked as
249 * having errors), but we can't free the inode if the mark_dirty
250 * fails.
252 if (ext4_mark_inode_dirty(handle, inode))
253 /* If that failed, just do the required in-core inode clear. */
254 ext4_clear_inode(inode);
255 else
256 ext4_free_inode(handle, inode);
257 ext4_journal_stop(handle);
258 return;
259 no_delete:
260 ext4_clear_inode(inode); /* We must guarantee clearing of inode... */
263 typedef struct {
264 __le32 *p;
265 __le32 key;
266 struct buffer_head *bh;
267 } Indirect;
269 static inline void add_chain(Indirect *p, struct buffer_head *bh, __le32 *v)
271 p->key = *(p->p = v);
272 p->bh = bh;
276 * ext4_block_to_path - parse the block number into array of offsets
277 * @inode: inode in question (we are only interested in its superblock)
278 * @i_block: block number to be parsed
279 * @offsets: array to store the offsets in
280 * @boundary: set this non-zero if the referred-to block is likely to be
281 * followed (on disk) by an indirect block.
283 * To store the locations of file's data ext4 uses a data structure common
284 * for UNIX filesystems - tree of pointers anchored in the inode, with
285 * data blocks at leaves and indirect blocks in intermediate nodes.
286 * This function translates the block number into path in that tree -
287 * return value is the path length and @offsets[n] is the offset of
288 * pointer to (n+1)th node in the nth one. If @block is out of range
289 * (negative or too large) warning is printed and zero returned.
291 * Note: function doesn't find node addresses, so no IO is needed. All
292 * we need to know is the capacity of indirect blocks (taken from the
293 * inode->i_sb).
297 * Portability note: the last comparison (check that we fit into triple
298 * indirect block) is spelled differently, because otherwise on an
299 * architecture with 32-bit longs and 8Kb pages we might get into trouble
300 * if our filesystem had 8Kb blocks. We might use long long, but that would
301 * kill us on x86. Oh, well, at least the sign propagation does not matter -
302 * i_block would have to be negative in the very beginning, so we would not
303 * get there at all.
306 static int ext4_block_to_path(struct inode *inode,
307 ext4_lblk_t i_block,
308 ext4_lblk_t offsets[4], int *boundary)
310 int ptrs = EXT4_ADDR_PER_BLOCK(inode->i_sb);
311 int ptrs_bits = EXT4_ADDR_PER_BLOCK_BITS(inode->i_sb);
312 const long direct_blocks = EXT4_NDIR_BLOCKS,
313 indirect_blocks = ptrs,
314 double_blocks = (1 << (ptrs_bits * 2));
315 int n = 0;
316 int final = 0;
318 if (i_block < direct_blocks) {
319 offsets[n++] = i_block;
320 final = direct_blocks;
321 } else if ((i_block -= direct_blocks) < indirect_blocks) {
322 offsets[n++] = EXT4_IND_BLOCK;
323 offsets[n++] = i_block;
324 final = ptrs;
325 } else if ((i_block -= indirect_blocks) < double_blocks) {
326 offsets[n++] = EXT4_DIND_BLOCK;
327 offsets[n++] = i_block >> ptrs_bits;
328 offsets[n++] = i_block & (ptrs - 1);
329 final = ptrs;
330 } else if (((i_block -= double_blocks) >> (ptrs_bits * 2)) < ptrs) {
331 offsets[n++] = EXT4_TIND_BLOCK;
332 offsets[n++] = i_block >> (ptrs_bits * 2);
333 offsets[n++] = (i_block >> ptrs_bits) & (ptrs - 1);
334 offsets[n++] = i_block & (ptrs - 1);
335 final = ptrs;
336 } else {
337 ext4_warning(inode->i_sb, "block %lu > max in inode %lu",
338 i_block + direct_blocks +
339 indirect_blocks + double_blocks, inode->i_ino);
341 if (boundary)
342 *boundary = final - 1 - (i_block & (ptrs - 1));
343 return n;
346 static int __ext4_check_blockref(const char *function, unsigned int line,
347 struct inode *inode,
348 __le32 *p, unsigned int max)
350 struct ext4_super_block *es = EXT4_SB(inode->i_sb)->s_es;
351 __le32 *bref = p;
352 unsigned int blk;
354 while (bref < p+max) {
355 blk = le32_to_cpu(*bref++);
356 if (blk &&
357 unlikely(!ext4_data_block_valid(EXT4_SB(inode->i_sb),
358 blk, 1))) {
359 es->s_last_error_block = cpu_to_le64(blk);
360 ext4_error_inode(inode, function, line, blk,
361 "invalid block");
362 return -EIO;
365 return 0;
369 #define ext4_check_indirect_blockref(inode, bh) \
370 __ext4_check_blockref(__func__, __LINE__, inode, \
371 (__le32 *)(bh)->b_data, \
372 EXT4_ADDR_PER_BLOCK((inode)->i_sb))
374 #define ext4_check_inode_blockref(inode) \
375 __ext4_check_blockref(__func__, __LINE__, inode, \
376 EXT4_I(inode)->i_data, \
377 EXT4_NDIR_BLOCKS)
380 * ext4_get_branch - read the chain of indirect blocks leading to data
381 * @inode: inode in question
382 * @depth: depth of the chain (1 - direct pointer, etc.)
383 * @offsets: offsets of pointers in inode/indirect blocks
384 * @chain: place to store the result
385 * @err: here we store the error value
387 * Function fills the array of triples <key, p, bh> and returns %NULL
388 * if everything went OK or the pointer to the last filled triple
389 * (incomplete one) otherwise. Upon the return chain[i].key contains
390 * the number of (i+1)-th block in the chain (as it is stored in memory,
391 * i.e. little-endian 32-bit), chain[i].p contains the address of that
392 * number (it points into struct inode for i==0 and into the bh->b_data
393 * for i>0) and chain[i].bh points to the buffer_head of i-th indirect
394 * block for i>0 and NULL for i==0. In other words, it holds the block
395 * numbers of the chain, addresses they were taken from (and where we can
396 * verify that chain did not change) and buffer_heads hosting these
397 * numbers.
399 * Function stops when it stumbles upon zero pointer (absent block)
400 * (pointer to last triple returned, *@err == 0)
401 * or when it gets an IO error reading an indirect block
402 * (ditto, *@err == -EIO)
403 * or when it reads all @depth-1 indirect blocks successfully and finds
404 * the whole chain, all way to the data (returns %NULL, *err == 0).
406 * Need to be called with
407 * down_read(&EXT4_I(inode)->i_data_sem)
409 static Indirect *ext4_get_branch(struct inode *inode, int depth,
410 ext4_lblk_t *offsets,
411 Indirect chain[4], int *err)
413 struct super_block *sb = inode->i_sb;
414 Indirect *p = chain;
415 struct buffer_head *bh;
417 *err = 0;
418 /* i_data is not going away, no lock needed */
419 add_chain(chain, NULL, EXT4_I(inode)->i_data + *offsets);
420 if (!p->key)
421 goto no_block;
422 while (--depth) {
423 bh = sb_getblk(sb, le32_to_cpu(p->key));
424 if (unlikely(!bh))
425 goto failure;
427 if (!bh_uptodate_or_lock(bh)) {
428 if (bh_submit_read(bh) < 0) {
429 put_bh(bh);
430 goto failure;
432 /* validate block references */
433 if (ext4_check_indirect_blockref(inode, bh)) {
434 put_bh(bh);
435 goto failure;
439 add_chain(++p, bh, (__le32 *)bh->b_data + *++offsets);
440 /* Reader: end */
441 if (!p->key)
442 goto no_block;
444 return NULL;
446 failure:
447 *err = -EIO;
448 no_block:
449 return p;
453 * ext4_find_near - find a place for allocation with sufficient locality
454 * @inode: owner
455 * @ind: descriptor of indirect block.
457 * This function returns the preferred place for block allocation.
458 * It is used when heuristic for sequential allocation fails.
459 * Rules are:
460 * + if there is a block to the left of our position - allocate near it.
461 * + if pointer will live in indirect block - allocate near that block.
462 * + if pointer will live in inode - allocate in the same
463 * cylinder group.
465 * In the latter case we colour the starting block by the callers PID to
466 * prevent it from clashing with concurrent allocations for a different inode
467 * in the same block group. The PID is used here so that functionally related
468 * files will be close-by on-disk.
470 * Caller must make sure that @ind is valid and will stay that way.
472 static ext4_fsblk_t ext4_find_near(struct inode *inode, Indirect *ind)
474 struct ext4_inode_info *ei = EXT4_I(inode);
475 __le32 *start = ind->bh ? (__le32 *) ind->bh->b_data : ei->i_data;
476 __le32 *p;
477 ext4_fsblk_t bg_start;
478 ext4_fsblk_t last_block;
479 ext4_grpblk_t colour;
480 ext4_group_t block_group;
481 int flex_size = ext4_flex_bg_size(EXT4_SB(inode->i_sb));
483 /* Try to find previous block */
484 for (p = ind->p - 1; p >= start; p--) {
485 if (*p)
486 return le32_to_cpu(*p);
489 /* No such thing, so let's try location of indirect block */
490 if (ind->bh)
491 return ind->bh->b_blocknr;
494 * It is going to be referred to from the inode itself? OK, just put it
495 * into the same cylinder group then.
497 block_group = ei->i_block_group;
498 if (flex_size >= EXT4_FLEX_SIZE_DIR_ALLOC_SCHEME) {
499 block_group &= ~(flex_size-1);
500 if (S_ISREG(inode->i_mode))
501 block_group++;
503 bg_start = ext4_group_first_block_no(inode->i_sb, block_group);
504 last_block = ext4_blocks_count(EXT4_SB(inode->i_sb)->s_es) - 1;
507 * If we are doing delayed allocation, we don't need take
508 * colour into account.
510 if (test_opt(inode->i_sb, DELALLOC))
511 return bg_start;
513 if (bg_start + EXT4_BLOCKS_PER_GROUP(inode->i_sb) <= last_block)
514 colour = (current->pid % 16) *
515 (EXT4_BLOCKS_PER_GROUP(inode->i_sb) / 16);
516 else
517 colour = (current->pid % 16) * ((last_block - bg_start) / 16);
518 return bg_start + colour;
522 * ext4_find_goal - find a preferred place for allocation.
523 * @inode: owner
524 * @block: block we want
525 * @partial: pointer to the last triple within a chain
527 * Normally this function find the preferred place for block allocation,
528 * returns it.
529 * Because this is only used for non-extent files, we limit the block nr
530 * to 32 bits.
532 static ext4_fsblk_t ext4_find_goal(struct inode *inode, ext4_lblk_t block,
533 Indirect *partial)
535 ext4_fsblk_t goal;
538 goal = ext4_find_near(inode, partial);
539 goal = goal & EXT4_MAX_BLOCK_FILE_PHYS;
540 return goal;
544 * ext4_blks_to_allocate: Look up the block map and count the number
545 * of direct blocks need to be allocated for the given branch.
547 * @branch: chain of indirect blocks
548 * @k: number of blocks need for indirect blocks
549 * @blks: number of data blocks to be mapped.
550 * @blocks_to_boundary: the offset in the indirect block
552 * return the total number of blocks to be allocate, including the
553 * direct and indirect blocks.
555 static int ext4_blks_to_allocate(Indirect *branch, int k, unsigned int blks,
556 int blocks_to_boundary)
558 unsigned int count = 0;
561 * Simple case, [t,d]Indirect block(s) has not allocated yet
562 * then it's clear blocks on that path have not allocated
564 if (k > 0) {
565 /* right now we don't handle cross boundary allocation */
566 if (blks < blocks_to_boundary + 1)
567 count += blks;
568 else
569 count += blocks_to_boundary + 1;
570 return count;
573 count++;
574 while (count < blks && count <= blocks_to_boundary &&
575 le32_to_cpu(*(branch[0].p + count)) == 0) {
576 count++;
578 return count;
582 * ext4_alloc_blocks: multiple allocate blocks needed for a branch
583 * @indirect_blks: the number of blocks need to allocate for indirect
584 * blocks
586 * @new_blocks: on return it will store the new block numbers for
587 * the indirect blocks(if needed) and the first direct block,
588 * @blks: on return it will store the total number of allocated
589 * direct blocks
591 static int ext4_alloc_blocks(handle_t *handle, struct inode *inode,
592 ext4_lblk_t iblock, ext4_fsblk_t goal,
593 int indirect_blks, int blks,
594 ext4_fsblk_t new_blocks[4], int *err)
596 struct ext4_allocation_request ar;
597 int target, i;
598 unsigned long count = 0, blk_allocated = 0;
599 int index = 0;
600 ext4_fsblk_t current_block = 0;
601 int ret = 0;
604 * Here we try to allocate the requested multiple blocks at once,
605 * on a best-effort basis.
606 * To build a branch, we should allocate blocks for
607 * the indirect blocks(if not allocated yet), and at least
608 * the first direct block of this branch. That's the
609 * minimum number of blocks need to allocate(required)
611 /* first we try to allocate the indirect blocks */
612 target = indirect_blks;
613 while (target > 0) {
614 count = target;
615 /* allocating blocks for indirect blocks and direct blocks */
616 current_block = ext4_new_meta_blocks(handle, inode,
617 goal, &count, err);
618 if (*err)
619 goto failed_out;
621 if (unlikely(current_block + count > EXT4_MAX_BLOCK_FILE_PHYS)) {
622 EXT4_ERROR_INODE(inode,
623 "current_block %llu + count %lu > %d!",
624 current_block, count,
625 EXT4_MAX_BLOCK_FILE_PHYS);
626 *err = -EIO;
627 goto failed_out;
630 target -= count;
631 /* allocate blocks for indirect blocks */
632 while (index < indirect_blks && count) {
633 new_blocks[index++] = current_block++;
634 count--;
636 if (count > 0) {
638 * save the new block number
639 * for the first direct block
641 new_blocks[index] = current_block;
642 printk(KERN_INFO "%s returned more blocks than "
643 "requested\n", __func__);
644 WARN_ON(1);
645 break;
649 target = blks - count ;
650 blk_allocated = count;
651 if (!target)
652 goto allocated;
653 /* Now allocate data blocks */
654 memset(&ar, 0, sizeof(ar));
655 ar.inode = inode;
656 ar.goal = goal;
657 ar.len = target;
658 ar.logical = iblock;
659 if (S_ISREG(inode->i_mode))
660 /* enable in-core preallocation only for regular files */
661 ar.flags = EXT4_MB_HINT_DATA;
663 current_block = ext4_mb_new_blocks(handle, &ar, err);
664 if (unlikely(current_block + ar.len > EXT4_MAX_BLOCK_FILE_PHYS)) {
665 EXT4_ERROR_INODE(inode,
666 "current_block %llu + ar.len %d > %d!",
667 current_block, ar.len,
668 EXT4_MAX_BLOCK_FILE_PHYS);
669 *err = -EIO;
670 goto failed_out;
673 if (*err && (target == blks)) {
675 * if the allocation failed and we didn't allocate
676 * any blocks before
678 goto failed_out;
680 if (!*err) {
681 if (target == blks) {
683 * save the new block number
684 * for the first direct block
686 new_blocks[index] = current_block;
688 blk_allocated += ar.len;
690 allocated:
691 /* total number of blocks allocated for direct blocks */
692 ret = blk_allocated;
693 *err = 0;
694 return ret;
695 failed_out:
696 for (i = 0; i < index; i++)
697 ext4_free_blocks(handle, inode, 0, new_blocks[i], 1, 0);
698 return ret;
702 * ext4_alloc_branch - allocate and set up a chain of blocks.
703 * @inode: owner
704 * @indirect_blks: number of allocated indirect blocks
705 * @blks: number of allocated direct blocks
706 * @offsets: offsets (in the blocks) to store the pointers to next.
707 * @branch: place to store the chain in.
709 * This function allocates blocks, zeroes out all but the last one,
710 * links them into chain and (if we are synchronous) writes them to disk.
711 * In other words, it prepares a branch that can be spliced onto the
712 * inode. It stores the information about that chain in the branch[], in
713 * the same format as ext4_get_branch() would do. We are calling it after
714 * we had read the existing part of chain and partial points to the last
715 * triple of that (one with zero ->key). Upon the exit we have the same
716 * picture as after the successful ext4_get_block(), except that in one
717 * place chain is disconnected - *branch->p is still zero (we did not
718 * set the last link), but branch->key contains the number that should
719 * be placed into *branch->p to fill that gap.
721 * If allocation fails we free all blocks we've allocated (and forget
722 * their buffer_heads) and return the error value the from failed
723 * ext4_alloc_block() (normally -ENOSPC). Otherwise we set the chain
724 * as described above and return 0.
726 static int ext4_alloc_branch(handle_t *handle, struct inode *inode,
727 ext4_lblk_t iblock, int indirect_blks,
728 int *blks, ext4_fsblk_t goal,
729 ext4_lblk_t *offsets, Indirect *branch)
731 int blocksize = inode->i_sb->s_blocksize;
732 int i, n = 0;
733 int err = 0;
734 struct buffer_head *bh;
735 int num;
736 ext4_fsblk_t new_blocks[4];
737 ext4_fsblk_t current_block;
739 num = ext4_alloc_blocks(handle, inode, iblock, goal, indirect_blks,
740 *blks, new_blocks, &err);
741 if (err)
742 return err;
744 branch[0].key = cpu_to_le32(new_blocks[0]);
746 * metadata blocks and data blocks are allocated.
748 for (n = 1; n <= indirect_blks; n++) {
750 * Get buffer_head for parent block, zero it out
751 * and set the pointer to new one, then send
752 * parent to disk.
754 bh = sb_getblk(inode->i_sb, new_blocks[n-1]);
755 branch[n].bh = bh;
756 lock_buffer(bh);
757 BUFFER_TRACE(bh, "call get_create_access");
758 err = ext4_journal_get_create_access(handle, bh);
759 if (err) {
760 /* Don't brelse(bh) here; it's done in
761 * ext4_journal_forget() below */
762 unlock_buffer(bh);
763 goto failed;
766 memset(bh->b_data, 0, blocksize);
767 branch[n].p = (__le32 *) bh->b_data + offsets[n];
768 branch[n].key = cpu_to_le32(new_blocks[n]);
769 *branch[n].p = branch[n].key;
770 if (n == indirect_blks) {
771 current_block = new_blocks[n];
773 * End of chain, update the last new metablock of
774 * the chain to point to the new allocated
775 * data blocks numbers
777 for (i = 1; i < num; i++)
778 *(branch[n].p + i) = cpu_to_le32(++current_block);
780 BUFFER_TRACE(bh, "marking uptodate");
781 set_buffer_uptodate(bh);
782 unlock_buffer(bh);
784 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
785 err = ext4_handle_dirty_metadata(handle, inode, bh);
786 if (err)
787 goto failed;
789 *blks = num;
790 return err;
791 failed:
792 /* Allocation failed, free what we already allocated */
793 ext4_free_blocks(handle, inode, 0, new_blocks[0], 1, 0);
794 for (i = 1; i <= n ; i++) {
796 * branch[i].bh is newly allocated, so there is no
797 * need to revoke the block, which is why we don't
798 * need to set EXT4_FREE_BLOCKS_METADATA.
800 ext4_free_blocks(handle, inode, 0, new_blocks[i], 1,
801 EXT4_FREE_BLOCKS_FORGET);
803 for (i = n+1; i < indirect_blks; i++)
804 ext4_free_blocks(handle, inode, 0, new_blocks[i], 1, 0);
806 ext4_free_blocks(handle, inode, 0, new_blocks[i], num, 0);
808 return err;
812 * ext4_splice_branch - splice the allocated branch onto inode.
813 * @inode: owner
814 * @block: (logical) number of block we are adding
815 * @chain: chain of indirect blocks (with a missing link - see
816 * ext4_alloc_branch)
817 * @where: location of missing link
818 * @num: number of indirect blocks we are adding
819 * @blks: number of direct blocks we are adding
821 * This function fills the missing link and does all housekeeping needed in
822 * inode (->i_blocks, etc.). In case of success we end up with the full
823 * chain to new block and return 0.
825 static int ext4_splice_branch(handle_t *handle, struct inode *inode,
826 ext4_lblk_t block, Indirect *where, int num,
827 int blks)
829 int i;
830 int err = 0;
831 ext4_fsblk_t current_block;
834 * If we're splicing into a [td]indirect block (as opposed to the
835 * inode) then we need to get write access to the [td]indirect block
836 * before the splice.
838 if (where->bh) {
839 BUFFER_TRACE(where->bh, "get_write_access");
840 err = ext4_journal_get_write_access(handle, where->bh);
841 if (err)
842 goto err_out;
844 /* That's it */
846 *where->p = where->key;
849 * Update the host buffer_head or inode to point to more just allocated
850 * direct blocks blocks
852 if (num == 0 && blks > 1) {
853 current_block = le32_to_cpu(where->key) + 1;
854 for (i = 1; i < blks; i++)
855 *(where->p + i) = cpu_to_le32(current_block++);
858 /* We are done with atomic stuff, now do the rest of housekeeping */
859 /* had we spliced it onto indirect block? */
860 if (where->bh) {
862 * If we spliced it onto an indirect block, we haven't
863 * altered the inode. Note however that if it is being spliced
864 * onto an indirect block at the very end of the file (the
865 * file is growing) then we *will* alter the inode to reflect
866 * the new i_size. But that is not done here - it is done in
867 * generic_commit_write->__mark_inode_dirty->ext4_dirty_inode.
869 jbd_debug(5, "splicing indirect only\n");
870 BUFFER_TRACE(where->bh, "call ext4_handle_dirty_metadata");
871 err = ext4_handle_dirty_metadata(handle, inode, where->bh);
872 if (err)
873 goto err_out;
874 } else {
876 * OK, we spliced it into the inode itself on a direct block.
878 ext4_mark_inode_dirty(handle, inode);
879 jbd_debug(5, "splicing direct\n");
881 return err;
883 err_out:
884 for (i = 1; i <= num; i++) {
886 * branch[i].bh is newly allocated, so there is no
887 * need to revoke the block, which is why we don't
888 * need to set EXT4_FREE_BLOCKS_METADATA.
890 ext4_free_blocks(handle, inode, where[i].bh, 0, 1,
891 EXT4_FREE_BLOCKS_FORGET);
893 ext4_free_blocks(handle, inode, 0, le32_to_cpu(where[num].key),
894 blks, 0);
896 return err;
900 * The ext4_ind_map_blocks() function handles non-extents inodes
901 * (i.e., using the traditional indirect/double-indirect i_blocks
902 * scheme) for ext4_map_blocks().
904 * Allocation strategy is simple: if we have to allocate something, we will
905 * have to go the whole way to leaf. So let's do it before attaching anything
906 * to tree, set linkage between the newborn blocks, write them if sync is
907 * required, recheck the path, free and repeat if check fails, otherwise
908 * set the last missing link (that will protect us from any truncate-generated
909 * removals - all blocks on the path are immune now) and possibly force the
910 * write on the parent block.
911 * That has a nice additional property: no special recovery from the failed
912 * allocations is needed - we simply release blocks and do not touch anything
913 * reachable from inode.
915 * `handle' can be NULL if create == 0.
917 * return > 0, # of blocks mapped or allocated.
918 * return = 0, if plain lookup failed.
919 * return < 0, error case.
921 * The ext4_ind_get_blocks() function should be called with
922 * down_write(&EXT4_I(inode)->i_data_sem) if allocating filesystem
923 * blocks (i.e., flags has EXT4_GET_BLOCKS_CREATE set) or
924 * down_read(&EXT4_I(inode)->i_data_sem) if not allocating file system
925 * blocks.
927 static int ext4_ind_map_blocks(handle_t *handle, struct inode *inode,
928 struct ext4_map_blocks *map,
929 int flags)
931 int err = -EIO;
932 ext4_lblk_t offsets[4];
933 Indirect chain[4];
934 Indirect *partial;
935 ext4_fsblk_t goal;
936 int indirect_blks;
937 int blocks_to_boundary = 0;
938 int depth;
939 int count = 0;
940 ext4_fsblk_t first_block = 0;
942 J_ASSERT(!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)));
943 J_ASSERT(handle != NULL || (flags & EXT4_GET_BLOCKS_CREATE) == 0);
944 depth = ext4_block_to_path(inode, map->m_lblk, offsets,
945 &blocks_to_boundary);
947 if (depth == 0)
948 goto out;
950 partial = ext4_get_branch(inode, depth, offsets, chain, &err);
952 /* Simplest case - block found, no allocation needed */
953 if (!partial) {
954 first_block = le32_to_cpu(chain[depth - 1].key);
955 count++;
956 /*map more blocks*/
957 while (count < map->m_len && count <= blocks_to_boundary) {
958 ext4_fsblk_t blk;
960 blk = le32_to_cpu(*(chain[depth-1].p + count));
962 if (blk == first_block + count)
963 count++;
964 else
965 break;
967 goto got_it;
970 /* Next simple case - plain lookup or failed read of indirect block */
971 if ((flags & EXT4_GET_BLOCKS_CREATE) == 0 || err == -EIO)
972 goto cleanup;
975 * Okay, we need to do block allocation.
977 goal = ext4_find_goal(inode, map->m_lblk, partial);
979 /* the number of blocks need to allocate for [d,t]indirect blocks */
980 indirect_blks = (chain + depth) - partial - 1;
983 * Next look up the indirect map to count the totoal number of
984 * direct blocks to allocate for this branch.
986 count = ext4_blks_to_allocate(partial, indirect_blks,
987 map->m_len, blocks_to_boundary);
989 * Block out ext4_truncate while we alter the tree
991 err = ext4_alloc_branch(handle, inode, map->m_lblk, indirect_blks,
992 &count, goal,
993 offsets + (partial - chain), partial);
996 * The ext4_splice_branch call will free and forget any buffers
997 * on the new chain if there is a failure, but that risks using
998 * up transaction credits, especially for bitmaps where the
999 * credits cannot be returned. Can we handle this somehow? We
1000 * may need to return -EAGAIN upwards in the worst case. --sct
1002 if (!err)
1003 err = ext4_splice_branch(handle, inode, map->m_lblk,
1004 partial, indirect_blks, count);
1005 if (err)
1006 goto cleanup;
1008 map->m_flags |= EXT4_MAP_NEW;
1010 ext4_update_inode_fsync_trans(handle, inode, 1);
1011 got_it:
1012 map->m_flags |= EXT4_MAP_MAPPED;
1013 map->m_pblk = le32_to_cpu(chain[depth-1].key);
1014 map->m_len = count;
1015 if (count > blocks_to_boundary)
1016 map->m_flags |= EXT4_MAP_BOUNDARY;
1017 err = count;
1018 /* Clean up and exit */
1019 partial = chain + depth - 1; /* the whole chain */
1020 cleanup:
1021 while (partial > chain) {
1022 BUFFER_TRACE(partial->bh, "call brelse");
1023 brelse(partial->bh);
1024 partial--;
1026 out:
1027 return err;
1030 #ifdef CONFIG_QUOTA
1031 qsize_t *ext4_get_reserved_space(struct inode *inode)
1033 return &EXT4_I(inode)->i_reserved_quota;
1035 #endif
1038 * Calculate the number of metadata blocks need to reserve
1039 * to allocate a new block at @lblocks for non extent file based file
1041 static int ext4_indirect_calc_metadata_amount(struct inode *inode,
1042 sector_t lblock)
1044 struct ext4_inode_info *ei = EXT4_I(inode);
1045 sector_t dind_mask = ~((sector_t)EXT4_ADDR_PER_BLOCK(inode->i_sb) - 1);
1046 int blk_bits;
1048 if (lblock < EXT4_NDIR_BLOCKS)
1049 return 0;
1051 lblock -= EXT4_NDIR_BLOCKS;
1053 if (ei->i_da_metadata_calc_len &&
1054 (lblock & dind_mask) == ei->i_da_metadata_calc_last_lblock) {
1055 ei->i_da_metadata_calc_len++;
1056 return 0;
1058 ei->i_da_metadata_calc_last_lblock = lblock & dind_mask;
1059 ei->i_da_metadata_calc_len = 1;
1060 blk_bits = order_base_2(lblock);
1061 return (blk_bits / EXT4_ADDR_PER_BLOCK_BITS(inode->i_sb)) + 1;
1065 * Calculate the number of metadata blocks need to reserve
1066 * to allocate a block located at @lblock
1068 static int ext4_calc_metadata_amount(struct inode *inode, sector_t lblock)
1070 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
1071 return ext4_ext_calc_metadata_amount(inode, lblock);
1073 return ext4_indirect_calc_metadata_amount(inode, lblock);
1077 * Called with i_data_sem down, which is important since we can call
1078 * ext4_discard_preallocations() from here.
1080 void ext4_da_update_reserve_space(struct inode *inode,
1081 int used, int quota_claim)
1083 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1084 struct ext4_inode_info *ei = EXT4_I(inode);
1086 spin_lock(&ei->i_block_reservation_lock);
1087 trace_ext4_da_update_reserve_space(inode, used);
1088 if (unlikely(used > ei->i_reserved_data_blocks)) {
1089 ext4_msg(inode->i_sb, KERN_NOTICE, "%s: ino %lu, used %d "
1090 "with only %d reserved data blocks\n",
1091 __func__, inode->i_ino, used,
1092 ei->i_reserved_data_blocks);
1093 WARN_ON(1);
1094 used = ei->i_reserved_data_blocks;
1097 /* Update per-inode reservations */
1098 ei->i_reserved_data_blocks -= used;
1099 ei->i_reserved_meta_blocks -= ei->i_allocated_meta_blocks;
1100 percpu_counter_sub(&sbi->s_dirtyblocks_counter,
1101 used + ei->i_allocated_meta_blocks);
1102 ei->i_allocated_meta_blocks = 0;
1104 if (ei->i_reserved_data_blocks == 0) {
1106 * We can release all of the reserved metadata blocks
1107 * only when we have written all of the delayed
1108 * allocation blocks.
1110 percpu_counter_sub(&sbi->s_dirtyblocks_counter,
1111 ei->i_reserved_meta_blocks);
1112 ei->i_reserved_meta_blocks = 0;
1113 ei->i_da_metadata_calc_len = 0;
1115 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
1117 /* Update quota subsystem for data blocks */
1118 if (quota_claim)
1119 dquot_claim_block(inode, used);
1120 else {
1122 * We did fallocate with an offset that is already delayed
1123 * allocated. So on delayed allocated writeback we should
1124 * not re-claim the quota for fallocated blocks.
1126 dquot_release_reservation_block(inode, used);
1130 * If we have done all the pending block allocations and if
1131 * there aren't any writers on the inode, we can discard the
1132 * inode's preallocations.
1134 if ((ei->i_reserved_data_blocks == 0) &&
1135 (atomic_read(&inode->i_writecount) == 0))
1136 ext4_discard_preallocations(inode);
1139 static int __check_block_validity(struct inode *inode, const char *func,
1140 unsigned int line,
1141 struct ext4_map_blocks *map)
1143 if (!ext4_data_block_valid(EXT4_SB(inode->i_sb), map->m_pblk,
1144 map->m_len)) {
1145 ext4_error_inode(inode, func, line, map->m_pblk,
1146 "lblock %lu mapped to illegal pblock "
1147 "(length %d)", (unsigned long) map->m_lblk,
1148 map->m_len);
1149 return -EIO;
1151 return 0;
1154 #define check_block_validity(inode, map) \
1155 __check_block_validity((inode), __func__, __LINE__, (map))
1158 * Return the number of contiguous dirty pages in a given inode
1159 * starting at page frame idx.
1161 static pgoff_t ext4_num_dirty_pages(struct inode *inode, pgoff_t idx,
1162 unsigned int max_pages)
1164 struct address_space *mapping = inode->i_mapping;
1165 pgoff_t index;
1166 struct pagevec pvec;
1167 pgoff_t num = 0;
1168 int i, nr_pages, done = 0;
1170 if (max_pages == 0)
1171 return 0;
1172 pagevec_init(&pvec, 0);
1173 while (!done) {
1174 index = idx;
1175 nr_pages = pagevec_lookup_tag(&pvec, mapping, &index,
1176 PAGECACHE_TAG_DIRTY,
1177 (pgoff_t)PAGEVEC_SIZE);
1178 if (nr_pages == 0)
1179 break;
1180 for (i = 0; i < nr_pages; i++) {
1181 struct page *page = pvec.pages[i];
1182 struct buffer_head *bh, *head;
1184 lock_page(page);
1185 if (unlikely(page->mapping != mapping) ||
1186 !PageDirty(page) ||
1187 PageWriteback(page) ||
1188 page->index != idx) {
1189 done = 1;
1190 unlock_page(page);
1191 break;
1193 if (page_has_buffers(page)) {
1194 bh = head = page_buffers(page);
1195 do {
1196 if (!buffer_delay(bh) &&
1197 !buffer_unwritten(bh))
1198 done = 1;
1199 bh = bh->b_this_page;
1200 } while (!done && (bh != head));
1202 unlock_page(page);
1203 if (done)
1204 break;
1205 idx++;
1206 num++;
1207 if (num >= max_pages)
1208 break;
1210 pagevec_release(&pvec);
1212 return num;
1216 * The ext4_map_blocks() function tries to look up the requested blocks,
1217 * and returns if the blocks are already mapped.
1219 * Otherwise it takes the write lock of the i_data_sem and allocate blocks
1220 * and store the allocated blocks in the result buffer head and mark it
1221 * mapped.
1223 * If file type is extents based, it will call ext4_ext_map_blocks(),
1224 * Otherwise, call with ext4_ind_map_blocks() to handle indirect mapping
1225 * based files
1227 * On success, it returns the number of blocks being mapped or allocate.
1228 * if create==0 and the blocks are pre-allocated and uninitialized block,
1229 * the result buffer head is unmapped. If the create ==1, it will make sure
1230 * the buffer head is mapped.
1232 * It returns 0 if plain look up failed (blocks have not been allocated), in
1233 * that casem, buffer head is unmapped
1235 * It returns the error in case of allocation failure.
1237 int ext4_map_blocks(handle_t *handle, struct inode *inode,
1238 struct ext4_map_blocks *map, int flags)
1240 int retval;
1242 map->m_flags = 0;
1243 ext_debug("ext4_map_blocks(): inode %lu, flag %d, max_blocks %u,"
1244 "logical block %lu\n", inode->i_ino, flags, map->m_len,
1245 (unsigned long) map->m_lblk);
1247 * Try to see if we can get the block without requesting a new
1248 * file system block.
1250 down_read((&EXT4_I(inode)->i_data_sem));
1251 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
1252 retval = ext4_ext_map_blocks(handle, inode, map, 0);
1253 } else {
1254 retval = ext4_ind_map_blocks(handle, inode, map, 0);
1256 up_read((&EXT4_I(inode)->i_data_sem));
1258 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
1259 int ret = check_block_validity(inode, map);
1260 if (ret != 0)
1261 return ret;
1264 /* If it is only a block(s) look up */
1265 if ((flags & EXT4_GET_BLOCKS_CREATE) == 0)
1266 return retval;
1269 * Returns if the blocks have already allocated
1271 * Note that if blocks have been preallocated
1272 * ext4_ext_get_block() returns th create = 0
1273 * with buffer head unmapped.
1275 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED)
1276 return retval;
1279 * When we call get_blocks without the create flag, the
1280 * BH_Unwritten flag could have gotten set if the blocks
1281 * requested were part of a uninitialized extent. We need to
1282 * clear this flag now that we are committed to convert all or
1283 * part of the uninitialized extent to be an initialized
1284 * extent. This is because we need to avoid the combination
1285 * of BH_Unwritten and BH_Mapped flags being simultaneously
1286 * set on the buffer_head.
1288 map->m_flags &= ~EXT4_MAP_UNWRITTEN;
1291 * New blocks allocate and/or writing to uninitialized extent
1292 * will possibly result in updating i_data, so we take
1293 * the write lock of i_data_sem, and call get_blocks()
1294 * with create == 1 flag.
1296 down_write((&EXT4_I(inode)->i_data_sem));
1299 * if the caller is from delayed allocation writeout path
1300 * we have already reserved fs blocks for allocation
1301 * let the underlying get_block() function know to
1302 * avoid double accounting
1304 if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
1305 EXT4_I(inode)->i_delalloc_reserved_flag = 1;
1307 * We need to check for EXT4 here because migrate
1308 * could have changed the inode type in between
1310 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
1311 retval = ext4_ext_map_blocks(handle, inode, map, flags);
1312 } else {
1313 retval = ext4_ind_map_blocks(handle, inode, map, flags);
1315 if (retval > 0 && map->m_flags & EXT4_MAP_NEW) {
1317 * We allocated new blocks which will result in
1318 * i_data's format changing. Force the migrate
1319 * to fail by clearing migrate flags
1321 ext4_clear_inode_state(inode, EXT4_STATE_EXT_MIGRATE);
1325 * Update reserved blocks/metadata blocks after successful
1326 * block allocation which had been deferred till now. We don't
1327 * support fallocate for non extent files. So we can update
1328 * reserve space here.
1330 if ((retval > 0) &&
1331 (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE))
1332 ext4_da_update_reserve_space(inode, retval, 1);
1334 if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
1335 EXT4_I(inode)->i_delalloc_reserved_flag = 0;
1337 up_write((&EXT4_I(inode)->i_data_sem));
1338 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
1339 int ret = check_block_validity(inode, map);
1340 if (ret != 0)
1341 return ret;
1343 return retval;
1346 /* Maximum number of blocks we map for direct IO at once. */
1347 #define DIO_MAX_BLOCKS 4096
1349 static int _ext4_get_block(struct inode *inode, sector_t iblock,
1350 struct buffer_head *bh, int flags)
1352 handle_t *handle = ext4_journal_current_handle();
1353 struct ext4_map_blocks map;
1354 int ret = 0, started = 0;
1355 int dio_credits;
1357 map.m_lblk = iblock;
1358 map.m_len = bh->b_size >> inode->i_blkbits;
1360 if (flags && !handle) {
1361 /* Direct IO write... */
1362 if (map.m_len > DIO_MAX_BLOCKS)
1363 map.m_len = DIO_MAX_BLOCKS;
1364 dio_credits = ext4_chunk_trans_blocks(inode, map.m_len);
1365 handle = ext4_journal_start(inode, dio_credits);
1366 if (IS_ERR(handle)) {
1367 ret = PTR_ERR(handle);
1368 return ret;
1370 started = 1;
1373 ret = ext4_map_blocks(handle, inode, &map, flags);
1374 if (ret > 0) {
1375 map_bh(bh, inode->i_sb, map.m_pblk);
1376 bh->b_state = (bh->b_state & ~EXT4_MAP_FLAGS) | map.m_flags;
1377 bh->b_size = inode->i_sb->s_blocksize * map.m_len;
1378 ret = 0;
1380 if (started)
1381 ext4_journal_stop(handle);
1382 return ret;
1385 int ext4_get_block(struct inode *inode, sector_t iblock,
1386 struct buffer_head *bh, int create)
1388 return _ext4_get_block(inode, iblock, bh,
1389 create ? EXT4_GET_BLOCKS_CREATE : 0);
1393 * `handle' can be NULL if create is zero
1395 struct buffer_head *ext4_getblk(handle_t *handle, struct inode *inode,
1396 ext4_lblk_t block, int create, int *errp)
1398 struct ext4_map_blocks map;
1399 struct buffer_head *bh;
1400 int fatal = 0, err;
1402 J_ASSERT(handle != NULL || create == 0);
1404 map.m_lblk = block;
1405 map.m_len = 1;
1406 err = ext4_map_blocks(handle, inode, &map,
1407 create ? EXT4_GET_BLOCKS_CREATE : 0);
1409 if (err < 0)
1410 *errp = err;
1411 if (err <= 0)
1412 return NULL;
1413 *errp = 0;
1415 bh = sb_getblk(inode->i_sb, map.m_pblk);
1416 if (!bh) {
1417 *errp = -EIO;
1418 return NULL;
1420 if (map.m_flags & EXT4_MAP_NEW) {
1421 J_ASSERT(create != 0);
1422 J_ASSERT(handle != NULL);
1425 * Now that we do not always journal data, we should
1426 * keep in mind whether this should always journal the
1427 * new buffer as metadata. For now, regular file
1428 * writes use ext4_get_block instead, so it's not a
1429 * problem.
1431 lock_buffer(bh);
1432 BUFFER_TRACE(bh, "call get_create_access");
1433 fatal = ext4_journal_get_create_access(handle, bh);
1434 if (!fatal && !buffer_uptodate(bh)) {
1435 memset(bh->b_data, 0, inode->i_sb->s_blocksize);
1436 set_buffer_uptodate(bh);
1438 unlock_buffer(bh);
1439 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
1440 err = ext4_handle_dirty_metadata(handle, inode, bh);
1441 if (!fatal)
1442 fatal = err;
1443 } else {
1444 BUFFER_TRACE(bh, "not a new buffer");
1446 if (fatal) {
1447 *errp = fatal;
1448 brelse(bh);
1449 bh = NULL;
1451 return bh;
1454 struct buffer_head *ext4_bread(handle_t *handle, struct inode *inode,
1455 ext4_lblk_t block, int create, int *err)
1457 struct buffer_head *bh;
1459 bh = ext4_getblk(handle, inode, block, create, err);
1460 if (!bh)
1461 return bh;
1462 if (buffer_uptodate(bh))
1463 return bh;
1464 ll_rw_block(READ_META, 1, &bh);
1465 wait_on_buffer(bh);
1466 if (buffer_uptodate(bh))
1467 return bh;
1468 put_bh(bh);
1469 *err = -EIO;
1470 return NULL;
1473 static int walk_page_buffers(handle_t *handle,
1474 struct buffer_head *head,
1475 unsigned from,
1476 unsigned to,
1477 int *partial,
1478 int (*fn)(handle_t *handle,
1479 struct buffer_head *bh))
1481 struct buffer_head *bh;
1482 unsigned block_start, block_end;
1483 unsigned blocksize = head->b_size;
1484 int err, ret = 0;
1485 struct buffer_head *next;
1487 for (bh = head, block_start = 0;
1488 ret == 0 && (bh != head || !block_start);
1489 block_start = block_end, bh = next) {
1490 next = bh->b_this_page;
1491 block_end = block_start + blocksize;
1492 if (block_end <= from || block_start >= to) {
1493 if (partial && !buffer_uptodate(bh))
1494 *partial = 1;
1495 continue;
1497 err = (*fn)(handle, bh);
1498 if (!ret)
1499 ret = err;
1501 return ret;
1505 * To preserve ordering, it is essential that the hole instantiation and
1506 * the data write be encapsulated in a single transaction. We cannot
1507 * close off a transaction and start a new one between the ext4_get_block()
1508 * and the commit_write(). So doing the jbd2_journal_start at the start of
1509 * prepare_write() is the right place.
1511 * Also, this function can nest inside ext4_writepage() ->
1512 * block_write_full_page(). In that case, we *know* that ext4_writepage()
1513 * has generated enough buffer credits to do the whole page. So we won't
1514 * block on the journal in that case, which is good, because the caller may
1515 * be PF_MEMALLOC.
1517 * By accident, ext4 can be reentered when a transaction is open via
1518 * quota file writes. If we were to commit the transaction while thus
1519 * reentered, there can be a deadlock - we would be holding a quota
1520 * lock, and the commit would never complete if another thread had a
1521 * transaction open and was blocking on the quota lock - a ranking
1522 * violation.
1524 * So what we do is to rely on the fact that jbd2_journal_stop/journal_start
1525 * will _not_ run commit under these circumstances because handle->h_ref
1526 * is elevated. We'll still have enough credits for the tiny quotafile
1527 * write.
1529 static int do_journal_get_write_access(handle_t *handle,
1530 struct buffer_head *bh)
1532 int dirty = buffer_dirty(bh);
1533 int ret;
1535 if (!buffer_mapped(bh) || buffer_freed(bh))
1536 return 0;
1538 * __block_prepare_write() could have dirtied some buffers. Clean
1539 * the dirty bit as jbd2_journal_get_write_access() could complain
1540 * otherwise about fs integrity issues. Setting of the dirty bit
1541 * by __block_prepare_write() isn't a real problem here as we clear
1542 * the bit before releasing a page lock and thus writeback cannot
1543 * ever write the buffer.
1545 if (dirty)
1546 clear_buffer_dirty(bh);
1547 ret = ext4_journal_get_write_access(handle, bh);
1548 if (!ret && dirty)
1549 ret = ext4_handle_dirty_metadata(handle, NULL, bh);
1550 return ret;
1554 * Truncate blocks that were not used by write. We have to truncate the
1555 * pagecache as well so that corresponding buffers get properly unmapped.
1557 static void ext4_truncate_failed_write(struct inode *inode)
1559 truncate_inode_pages(inode->i_mapping, inode->i_size);
1560 ext4_truncate(inode);
1563 static int ext4_get_block_write(struct inode *inode, sector_t iblock,
1564 struct buffer_head *bh_result, int create);
1565 static int ext4_write_begin(struct file *file, struct address_space *mapping,
1566 loff_t pos, unsigned len, unsigned flags,
1567 struct page **pagep, void **fsdata)
1569 struct inode *inode = mapping->host;
1570 int ret, needed_blocks;
1571 handle_t *handle;
1572 int retries = 0;
1573 struct page *page;
1574 pgoff_t index;
1575 unsigned from, to;
1577 trace_ext4_write_begin(inode, pos, len, flags);
1579 * Reserve one block more for addition to orphan list in case
1580 * we allocate blocks but write fails for some reason
1582 needed_blocks = ext4_writepage_trans_blocks(inode) + 1;
1583 index = pos >> PAGE_CACHE_SHIFT;
1584 from = pos & (PAGE_CACHE_SIZE - 1);
1585 to = from + len;
1587 retry:
1588 handle = ext4_journal_start(inode, needed_blocks);
1589 if (IS_ERR(handle)) {
1590 ret = PTR_ERR(handle);
1591 goto out;
1594 /* We cannot recurse into the filesystem as the transaction is already
1595 * started */
1596 flags |= AOP_FLAG_NOFS;
1598 page = grab_cache_page_write_begin(mapping, index, flags);
1599 if (!page) {
1600 ext4_journal_stop(handle);
1601 ret = -ENOMEM;
1602 goto out;
1604 *pagep = page;
1606 if (ext4_should_dioread_nolock(inode))
1607 ret = __block_write_begin(page, pos, len, ext4_get_block_write);
1608 else
1609 ret = __block_write_begin(page, pos, len, ext4_get_block);
1611 if (!ret && ext4_should_journal_data(inode)) {
1612 ret = walk_page_buffers(handle, page_buffers(page),
1613 from, to, NULL, do_journal_get_write_access);
1616 if (ret) {
1617 unlock_page(page);
1618 page_cache_release(page);
1620 * __block_write_begin may have instantiated a few blocks
1621 * outside i_size. Trim these off again. Don't need
1622 * i_size_read because we hold i_mutex.
1624 * Add inode to orphan list in case we crash before
1625 * truncate finishes
1627 if (pos + len > inode->i_size && ext4_can_truncate(inode))
1628 ext4_orphan_add(handle, inode);
1630 ext4_journal_stop(handle);
1631 if (pos + len > inode->i_size) {
1632 ext4_truncate_failed_write(inode);
1634 * If truncate failed early the inode might
1635 * still be on the orphan list; we need to
1636 * make sure the inode is removed from the
1637 * orphan list in that case.
1639 if (inode->i_nlink)
1640 ext4_orphan_del(NULL, inode);
1644 if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
1645 goto retry;
1646 out:
1647 return ret;
1650 /* For write_end() in data=journal mode */
1651 static int write_end_fn(handle_t *handle, struct buffer_head *bh)
1653 if (!buffer_mapped(bh) || buffer_freed(bh))
1654 return 0;
1655 set_buffer_uptodate(bh);
1656 return ext4_handle_dirty_metadata(handle, NULL, bh);
1659 static int ext4_generic_write_end(struct file *file,
1660 struct address_space *mapping,
1661 loff_t pos, unsigned len, unsigned copied,
1662 struct page *page, void *fsdata)
1664 int i_size_changed = 0;
1665 struct inode *inode = mapping->host;
1666 handle_t *handle = ext4_journal_current_handle();
1668 copied = block_write_end(file, mapping, pos, len, copied, page, fsdata);
1671 * No need to use i_size_read() here, the i_size
1672 * cannot change under us because we hold i_mutex.
1674 * But it's important to update i_size while still holding page lock:
1675 * page writeout could otherwise come in and zero beyond i_size.
1677 if (pos + copied > inode->i_size) {
1678 i_size_write(inode, pos + copied);
1679 i_size_changed = 1;
1682 if (pos + copied > EXT4_I(inode)->i_disksize) {
1683 /* We need to mark inode dirty even if
1684 * new_i_size is less that inode->i_size
1685 * bu greater than i_disksize.(hint delalloc)
1687 ext4_update_i_disksize(inode, (pos + copied));
1688 i_size_changed = 1;
1690 unlock_page(page);
1691 page_cache_release(page);
1694 * Don't mark the inode dirty under page lock. First, it unnecessarily
1695 * makes the holding time of page lock longer. Second, it forces lock
1696 * ordering of page lock and transaction start for journaling
1697 * filesystems.
1699 if (i_size_changed)
1700 ext4_mark_inode_dirty(handle, inode);
1702 return copied;
1706 * We need to pick up the new inode size which generic_commit_write gave us
1707 * `file' can be NULL - eg, when called from page_symlink().
1709 * ext4 never places buffers on inode->i_mapping->private_list. metadata
1710 * buffers are managed internally.
1712 static int ext4_ordered_write_end(struct file *file,
1713 struct address_space *mapping,
1714 loff_t pos, unsigned len, unsigned copied,
1715 struct page *page, void *fsdata)
1717 handle_t *handle = ext4_journal_current_handle();
1718 struct inode *inode = mapping->host;
1719 int ret = 0, ret2;
1721 trace_ext4_ordered_write_end(inode, pos, len, copied);
1722 ret = ext4_jbd2_file_inode(handle, inode);
1724 if (ret == 0) {
1725 ret2 = ext4_generic_write_end(file, mapping, pos, len, copied,
1726 page, fsdata);
1727 copied = ret2;
1728 if (pos + len > inode->i_size && ext4_can_truncate(inode))
1729 /* if we have allocated more blocks and copied
1730 * less. We will have blocks allocated outside
1731 * inode->i_size. So truncate them
1733 ext4_orphan_add(handle, inode);
1734 if (ret2 < 0)
1735 ret = ret2;
1737 ret2 = ext4_journal_stop(handle);
1738 if (!ret)
1739 ret = ret2;
1741 if (pos + len > inode->i_size) {
1742 ext4_truncate_failed_write(inode);
1744 * If truncate failed early the inode might still be
1745 * on the orphan list; we need to make sure the inode
1746 * is removed from the orphan list in that case.
1748 if (inode->i_nlink)
1749 ext4_orphan_del(NULL, inode);
1753 return ret ? ret : copied;
1756 static int ext4_writeback_write_end(struct file *file,
1757 struct address_space *mapping,
1758 loff_t pos, unsigned len, unsigned copied,
1759 struct page *page, void *fsdata)
1761 handle_t *handle = ext4_journal_current_handle();
1762 struct inode *inode = mapping->host;
1763 int ret = 0, ret2;
1765 trace_ext4_writeback_write_end(inode, pos, len, copied);
1766 ret2 = ext4_generic_write_end(file, mapping, pos, len, copied,
1767 page, fsdata);
1768 copied = ret2;
1769 if (pos + len > inode->i_size && ext4_can_truncate(inode))
1770 /* if we have allocated more blocks and copied
1771 * less. We will have blocks allocated outside
1772 * inode->i_size. So truncate them
1774 ext4_orphan_add(handle, inode);
1776 if (ret2 < 0)
1777 ret = ret2;
1779 ret2 = ext4_journal_stop(handle);
1780 if (!ret)
1781 ret = ret2;
1783 if (pos + len > inode->i_size) {
1784 ext4_truncate_failed_write(inode);
1786 * If truncate failed early the inode might still be
1787 * on the orphan list; we need to make sure the inode
1788 * is removed from the orphan list in that case.
1790 if (inode->i_nlink)
1791 ext4_orphan_del(NULL, inode);
1794 return ret ? ret : copied;
1797 static int ext4_journalled_write_end(struct file *file,
1798 struct address_space *mapping,
1799 loff_t pos, unsigned len, unsigned copied,
1800 struct page *page, void *fsdata)
1802 handle_t *handle = ext4_journal_current_handle();
1803 struct inode *inode = mapping->host;
1804 int ret = 0, ret2;
1805 int partial = 0;
1806 unsigned from, to;
1807 loff_t new_i_size;
1809 trace_ext4_journalled_write_end(inode, pos, len, copied);
1810 from = pos & (PAGE_CACHE_SIZE - 1);
1811 to = from + len;
1813 if (copied < len) {
1814 if (!PageUptodate(page))
1815 copied = 0;
1816 page_zero_new_buffers(page, from+copied, to);
1819 ret = walk_page_buffers(handle, page_buffers(page), from,
1820 to, &partial, write_end_fn);
1821 if (!partial)
1822 SetPageUptodate(page);
1823 new_i_size = pos + copied;
1824 if (new_i_size > inode->i_size)
1825 i_size_write(inode, pos+copied);
1826 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
1827 if (new_i_size > EXT4_I(inode)->i_disksize) {
1828 ext4_update_i_disksize(inode, new_i_size);
1829 ret2 = ext4_mark_inode_dirty(handle, inode);
1830 if (!ret)
1831 ret = ret2;
1834 unlock_page(page);
1835 page_cache_release(page);
1836 if (pos + len > inode->i_size && ext4_can_truncate(inode))
1837 /* if we have allocated more blocks and copied
1838 * less. We will have blocks allocated outside
1839 * inode->i_size. So truncate them
1841 ext4_orphan_add(handle, inode);
1843 ret2 = ext4_journal_stop(handle);
1844 if (!ret)
1845 ret = ret2;
1846 if (pos + len > inode->i_size) {
1847 ext4_truncate_failed_write(inode);
1849 * If truncate failed early the inode might still be
1850 * on the orphan list; we need to make sure the inode
1851 * is removed from the orphan list in that case.
1853 if (inode->i_nlink)
1854 ext4_orphan_del(NULL, inode);
1857 return ret ? ret : copied;
1861 * Reserve a single block located at lblock
1863 static int ext4_da_reserve_space(struct inode *inode, sector_t lblock)
1865 int retries = 0;
1866 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1867 struct ext4_inode_info *ei = EXT4_I(inode);
1868 unsigned long md_needed;
1869 int ret;
1872 * recalculate the amount of metadata blocks to reserve
1873 * in order to allocate nrblocks
1874 * worse case is one extent per block
1876 repeat:
1877 spin_lock(&ei->i_block_reservation_lock);
1878 md_needed = ext4_calc_metadata_amount(inode, lblock);
1879 trace_ext4_da_reserve_space(inode, md_needed);
1880 spin_unlock(&ei->i_block_reservation_lock);
1883 * We will charge metadata quota at writeout time; this saves
1884 * us from metadata over-estimation, though we may go over by
1885 * a small amount in the end. Here we just reserve for data.
1887 ret = dquot_reserve_block(inode, 1);
1888 if (ret)
1889 return ret;
1891 * We do still charge estimated metadata to the sb though;
1892 * we cannot afford to run out of free blocks.
1894 if (ext4_claim_free_blocks(sbi, md_needed + 1)) {
1895 dquot_release_reservation_block(inode, 1);
1896 if (ext4_should_retry_alloc(inode->i_sb, &retries)) {
1897 yield();
1898 goto repeat;
1900 return -ENOSPC;
1902 spin_lock(&ei->i_block_reservation_lock);
1903 ei->i_reserved_data_blocks++;
1904 ei->i_reserved_meta_blocks += md_needed;
1905 spin_unlock(&ei->i_block_reservation_lock);
1907 return 0; /* success */
1910 static void ext4_da_release_space(struct inode *inode, int to_free)
1912 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1913 struct ext4_inode_info *ei = EXT4_I(inode);
1915 if (!to_free)
1916 return; /* Nothing to release, exit */
1918 spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
1920 trace_ext4_da_release_space(inode, to_free);
1921 if (unlikely(to_free > ei->i_reserved_data_blocks)) {
1923 * if there aren't enough reserved blocks, then the
1924 * counter is messed up somewhere. Since this
1925 * function is called from invalidate page, it's
1926 * harmless to return without any action.
1928 ext4_msg(inode->i_sb, KERN_NOTICE, "ext4_da_release_space: "
1929 "ino %lu, to_free %d with only %d reserved "
1930 "data blocks\n", inode->i_ino, to_free,
1931 ei->i_reserved_data_blocks);
1932 WARN_ON(1);
1933 to_free = ei->i_reserved_data_blocks;
1935 ei->i_reserved_data_blocks -= to_free;
1937 if (ei->i_reserved_data_blocks == 0) {
1939 * We can release all of the reserved metadata blocks
1940 * only when we have written all of the delayed
1941 * allocation blocks.
1943 percpu_counter_sub(&sbi->s_dirtyblocks_counter,
1944 ei->i_reserved_meta_blocks);
1945 ei->i_reserved_meta_blocks = 0;
1946 ei->i_da_metadata_calc_len = 0;
1949 /* update fs dirty data blocks counter */
1950 percpu_counter_sub(&sbi->s_dirtyblocks_counter, to_free);
1952 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
1954 dquot_release_reservation_block(inode, to_free);
1957 static void ext4_da_page_release_reservation(struct page *page,
1958 unsigned long offset)
1960 int to_release = 0;
1961 struct buffer_head *head, *bh;
1962 unsigned int curr_off = 0;
1964 head = page_buffers(page);
1965 bh = head;
1966 do {
1967 unsigned int next_off = curr_off + bh->b_size;
1969 if ((offset <= curr_off) && (buffer_delay(bh))) {
1970 to_release++;
1971 clear_buffer_delay(bh);
1973 curr_off = next_off;
1974 } while ((bh = bh->b_this_page) != head);
1975 ext4_da_release_space(page->mapping->host, to_release);
1979 * Delayed allocation stuff
1983 * mpage_da_submit_io - walks through extent of pages and try to write
1984 * them with writepage() call back
1986 * @mpd->inode: inode
1987 * @mpd->first_page: first page of the extent
1988 * @mpd->next_page: page after the last page of the extent
1990 * By the time mpage_da_submit_io() is called we expect all blocks
1991 * to be allocated. this may be wrong if allocation failed.
1993 * As pages are already locked by write_cache_pages(), we can't use it
1995 static int mpage_da_submit_io(struct mpage_da_data *mpd)
1997 long pages_skipped;
1998 struct pagevec pvec;
1999 unsigned long index, end;
2000 int ret = 0, err, nr_pages, i;
2001 struct inode *inode = mpd->inode;
2002 struct address_space *mapping = inode->i_mapping;
2004 BUG_ON(mpd->next_page <= mpd->first_page);
2006 * We need to start from the first_page to the next_page - 1
2007 * to make sure we also write the mapped dirty buffer_heads.
2008 * If we look at mpd->b_blocknr we would only be looking
2009 * at the currently mapped buffer_heads.
2011 index = mpd->first_page;
2012 end = mpd->next_page - 1;
2014 pagevec_init(&pvec, 0);
2015 while (index <= end) {
2016 nr_pages = pagevec_lookup(&pvec, mapping, index, PAGEVEC_SIZE);
2017 if (nr_pages == 0)
2018 break;
2019 for (i = 0; i < nr_pages; i++) {
2020 struct page *page = pvec.pages[i];
2022 index = page->index;
2023 if (index > end)
2024 break;
2025 index++;
2027 BUG_ON(!PageLocked(page));
2028 BUG_ON(PageWriteback(page));
2030 pages_skipped = mpd->wbc->pages_skipped;
2031 err = mapping->a_ops->writepage(page, mpd->wbc);
2032 if (!err && (pages_skipped == mpd->wbc->pages_skipped))
2034 * have successfully written the page
2035 * without skipping the same
2037 mpd->pages_written++;
2038 if (ret == 0)
2039 ret = err;
2041 pagevec_release(&pvec);
2043 return ret;
2047 * mpage_put_bnr_to_bhs - walk blocks and assign them actual numbers
2049 * the function goes through all passed space and put actual disk
2050 * block numbers into buffer heads, dropping BH_Delay and BH_Unwritten
2052 static void mpage_put_bnr_to_bhs(struct mpage_da_data *mpd,
2053 struct ext4_map_blocks *map)
2055 struct inode *inode = mpd->inode;
2056 struct address_space *mapping = inode->i_mapping;
2057 int blocks = map->m_len;
2058 sector_t pblock = map->m_pblk, cur_logical;
2059 struct buffer_head *head, *bh;
2060 pgoff_t index, end;
2061 struct pagevec pvec;
2062 int nr_pages, i;
2064 index = map->m_lblk >> (PAGE_CACHE_SHIFT - inode->i_blkbits);
2065 end = (map->m_lblk + blocks - 1) >> (PAGE_CACHE_SHIFT - inode->i_blkbits);
2066 cur_logical = index << (PAGE_CACHE_SHIFT - inode->i_blkbits);
2068 pagevec_init(&pvec, 0);
2070 while (index <= end) {
2071 nr_pages = pagevec_lookup(&pvec, mapping, index, PAGEVEC_SIZE);
2072 if (nr_pages == 0)
2073 break;
2074 for (i = 0; i < nr_pages; i++) {
2075 struct page *page = pvec.pages[i];
2077 index = page->index;
2078 if (index > end)
2079 break;
2080 index++;
2082 BUG_ON(!PageLocked(page));
2083 BUG_ON(PageWriteback(page));
2084 BUG_ON(!page_has_buffers(page));
2086 bh = page_buffers(page);
2087 head = bh;
2089 /* skip blocks out of the range */
2090 do {
2091 if (cur_logical >= map->m_lblk)
2092 break;
2093 cur_logical++;
2094 } while ((bh = bh->b_this_page) != head);
2096 do {
2097 if (cur_logical >= map->m_lblk + blocks)
2098 break;
2100 if (buffer_delay(bh) || buffer_unwritten(bh)) {
2102 BUG_ON(bh->b_bdev != inode->i_sb->s_bdev);
2104 if (buffer_delay(bh)) {
2105 clear_buffer_delay(bh);
2106 bh->b_blocknr = pblock;
2107 } else {
2109 * unwritten already should have
2110 * blocknr assigned. Verify that
2112 clear_buffer_unwritten(bh);
2113 BUG_ON(bh->b_blocknr != pblock);
2116 } else if (buffer_mapped(bh))
2117 BUG_ON(bh->b_blocknr != pblock);
2119 if (map->m_flags & EXT4_MAP_UNINIT)
2120 set_buffer_uninit(bh);
2121 cur_logical++;
2122 pblock++;
2123 } while ((bh = bh->b_this_page) != head);
2125 pagevec_release(&pvec);
2130 static void ext4_da_block_invalidatepages(struct mpage_da_data *mpd,
2131 sector_t logical, long blk_cnt)
2133 int nr_pages, i;
2134 pgoff_t index, end;
2135 struct pagevec pvec;
2136 struct inode *inode = mpd->inode;
2137 struct address_space *mapping = inode->i_mapping;
2139 index = logical >> (PAGE_CACHE_SHIFT - inode->i_blkbits);
2140 end = (logical + blk_cnt - 1) >>
2141 (PAGE_CACHE_SHIFT - inode->i_blkbits);
2142 while (index <= end) {
2143 nr_pages = pagevec_lookup(&pvec, mapping, index, PAGEVEC_SIZE);
2144 if (nr_pages == 0)
2145 break;
2146 for (i = 0; i < nr_pages; i++) {
2147 struct page *page = pvec.pages[i];
2148 if (page->index > end)
2149 break;
2150 BUG_ON(!PageLocked(page));
2151 BUG_ON(PageWriteback(page));
2152 block_invalidatepage(page, 0);
2153 ClearPageUptodate(page);
2154 unlock_page(page);
2156 index = pvec.pages[nr_pages - 1]->index + 1;
2157 pagevec_release(&pvec);
2159 return;
2162 static void ext4_print_free_blocks(struct inode *inode)
2164 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
2165 printk(KERN_CRIT "Total free blocks count %lld\n",
2166 ext4_count_free_blocks(inode->i_sb));
2167 printk(KERN_CRIT "Free/Dirty block details\n");
2168 printk(KERN_CRIT "free_blocks=%lld\n",
2169 (long long) percpu_counter_sum(&sbi->s_freeblocks_counter));
2170 printk(KERN_CRIT "dirty_blocks=%lld\n",
2171 (long long) percpu_counter_sum(&sbi->s_dirtyblocks_counter));
2172 printk(KERN_CRIT "Block reservation details\n");
2173 printk(KERN_CRIT "i_reserved_data_blocks=%u\n",
2174 EXT4_I(inode)->i_reserved_data_blocks);
2175 printk(KERN_CRIT "i_reserved_meta_blocks=%u\n",
2176 EXT4_I(inode)->i_reserved_meta_blocks);
2177 return;
2181 * mpage_da_map_blocks - go through given space
2183 * @mpd - bh describing space
2185 * The function skips space we know is already mapped to disk blocks.
2188 static int mpage_da_map_blocks(struct mpage_da_data *mpd)
2190 int err, blks, get_blocks_flags;
2191 struct ext4_map_blocks map;
2192 sector_t next = mpd->b_blocknr;
2193 unsigned max_blocks = mpd->b_size >> mpd->inode->i_blkbits;
2194 loff_t disksize = EXT4_I(mpd->inode)->i_disksize;
2195 handle_t *handle = NULL;
2198 * We consider only non-mapped and non-allocated blocks
2200 if ((mpd->b_state & (1 << BH_Mapped)) &&
2201 !(mpd->b_state & (1 << BH_Delay)) &&
2202 !(mpd->b_state & (1 << BH_Unwritten)))
2203 return 0;
2206 * If we didn't accumulate anything to write simply return
2208 if (!mpd->b_size)
2209 return 0;
2211 handle = ext4_journal_current_handle();
2212 BUG_ON(!handle);
2215 * Call ext4_map_blocks() to allocate any delayed allocation
2216 * blocks, or to convert an uninitialized extent to be
2217 * initialized (in the case where we have written into
2218 * one or more preallocated blocks).
2220 * We pass in the magic EXT4_GET_BLOCKS_DELALLOC_RESERVE to
2221 * indicate that we are on the delayed allocation path. This
2222 * affects functions in many different parts of the allocation
2223 * call path. This flag exists primarily because we don't
2224 * want to change *many* call functions, so ext4_map_blocks()
2225 * will set the magic i_delalloc_reserved_flag once the
2226 * inode's allocation semaphore is taken.
2228 * If the blocks in questions were delalloc blocks, set
2229 * EXT4_GET_BLOCKS_DELALLOC_RESERVE so the delalloc accounting
2230 * variables are updated after the blocks have been allocated.
2232 map.m_lblk = next;
2233 map.m_len = max_blocks;
2234 get_blocks_flags = EXT4_GET_BLOCKS_CREATE;
2235 if (ext4_should_dioread_nolock(mpd->inode))
2236 get_blocks_flags |= EXT4_GET_BLOCKS_IO_CREATE_EXT;
2237 if (mpd->b_state & (1 << BH_Delay))
2238 get_blocks_flags |= EXT4_GET_BLOCKS_DELALLOC_RESERVE;
2240 blks = ext4_map_blocks(handle, mpd->inode, &map, get_blocks_flags);
2241 if (blks < 0) {
2242 struct super_block *sb = mpd->inode->i_sb;
2244 err = blks;
2246 * If get block returns with error we simply
2247 * return. Later writepage will redirty the page and
2248 * writepages will find the dirty page again
2250 if (err == -EAGAIN)
2251 return 0;
2253 if (err == -ENOSPC &&
2254 ext4_count_free_blocks(sb)) {
2255 mpd->retval = err;
2256 return 0;
2260 * get block failure will cause us to loop in
2261 * writepages, because a_ops->writepage won't be able
2262 * to make progress. The page will be redirtied by
2263 * writepage and writepages will again try to write
2264 * the same.
2266 if (!(EXT4_SB(sb)->s_mount_flags & EXT4_MF_FS_ABORTED)) {
2267 ext4_msg(sb, KERN_CRIT,
2268 "delayed block allocation failed for inode %lu "
2269 "at logical offset %llu with max blocks %zd "
2270 "with error %d", mpd->inode->i_ino,
2271 (unsigned long long) next,
2272 mpd->b_size >> mpd->inode->i_blkbits, err);
2273 ext4_msg(sb, KERN_CRIT,
2274 "This should not happen!! Data will be lost\n");
2275 if (err == -ENOSPC)
2276 ext4_print_free_blocks(mpd->inode);
2278 /* invalidate all the pages */
2279 ext4_da_block_invalidatepages(mpd, next,
2280 mpd->b_size >> mpd->inode->i_blkbits);
2281 return err;
2283 BUG_ON(blks == 0);
2285 if (map.m_flags & EXT4_MAP_NEW) {
2286 struct block_device *bdev = mpd->inode->i_sb->s_bdev;
2287 int i;
2289 for (i = 0; i < map.m_len; i++)
2290 unmap_underlying_metadata(bdev, map.m_pblk + i);
2294 * If blocks are delayed marked, we need to
2295 * put actual blocknr and drop delayed bit
2297 if ((mpd->b_state & (1 << BH_Delay)) ||
2298 (mpd->b_state & (1 << BH_Unwritten)))
2299 mpage_put_bnr_to_bhs(mpd, &map);
2301 if (ext4_should_order_data(mpd->inode)) {
2302 err = ext4_jbd2_file_inode(handle, mpd->inode);
2303 if (err)
2304 return err;
2308 * Update on-disk size along with block allocation.
2310 disksize = ((loff_t) next + blks) << mpd->inode->i_blkbits;
2311 if (disksize > i_size_read(mpd->inode))
2312 disksize = i_size_read(mpd->inode);
2313 if (disksize > EXT4_I(mpd->inode)->i_disksize) {
2314 ext4_update_i_disksize(mpd->inode, disksize);
2315 return ext4_mark_inode_dirty(handle, mpd->inode);
2318 return 0;
2321 #define BH_FLAGS ((1 << BH_Uptodate) | (1 << BH_Mapped) | \
2322 (1 << BH_Delay) | (1 << BH_Unwritten))
2325 * mpage_add_bh_to_extent - try to add one more block to extent of blocks
2327 * @mpd->lbh - extent of blocks
2328 * @logical - logical number of the block in the file
2329 * @bh - bh of the block (used to access block's state)
2331 * the function is used to collect contig. blocks in same state
2333 static void mpage_add_bh_to_extent(struct mpage_da_data *mpd,
2334 sector_t logical, size_t b_size,
2335 unsigned long b_state)
2337 sector_t next;
2338 int nrblocks = mpd->b_size >> mpd->inode->i_blkbits;
2340 if (nrblocks >= 8*1024*1024/mpd->inode->i_sb->s_blocksize)
2341 goto flush_it;
2343 /* check if thereserved journal credits might overflow */
2344 if (!(ext4_test_inode_flag(mpd->inode, EXT4_INODE_EXTENTS))) {
2345 if (nrblocks >= EXT4_MAX_TRANS_DATA) {
2347 * With non-extent format we are limited by the journal
2348 * credit available. Total credit needed to insert
2349 * nrblocks contiguous blocks is dependent on the
2350 * nrblocks. So limit nrblocks.
2352 goto flush_it;
2353 } else if ((nrblocks + (b_size >> mpd->inode->i_blkbits)) >
2354 EXT4_MAX_TRANS_DATA) {
2356 * Adding the new buffer_head would make it cross the
2357 * allowed limit for which we have journal credit
2358 * reserved. So limit the new bh->b_size
2360 b_size = (EXT4_MAX_TRANS_DATA - nrblocks) <<
2361 mpd->inode->i_blkbits;
2362 /* we will do mpage_da_submit_io in the next loop */
2366 * First block in the extent
2368 if (mpd->b_size == 0) {
2369 mpd->b_blocknr = logical;
2370 mpd->b_size = b_size;
2371 mpd->b_state = b_state & BH_FLAGS;
2372 return;
2375 next = mpd->b_blocknr + nrblocks;
2377 * Can we merge the block to our big extent?
2379 if (logical == next && (b_state & BH_FLAGS) == mpd->b_state) {
2380 mpd->b_size += b_size;
2381 return;
2384 flush_it:
2386 * We couldn't merge the block to our extent, so we
2387 * need to flush current extent and start new one
2389 if (mpage_da_map_blocks(mpd) == 0)
2390 mpage_da_submit_io(mpd);
2391 mpd->io_done = 1;
2392 return;
2395 static int ext4_bh_delay_or_unwritten(handle_t *handle, struct buffer_head *bh)
2397 return (buffer_delay(bh) || buffer_unwritten(bh)) && buffer_dirty(bh);
2401 * __mpage_da_writepage - finds extent of pages and blocks
2403 * @page: page to consider
2404 * @wbc: not used, we just follow rules
2405 * @data: context
2407 * The function finds extents of pages and scan them for all blocks.
2409 static int __mpage_da_writepage(struct page *page,
2410 struct writeback_control *wbc, void *data)
2412 struct mpage_da_data *mpd = data;
2413 struct inode *inode = mpd->inode;
2414 struct buffer_head *bh, *head;
2415 sector_t logical;
2418 * Can we merge this page to current extent?
2420 if (mpd->next_page != page->index) {
2422 * Nope, we can't. So, we map non-allocated blocks
2423 * and start IO on them using writepage()
2425 if (mpd->next_page != mpd->first_page) {
2426 if (mpage_da_map_blocks(mpd) == 0)
2427 mpage_da_submit_io(mpd);
2429 * skip rest of the page in the page_vec
2431 mpd->io_done = 1;
2432 redirty_page_for_writepage(wbc, page);
2433 unlock_page(page);
2434 return MPAGE_DA_EXTENT_TAIL;
2438 * Start next extent of pages ...
2440 mpd->first_page = page->index;
2443 * ... and blocks
2445 mpd->b_size = 0;
2446 mpd->b_state = 0;
2447 mpd->b_blocknr = 0;
2450 mpd->next_page = page->index + 1;
2451 logical = (sector_t) page->index <<
2452 (PAGE_CACHE_SHIFT - inode->i_blkbits);
2454 if (!page_has_buffers(page)) {
2455 mpage_add_bh_to_extent(mpd, logical, PAGE_CACHE_SIZE,
2456 (1 << BH_Dirty) | (1 << BH_Uptodate));
2457 if (mpd->io_done)
2458 return MPAGE_DA_EXTENT_TAIL;
2459 } else {
2461 * Page with regular buffer heads, just add all dirty ones
2463 head = page_buffers(page);
2464 bh = head;
2465 do {
2466 BUG_ON(buffer_locked(bh));
2468 * We need to try to allocate
2469 * unmapped blocks in the same page.
2470 * Otherwise we won't make progress
2471 * with the page in ext4_writepage
2473 if (ext4_bh_delay_or_unwritten(NULL, bh)) {
2474 mpage_add_bh_to_extent(mpd, logical,
2475 bh->b_size,
2476 bh->b_state);
2477 if (mpd->io_done)
2478 return MPAGE_DA_EXTENT_TAIL;
2479 } else if (buffer_dirty(bh) && (buffer_mapped(bh))) {
2481 * mapped dirty buffer. We need to update
2482 * the b_state because we look at
2483 * b_state in mpage_da_map_blocks. We don't
2484 * update b_size because if we find an
2485 * unmapped buffer_head later we need to
2486 * use the b_state flag of that buffer_head.
2488 if (mpd->b_size == 0)
2489 mpd->b_state = bh->b_state & BH_FLAGS;
2491 logical++;
2492 } while ((bh = bh->b_this_page) != head);
2495 return 0;
2499 * This is a special get_blocks_t callback which is used by
2500 * ext4_da_write_begin(). It will either return mapped block or
2501 * reserve space for a single block.
2503 * For delayed buffer_head we have BH_Mapped, BH_New, BH_Delay set.
2504 * We also have b_blocknr = -1 and b_bdev initialized properly
2506 * For unwritten buffer_head we have BH_Mapped, BH_New, BH_Unwritten set.
2507 * We also have b_blocknr = physicalblock mapping unwritten extent and b_bdev
2508 * initialized properly.
2510 static int ext4_da_get_block_prep(struct inode *inode, sector_t iblock,
2511 struct buffer_head *bh, int create)
2513 struct ext4_map_blocks map;
2514 int ret = 0;
2515 sector_t invalid_block = ~((sector_t) 0xffff);
2517 if (invalid_block < ext4_blocks_count(EXT4_SB(inode->i_sb)->s_es))
2518 invalid_block = ~0;
2520 BUG_ON(create == 0);
2521 BUG_ON(bh->b_size != inode->i_sb->s_blocksize);
2523 map.m_lblk = iblock;
2524 map.m_len = 1;
2527 * first, we need to know whether the block is allocated already
2528 * preallocated blocks are unmapped but should treated
2529 * the same as allocated blocks.
2531 ret = ext4_map_blocks(NULL, inode, &map, 0);
2532 if (ret < 0)
2533 return ret;
2534 if (ret == 0) {
2535 if (buffer_delay(bh))
2536 return 0; /* Not sure this could or should happen */
2537 ret = ext4_da_reserve_space(inode, iblock);
2538 if (ret)
2539 /* not enough space to reserve */
2540 return ret;
2542 map_bh(bh, inode->i_sb, invalid_block);
2543 set_buffer_new(bh);
2544 set_buffer_delay(bh);
2545 return 0;
2548 map_bh(bh, inode->i_sb, map.m_pblk);
2549 bh->b_state = (bh->b_state & ~EXT4_MAP_FLAGS) | map.m_flags;
2551 if (buffer_unwritten(bh)) {
2552 /* A delayed write to unwritten bh should be marked
2553 * new and mapped. Mapped ensures that we don't do
2554 * get_block multiple times when we write to the same
2555 * offset and new ensures that we do proper zero out
2556 * for partial write.
2558 set_buffer_new(bh);
2559 set_buffer_mapped(bh);
2561 return 0;
2565 * This function is used as a standard get_block_t calback function
2566 * when there is no desire to allocate any blocks. It is used as a
2567 * callback function for block_prepare_write() and block_write_full_page().
2568 * These functions should only try to map a single block at a time.
2570 * Since this function doesn't do block allocations even if the caller
2571 * requests it by passing in create=1, it is critically important that
2572 * any caller checks to make sure that any buffer heads are returned
2573 * by this function are either all already mapped or marked for
2574 * delayed allocation before calling block_write_full_page(). Otherwise,
2575 * b_blocknr could be left unitialized, and the page write functions will
2576 * be taken by surprise.
2578 static int noalloc_get_block_write(struct inode *inode, sector_t iblock,
2579 struct buffer_head *bh_result, int create)
2581 BUG_ON(bh_result->b_size != inode->i_sb->s_blocksize);
2582 return _ext4_get_block(inode, iblock, bh_result, 0);
2585 static int bget_one(handle_t *handle, struct buffer_head *bh)
2587 get_bh(bh);
2588 return 0;
2591 static int bput_one(handle_t *handle, struct buffer_head *bh)
2593 put_bh(bh);
2594 return 0;
2597 static int __ext4_journalled_writepage(struct page *page,
2598 unsigned int len)
2600 struct address_space *mapping = page->mapping;
2601 struct inode *inode = mapping->host;
2602 struct buffer_head *page_bufs;
2603 handle_t *handle = NULL;
2604 int ret = 0;
2605 int err;
2607 page_bufs = page_buffers(page);
2608 BUG_ON(!page_bufs);
2609 walk_page_buffers(handle, page_bufs, 0, len, NULL, bget_one);
2610 /* As soon as we unlock the page, it can go away, but we have
2611 * references to buffers so we are safe */
2612 unlock_page(page);
2614 handle = ext4_journal_start(inode, ext4_writepage_trans_blocks(inode));
2615 if (IS_ERR(handle)) {
2616 ret = PTR_ERR(handle);
2617 goto out;
2620 ret = walk_page_buffers(handle, page_bufs, 0, len, NULL,
2621 do_journal_get_write_access);
2623 err = walk_page_buffers(handle, page_bufs, 0, len, NULL,
2624 write_end_fn);
2625 if (ret == 0)
2626 ret = err;
2627 err = ext4_journal_stop(handle);
2628 if (!ret)
2629 ret = err;
2631 walk_page_buffers(handle, page_bufs, 0, len, NULL, bput_one);
2632 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
2633 out:
2634 return ret;
2637 static int ext4_set_bh_endio(struct buffer_head *bh, struct inode *inode);
2638 static void ext4_end_io_buffer_write(struct buffer_head *bh, int uptodate);
2641 * Note that we don't need to start a transaction unless we're journaling data
2642 * because we should have holes filled from ext4_page_mkwrite(). We even don't
2643 * need to file the inode to the transaction's list in ordered mode because if
2644 * we are writing back data added by write(), the inode is already there and if
2645 * we are writing back data modified via mmap(), noone guarantees in which
2646 * transaction the data will hit the disk. In case we are journaling data, we
2647 * cannot start transaction directly because transaction start ranks above page
2648 * lock so we have to do some magic.
2650 * This function can get called via...
2651 * - ext4_da_writepages after taking page lock (have journal handle)
2652 * - journal_submit_inode_data_buffers (no journal handle)
2653 * - shrink_page_list via pdflush (no journal handle)
2654 * - grab_page_cache when doing write_begin (have journal handle)
2656 * We don't do any block allocation in this function. If we have page with
2657 * multiple blocks we need to write those buffer_heads that are mapped. This
2658 * is important for mmaped based write. So if we do with blocksize 1K
2659 * truncate(f, 1024);
2660 * a = mmap(f, 0, 4096);
2661 * a[0] = 'a';
2662 * truncate(f, 4096);
2663 * we have in the page first buffer_head mapped via page_mkwrite call back
2664 * but other bufer_heads would be unmapped but dirty(dirty done via the
2665 * do_wp_page). So writepage should write the first block. If we modify
2666 * the mmap area beyond 1024 we will again get a page_fault and the
2667 * page_mkwrite callback will do the block allocation and mark the
2668 * buffer_heads mapped.
2670 * We redirty the page if we have any buffer_heads that is either delay or
2671 * unwritten in the page.
2673 * We can get recursively called as show below.
2675 * ext4_writepage() -> kmalloc() -> __alloc_pages() -> page_launder() ->
2676 * ext4_writepage()
2678 * But since we don't do any block allocation we should not deadlock.
2679 * Page also have the dirty flag cleared so we don't get recurive page_lock.
2681 static int ext4_writepage(struct page *page,
2682 struct writeback_control *wbc)
2684 int ret = 0;
2685 loff_t size;
2686 unsigned int len;
2687 struct buffer_head *page_bufs = NULL;
2688 struct inode *inode = page->mapping->host;
2690 trace_ext4_writepage(inode, page);
2691 size = i_size_read(inode);
2692 if (page->index == size >> PAGE_CACHE_SHIFT)
2693 len = size & ~PAGE_CACHE_MASK;
2694 else
2695 len = PAGE_CACHE_SIZE;
2697 if (page_has_buffers(page)) {
2698 page_bufs = page_buffers(page);
2699 if (walk_page_buffers(NULL, page_bufs, 0, len, NULL,
2700 ext4_bh_delay_or_unwritten)) {
2702 * We don't want to do block allocation
2703 * So redirty the page and return
2704 * We may reach here when we do a journal commit
2705 * via journal_submit_inode_data_buffers.
2706 * If we don't have mapping block we just ignore
2707 * them. We can also reach here via shrink_page_list
2709 redirty_page_for_writepage(wbc, page);
2710 unlock_page(page);
2711 return 0;
2713 } else {
2715 * The test for page_has_buffers() is subtle:
2716 * We know the page is dirty but it lost buffers. That means
2717 * that at some moment in time after write_begin()/write_end()
2718 * has been called all buffers have been clean and thus they
2719 * must have been written at least once. So they are all
2720 * mapped and we can happily proceed with mapping them
2721 * and writing the page.
2723 * Try to initialize the buffer_heads and check whether
2724 * all are mapped and non delay. We don't want to
2725 * do block allocation here.
2727 ret = block_prepare_write(page, 0, len,
2728 noalloc_get_block_write);
2729 if (!ret) {
2730 page_bufs = page_buffers(page);
2731 /* check whether all are mapped and non delay */
2732 if (walk_page_buffers(NULL, page_bufs, 0, len, NULL,
2733 ext4_bh_delay_or_unwritten)) {
2734 redirty_page_for_writepage(wbc, page);
2735 unlock_page(page);
2736 return 0;
2738 } else {
2740 * We can't do block allocation here
2741 * so just redity the page and unlock
2742 * and return
2744 redirty_page_for_writepage(wbc, page);
2745 unlock_page(page);
2746 return 0;
2748 /* now mark the buffer_heads as dirty and uptodate */
2749 block_commit_write(page, 0, len);
2752 if (PageChecked(page) && ext4_should_journal_data(inode)) {
2754 * It's mmapped pagecache. Add buffers and journal it. There
2755 * doesn't seem much point in redirtying the page here.
2757 ClearPageChecked(page);
2758 return __ext4_journalled_writepage(page, len);
2761 if (page_bufs && buffer_uninit(page_bufs)) {
2762 ext4_set_bh_endio(page_bufs, inode);
2763 ret = block_write_full_page_endio(page, noalloc_get_block_write,
2764 wbc, ext4_end_io_buffer_write);
2765 } else
2766 ret = block_write_full_page(page, noalloc_get_block_write,
2767 wbc);
2769 return ret;
2773 * This is called via ext4_da_writepages() to
2774 * calulate the total number of credits to reserve to fit
2775 * a single extent allocation into a single transaction,
2776 * ext4_da_writpeages() will loop calling this before
2777 * the block allocation.
2780 static int ext4_da_writepages_trans_blocks(struct inode *inode)
2782 int max_blocks = EXT4_I(inode)->i_reserved_data_blocks;
2785 * With non-extent format the journal credit needed to
2786 * insert nrblocks contiguous block is dependent on
2787 * number of contiguous block. So we will limit
2788 * number of contiguous block to a sane value
2790 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) &&
2791 (max_blocks > EXT4_MAX_TRANS_DATA))
2792 max_blocks = EXT4_MAX_TRANS_DATA;
2794 return ext4_chunk_trans_blocks(inode, max_blocks);
2798 * write_cache_pages_da - walk the list of dirty pages of the given
2799 * address space and call the callback function (which usually writes
2800 * the pages).
2802 * This is a forked version of write_cache_pages(). Differences:
2803 * Range cyclic is ignored.
2804 * no_nrwrite_index_update is always presumed true
2806 static int write_cache_pages_da(struct address_space *mapping,
2807 struct writeback_control *wbc,
2808 struct mpage_da_data *mpd)
2810 int ret = 0;
2811 int done = 0;
2812 struct pagevec pvec;
2813 int nr_pages;
2814 pgoff_t index;
2815 pgoff_t end; /* Inclusive */
2816 long nr_to_write = wbc->nr_to_write;
2818 pagevec_init(&pvec, 0);
2819 index = wbc->range_start >> PAGE_CACHE_SHIFT;
2820 end = wbc->range_end >> PAGE_CACHE_SHIFT;
2822 while (!done && (index <= end)) {
2823 int i;
2825 nr_pages = pagevec_lookup_tag(&pvec, mapping, &index,
2826 PAGECACHE_TAG_DIRTY,
2827 min(end - index, (pgoff_t)PAGEVEC_SIZE-1) + 1);
2828 if (nr_pages == 0)
2829 break;
2831 for (i = 0; i < nr_pages; i++) {
2832 struct page *page = pvec.pages[i];
2835 * At this point, the page may be truncated or
2836 * invalidated (changing page->mapping to NULL), or
2837 * even swizzled back from swapper_space to tmpfs file
2838 * mapping. However, page->index will not change
2839 * because we have a reference on the page.
2841 if (page->index > end) {
2842 done = 1;
2843 break;
2846 lock_page(page);
2849 * Page truncated or invalidated. We can freely skip it
2850 * then, even for data integrity operations: the page
2851 * has disappeared concurrently, so there could be no
2852 * real expectation of this data interity operation
2853 * even if there is now a new, dirty page at the same
2854 * pagecache address.
2856 if (unlikely(page->mapping != mapping)) {
2857 continue_unlock:
2858 unlock_page(page);
2859 continue;
2862 if (!PageDirty(page)) {
2863 /* someone wrote it for us */
2864 goto continue_unlock;
2867 if (PageWriteback(page)) {
2868 if (wbc->sync_mode != WB_SYNC_NONE)
2869 wait_on_page_writeback(page);
2870 else
2871 goto continue_unlock;
2874 BUG_ON(PageWriteback(page));
2875 if (!clear_page_dirty_for_io(page))
2876 goto continue_unlock;
2878 ret = __mpage_da_writepage(page, wbc, mpd);
2879 if (unlikely(ret)) {
2880 if (ret == AOP_WRITEPAGE_ACTIVATE) {
2881 unlock_page(page);
2882 ret = 0;
2883 } else {
2884 done = 1;
2885 break;
2889 if (nr_to_write > 0) {
2890 nr_to_write--;
2891 if (nr_to_write == 0 &&
2892 wbc->sync_mode == WB_SYNC_NONE) {
2894 * We stop writing back only if we are
2895 * not doing integrity sync. In case of
2896 * integrity sync we have to keep going
2897 * because someone may be concurrently
2898 * dirtying pages, and we might have
2899 * synced a lot of newly appeared dirty
2900 * pages, but have not synced all of the
2901 * old dirty pages.
2903 done = 1;
2904 break;
2908 pagevec_release(&pvec);
2909 cond_resched();
2911 return ret;
2915 static int ext4_da_writepages(struct address_space *mapping,
2916 struct writeback_control *wbc)
2918 pgoff_t index;
2919 int range_whole = 0;
2920 handle_t *handle = NULL;
2921 struct mpage_da_data mpd;
2922 struct inode *inode = mapping->host;
2923 int pages_written = 0;
2924 long pages_skipped;
2925 unsigned int max_pages;
2926 int range_cyclic, cycled = 1, io_done = 0;
2927 int needed_blocks, ret = 0;
2928 long desired_nr_to_write, nr_to_writebump = 0;
2929 loff_t range_start = wbc->range_start;
2930 struct ext4_sb_info *sbi = EXT4_SB(mapping->host->i_sb);
2932 trace_ext4_da_writepages(inode, wbc);
2935 * No pages to write? This is mainly a kludge to avoid starting
2936 * a transaction for special inodes like journal inode on last iput()
2937 * because that could violate lock ordering on umount
2939 if (!mapping->nrpages || !mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
2940 return 0;
2943 * If the filesystem has aborted, it is read-only, so return
2944 * right away instead of dumping stack traces later on that
2945 * will obscure the real source of the problem. We test
2946 * EXT4_MF_FS_ABORTED instead of sb->s_flag's MS_RDONLY because
2947 * the latter could be true if the filesystem is mounted
2948 * read-only, and in that case, ext4_da_writepages should
2949 * *never* be called, so if that ever happens, we would want
2950 * the stack trace.
2952 if (unlikely(sbi->s_mount_flags & EXT4_MF_FS_ABORTED))
2953 return -EROFS;
2955 if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
2956 range_whole = 1;
2958 range_cyclic = wbc->range_cyclic;
2959 if (wbc->range_cyclic) {
2960 index = mapping->writeback_index;
2961 if (index)
2962 cycled = 0;
2963 wbc->range_start = index << PAGE_CACHE_SHIFT;
2964 wbc->range_end = LLONG_MAX;
2965 wbc->range_cyclic = 0;
2966 } else
2967 index = wbc->range_start >> PAGE_CACHE_SHIFT;
2970 * This works around two forms of stupidity. The first is in
2971 * the writeback code, which caps the maximum number of pages
2972 * written to be 1024 pages. This is wrong on multiple
2973 * levels; different architectues have a different page size,
2974 * which changes the maximum amount of data which gets
2975 * written. Secondly, 4 megabytes is way too small. XFS
2976 * forces this value to be 16 megabytes by multiplying
2977 * nr_to_write parameter by four, and then relies on its
2978 * allocator to allocate larger extents to make them
2979 * contiguous. Unfortunately this brings us to the second
2980 * stupidity, which is that ext4's mballoc code only allocates
2981 * at most 2048 blocks. So we force contiguous writes up to
2982 * the number of dirty blocks in the inode, or
2983 * sbi->max_writeback_mb_bump whichever is smaller.
2985 max_pages = sbi->s_max_writeback_mb_bump << (20 - PAGE_CACHE_SHIFT);
2986 if (!range_cyclic && range_whole)
2987 desired_nr_to_write = wbc->nr_to_write * 8;
2988 else
2989 desired_nr_to_write = ext4_num_dirty_pages(inode, index,
2990 max_pages);
2991 if (desired_nr_to_write > max_pages)
2992 desired_nr_to_write = max_pages;
2994 if (wbc->nr_to_write < desired_nr_to_write) {
2995 nr_to_writebump = desired_nr_to_write - wbc->nr_to_write;
2996 wbc->nr_to_write = desired_nr_to_write;
2999 mpd.wbc = wbc;
3000 mpd.inode = mapping->host;
3002 pages_skipped = wbc->pages_skipped;
3004 retry:
3005 while (!ret && wbc->nr_to_write > 0) {
3008 * we insert one extent at a time. So we need
3009 * credit needed for single extent allocation.
3010 * journalled mode is currently not supported
3011 * by delalloc
3013 BUG_ON(ext4_should_journal_data(inode));
3014 needed_blocks = ext4_da_writepages_trans_blocks(inode);
3016 /* start a new transaction*/
3017 handle = ext4_journal_start(inode, needed_blocks);
3018 if (IS_ERR(handle)) {
3019 ret = PTR_ERR(handle);
3020 ext4_msg(inode->i_sb, KERN_CRIT, "%s: jbd2_start: "
3021 "%ld pages, ino %lu; err %d", __func__,
3022 wbc->nr_to_write, inode->i_ino, ret);
3023 goto out_writepages;
3027 * Now call __mpage_da_writepage to find the next
3028 * contiguous region of logical blocks that need
3029 * blocks to be allocated by ext4. We don't actually
3030 * submit the blocks for I/O here, even though
3031 * write_cache_pages thinks it will, and will set the
3032 * pages as clean for write before calling
3033 * __mpage_da_writepage().
3035 mpd.b_size = 0;
3036 mpd.b_state = 0;
3037 mpd.b_blocknr = 0;
3038 mpd.first_page = 0;
3039 mpd.next_page = 0;
3040 mpd.io_done = 0;
3041 mpd.pages_written = 0;
3042 mpd.retval = 0;
3043 ret = write_cache_pages_da(mapping, wbc, &mpd);
3045 * If we have a contiguous extent of pages and we
3046 * haven't done the I/O yet, map the blocks and submit
3047 * them for I/O.
3049 if (!mpd.io_done && mpd.next_page != mpd.first_page) {
3050 if (mpage_da_map_blocks(&mpd) == 0)
3051 mpage_da_submit_io(&mpd);
3052 mpd.io_done = 1;
3053 ret = MPAGE_DA_EXTENT_TAIL;
3055 trace_ext4_da_write_pages(inode, &mpd);
3056 wbc->nr_to_write -= mpd.pages_written;
3058 ext4_journal_stop(handle);
3060 if ((mpd.retval == -ENOSPC) && sbi->s_journal) {
3061 /* commit the transaction which would
3062 * free blocks released in the transaction
3063 * and try again
3065 jbd2_journal_force_commit_nested(sbi->s_journal);
3066 wbc->pages_skipped = pages_skipped;
3067 ret = 0;
3068 } else if (ret == MPAGE_DA_EXTENT_TAIL) {
3070 * got one extent now try with
3071 * rest of the pages
3073 pages_written += mpd.pages_written;
3074 wbc->pages_skipped = pages_skipped;
3075 ret = 0;
3076 io_done = 1;
3077 } else if (wbc->nr_to_write)
3079 * There is no more writeout needed
3080 * or we requested for a noblocking writeout
3081 * and we found the device congested
3083 break;
3085 if (!io_done && !cycled) {
3086 cycled = 1;
3087 index = 0;
3088 wbc->range_start = index << PAGE_CACHE_SHIFT;
3089 wbc->range_end = mapping->writeback_index - 1;
3090 goto retry;
3092 if (pages_skipped != wbc->pages_skipped)
3093 ext4_msg(inode->i_sb, KERN_CRIT,
3094 "This should not happen leaving %s "
3095 "with nr_to_write = %ld ret = %d",
3096 __func__, wbc->nr_to_write, ret);
3098 /* Update index */
3099 index += pages_written;
3100 wbc->range_cyclic = range_cyclic;
3101 if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
3103 * set the writeback_index so that range_cyclic
3104 * mode will write it back later
3106 mapping->writeback_index = index;
3108 out_writepages:
3109 wbc->nr_to_write -= nr_to_writebump;
3110 wbc->range_start = range_start;
3111 trace_ext4_da_writepages_result(inode, wbc, ret, pages_written);
3112 return ret;
3115 #define FALL_BACK_TO_NONDELALLOC 1
3116 static int ext4_nonda_switch(struct super_block *sb)
3118 s64 free_blocks, dirty_blocks;
3119 struct ext4_sb_info *sbi = EXT4_SB(sb);
3122 * switch to non delalloc mode if we are running low
3123 * on free block. The free block accounting via percpu
3124 * counters can get slightly wrong with percpu_counter_batch getting
3125 * accumulated on each CPU without updating global counters
3126 * Delalloc need an accurate free block accounting. So switch
3127 * to non delalloc when we are near to error range.
3129 free_blocks = percpu_counter_read_positive(&sbi->s_freeblocks_counter);
3130 dirty_blocks = percpu_counter_read_positive(&sbi->s_dirtyblocks_counter);
3131 if (2 * free_blocks < 3 * dirty_blocks ||
3132 free_blocks < (dirty_blocks + EXT4_FREEBLOCKS_WATERMARK)) {
3134 * free block count is less than 150% of dirty blocks
3135 * or free blocks is less than watermark
3137 return 1;
3140 * Even if we don't switch but are nearing capacity,
3141 * start pushing delalloc when 1/2 of free blocks are dirty.
3143 if (free_blocks < 2 * dirty_blocks)
3144 writeback_inodes_sb_if_idle(sb);
3146 return 0;
3149 static int ext4_da_write_begin(struct file *file, struct address_space *mapping,
3150 loff_t pos, unsigned len, unsigned flags,
3151 struct page **pagep, void **fsdata)
3153 int ret, retries = 0;
3154 struct page *page;
3155 pgoff_t index;
3156 struct inode *inode = mapping->host;
3157 handle_t *handle;
3159 index = pos >> PAGE_CACHE_SHIFT;
3161 if (ext4_nonda_switch(inode->i_sb)) {
3162 *fsdata = (void *)FALL_BACK_TO_NONDELALLOC;
3163 return ext4_write_begin(file, mapping, pos,
3164 len, flags, pagep, fsdata);
3166 *fsdata = (void *)0;
3167 trace_ext4_da_write_begin(inode, pos, len, flags);
3168 retry:
3170 * With delayed allocation, we don't log the i_disksize update
3171 * if there is delayed block allocation. But we still need
3172 * to journalling the i_disksize update if writes to the end
3173 * of file which has an already mapped buffer.
3175 handle = ext4_journal_start(inode, 1);
3176 if (IS_ERR(handle)) {
3177 ret = PTR_ERR(handle);
3178 goto out;
3180 /* We cannot recurse into the filesystem as the transaction is already
3181 * started */
3182 flags |= AOP_FLAG_NOFS;
3184 page = grab_cache_page_write_begin(mapping, index, flags);
3185 if (!page) {
3186 ext4_journal_stop(handle);
3187 ret = -ENOMEM;
3188 goto out;
3190 *pagep = page;
3192 ret = __block_write_begin(page, pos, len, ext4_da_get_block_prep);
3193 if (ret < 0) {
3194 unlock_page(page);
3195 ext4_journal_stop(handle);
3196 page_cache_release(page);
3198 * block_write_begin may have instantiated a few blocks
3199 * outside i_size. Trim these off again. Don't need
3200 * i_size_read because we hold i_mutex.
3202 if (pos + len > inode->i_size)
3203 ext4_truncate_failed_write(inode);
3206 if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
3207 goto retry;
3208 out:
3209 return ret;
3213 * Check if we should update i_disksize
3214 * when write to the end of file but not require block allocation
3216 static int ext4_da_should_update_i_disksize(struct page *page,
3217 unsigned long offset)
3219 struct buffer_head *bh;
3220 struct inode *inode = page->mapping->host;
3221 unsigned int idx;
3222 int i;
3224 bh = page_buffers(page);
3225 idx = offset >> inode->i_blkbits;
3227 for (i = 0; i < idx; i++)
3228 bh = bh->b_this_page;
3230 if (!buffer_mapped(bh) || (buffer_delay(bh)) || buffer_unwritten(bh))
3231 return 0;
3232 return 1;
3235 static int ext4_da_write_end(struct file *file,
3236 struct address_space *mapping,
3237 loff_t pos, unsigned len, unsigned copied,
3238 struct page *page, void *fsdata)
3240 struct inode *inode = mapping->host;
3241 int ret = 0, ret2;
3242 handle_t *handle = ext4_journal_current_handle();
3243 loff_t new_i_size;
3244 unsigned long start, end;
3245 int write_mode = (int)(unsigned long)fsdata;
3247 if (write_mode == FALL_BACK_TO_NONDELALLOC) {
3248 if (ext4_should_order_data(inode)) {
3249 return ext4_ordered_write_end(file, mapping, pos,
3250 len, copied, page, fsdata);
3251 } else if (ext4_should_writeback_data(inode)) {
3252 return ext4_writeback_write_end(file, mapping, pos,
3253 len, copied, page, fsdata);
3254 } else {
3255 BUG();
3259 trace_ext4_da_write_end(inode, pos, len, copied);
3260 start = pos & (PAGE_CACHE_SIZE - 1);
3261 end = start + copied - 1;
3264 * generic_write_end() will run mark_inode_dirty() if i_size
3265 * changes. So let's piggyback the i_disksize mark_inode_dirty
3266 * into that.
3269 new_i_size = pos + copied;
3270 if (new_i_size > EXT4_I(inode)->i_disksize) {
3271 if (ext4_da_should_update_i_disksize(page, end)) {
3272 down_write(&EXT4_I(inode)->i_data_sem);
3273 if (new_i_size > EXT4_I(inode)->i_disksize) {
3275 * Updating i_disksize when extending file
3276 * without needing block allocation
3278 if (ext4_should_order_data(inode))
3279 ret = ext4_jbd2_file_inode(handle,
3280 inode);
3282 EXT4_I(inode)->i_disksize = new_i_size;
3284 up_write(&EXT4_I(inode)->i_data_sem);
3285 /* We need to mark inode dirty even if
3286 * new_i_size is less that inode->i_size
3287 * bu greater than i_disksize.(hint delalloc)
3289 ext4_mark_inode_dirty(handle, inode);
3292 ret2 = generic_write_end(file, mapping, pos, len, copied,
3293 page, fsdata);
3294 copied = ret2;
3295 if (ret2 < 0)
3296 ret = ret2;
3297 ret2 = ext4_journal_stop(handle);
3298 if (!ret)
3299 ret = ret2;
3301 return ret ? ret : copied;
3304 static void ext4_da_invalidatepage(struct page *page, unsigned long offset)
3307 * Drop reserved blocks
3309 BUG_ON(!PageLocked(page));
3310 if (!page_has_buffers(page))
3311 goto out;
3313 ext4_da_page_release_reservation(page, offset);
3315 out:
3316 ext4_invalidatepage(page, offset);
3318 return;
3322 * Force all delayed allocation blocks to be allocated for a given inode.
3324 int ext4_alloc_da_blocks(struct inode *inode)
3326 trace_ext4_alloc_da_blocks(inode);
3328 if (!EXT4_I(inode)->i_reserved_data_blocks &&
3329 !EXT4_I(inode)->i_reserved_meta_blocks)
3330 return 0;
3333 * We do something simple for now. The filemap_flush() will
3334 * also start triggering a write of the data blocks, which is
3335 * not strictly speaking necessary (and for users of
3336 * laptop_mode, not even desirable). However, to do otherwise
3337 * would require replicating code paths in:
3339 * ext4_da_writepages() ->
3340 * write_cache_pages() ---> (via passed in callback function)
3341 * __mpage_da_writepage() -->
3342 * mpage_add_bh_to_extent()
3343 * mpage_da_map_blocks()
3345 * The problem is that write_cache_pages(), located in
3346 * mm/page-writeback.c, marks pages clean in preparation for
3347 * doing I/O, which is not desirable if we're not planning on
3348 * doing I/O at all.
3350 * We could call write_cache_pages(), and then redirty all of
3351 * the pages by calling redirty_page_for_writeback() but that
3352 * would be ugly in the extreme. So instead we would need to
3353 * replicate parts of the code in the above functions,
3354 * simplifying them becuase we wouldn't actually intend to
3355 * write out the pages, but rather only collect contiguous
3356 * logical block extents, call the multi-block allocator, and
3357 * then update the buffer heads with the block allocations.
3359 * For now, though, we'll cheat by calling filemap_flush(),
3360 * which will map the blocks, and start the I/O, but not
3361 * actually wait for the I/O to complete.
3363 return filemap_flush(inode->i_mapping);
3367 * bmap() is special. It gets used by applications such as lilo and by
3368 * the swapper to find the on-disk block of a specific piece of data.
3370 * Naturally, this is dangerous if the block concerned is still in the
3371 * journal. If somebody makes a swapfile on an ext4 data-journaling
3372 * filesystem and enables swap, then they may get a nasty shock when the
3373 * data getting swapped to that swapfile suddenly gets overwritten by
3374 * the original zero's written out previously to the journal and
3375 * awaiting writeback in the kernel's buffer cache.
3377 * So, if we see any bmap calls here on a modified, data-journaled file,
3378 * take extra steps to flush any blocks which might be in the cache.
3380 static sector_t ext4_bmap(struct address_space *mapping, sector_t block)
3382 struct inode *inode = mapping->host;
3383 journal_t *journal;
3384 int err;
3386 if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY) &&
3387 test_opt(inode->i_sb, DELALLOC)) {
3389 * With delalloc we want to sync the file
3390 * so that we can make sure we allocate
3391 * blocks for file
3393 filemap_write_and_wait(mapping);
3396 if (EXT4_JOURNAL(inode) &&
3397 ext4_test_inode_state(inode, EXT4_STATE_JDATA)) {
3399 * This is a REALLY heavyweight approach, but the use of
3400 * bmap on dirty files is expected to be extremely rare:
3401 * only if we run lilo or swapon on a freshly made file
3402 * do we expect this to happen.
3404 * (bmap requires CAP_SYS_RAWIO so this does not
3405 * represent an unprivileged user DOS attack --- we'd be
3406 * in trouble if mortal users could trigger this path at
3407 * will.)
3409 * NB. EXT4_STATE_JDATA is not set on files other than
3410 * regular files. If somebody wants to bmap a directory
3411 * or symlink and gets confused because the buffer
3412 * hasn't yet been flushed to disk, they deserve
3413 * everything they get.
3416 ext4_clear_inode_state(inode, EXT4_STATE_JDATA);
3417 journal = EXT4_JOURNAL(inode);
3418 jbd2_journal_lock_updates(journal);
3419 err = jbd2_journal_flush(journal);
3420 jbd2_journal_unlock_updates(journal);
3422 if (err)
3423 return 0;
3426 return generic_block_bmap(mapping, block, ext4_get_block);
3429 static int ext4_readpage(struct file *file, struct page *page)
3431 return mpage_readpage(page, ext4_get_block);
3434 static int
3435 ext4_readpages(struct file *file, struct address_space *mapping,
3436 struct list_head *pages, unsigned nr_pages)
3438 return mpage_readpages(mapping, pages, nr_pages, ext4_get_block);
3441 static void ext4_free_io_end(ext4_io_end_t *io)
3443 BUG_ON(!io);
3444 if (io->page)
3445 put_page(io->page);
3446 iput(io->inode);
3447 kfree(io);
3450 static void ext4_invalidatepage_free_endio(struct page *page, unsigned long offset)
3452 struct buffer_head *head, *bh;
3453 unsigned int curr_off = 0;
3455 if (!page_has_buffers(page))
3456 return;
3457 head = bh = page_buffers(page);
3458 do {
3459 if (offset <= curr_off && test_clear_buffer_uninit(bh)
3460 && bh->b_private) {
3461 ext4_free_io_end(bh->b_private);
3462 bh->b_private = NULL;
3463 bh->b_end_io = NULL;
3465 curr_off = curr_off + bh->b_size;
3466 bh = bh->b_this_page;
3467 } while (bh != head);
3470 static void ext4_invalidatepage(struct page *page, unsigned long offset)
3472 journal_t *journal = EXT4_JOURNAL(page->mapping->host);
3475 * free any io_end structure allocated for buffers to be discarded
3477 if (ext4_should_dioread_nolock(page->mapping->host))
3478 ext4_invalidatepage_free_endio(page, offset);
3480 * If it's a full truncate we just forget about the pending dirtying
3482 if (offset == 0)
3483 ClearPageChecked(page);
3485 if (journal)
3486 jbd2_journal_invalidatepage(journal, page, offset);
3487 else
3488 block_invalidatepage(page, offset);
3491 static int ext4_releasepage(struct page *page, gfp_t wait)
3493 journal_t *journal = EXT4_JOURNAL(page->mapping->host);
3495 WARN_ON(PageChecked(page));
3496 if (!page_has_buffers(page))
3497 return 0;
3498 if (journal)
3499 return jbd2_journal_try_to_free_buffers(journal, page, wait);
3500 else
3501 return try_to_free_buffers(page);
3505 * O_DIRECT for ext3 (or indirect map) based files
3507 * If the O_DIRECT write will extend the file then add this inode to the
3508 * orphan list. So recovery will truncate it back to the original size
3509 * if the machine crashes during the write.
3511 * If the O_DIRECT write is intantiating holes inside i_size and the machine
3512 * crashes then stale disk data _may_ be exposed inside the file. But current
3513 * VFS code falls back into buffered path in that case so we are safe.
3515 static ssize_t ext4_ind_direct_IO(int rw, struct kiocb *iocb,
3516 const struct iovec *iov, loff_t offset,
3517 unsigned long nr_segs)
3519 struct file *file = iocb->ki_filp;
3520 struct inode *inode = file->f_mapping->host;
3521 struct ext4_inode_info *ei = EXT4_I(inode);
3522 handle_t *handle;
3523 ssize_t ret;
3524 int orphan = 0;
3525 size_t count = iov_length(iov, nr_segs);
3526 int retries = 0;
3528 if (rw == WRITE) {
3529 loff_t final_size = offset + count;
3531 if (final_size > inode->i_size) {
3532 /* Credits for sb + inode write */
3533 handle = ext4_journal_start(inode, 2);
3534 if (IS_ERR(handle)) {
3535 ret = PTR_ERR(handle);
3536 goto out;
3538 ret = ext4_orphan_add(handle, inode);
3539 if (ret) {
3540 ext4_journal_stop(handle);
3541 goto out;
3543 orphan = 1;
3544 ei->i_disksize = inode->i_size;
3545 ext4_journal_stop(handle);
3549 retry:
3550 if (rw == READ && ext4_should_dioread_nolock(inode))
3551 ret = __blockdev_direct_IO(rw, iocb, inode,
3552 inode->i_sb->s_bdev, iov,
3553 offset, nr_segs,
3554 ext4_get_block, NULL, NULL, 0);
3555 else {
3556 ret = blockdev_direct_IO(rw, iocb, inode,
3557 inode->i_sb->s_bdev, iov,
3558 offset, nr_segs,
3559 ext4_get_block, NULL);
3561 if (unlikely((rw & WRITE) && ret < 0)) {
3562 loff_t isize = i_size_read(inode);
3563 loff_t end = offset + iov_length(iov, nr_segs);
3565 if (end > isize)
3566 vmtruncate(inode, isize);
3569 if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
3570 goto retry;
3572 if (orphan) {
3573 int err;
3575 /* Credits for sb + inode write */
3576 handle = ext4_journal_start(inode, 2);
3577 if (IS_ERR(handle)) {
3578 /* This is really bad luck. We've written the data
3579 * but cannot extend i_size. Bail out and pretend
3580 * the write failed... */
3581 ret = PTR_ERR(handle);
3582 if (inode->i_nlink)
3583 ext4_orphan_del(NULL, inode);
3585 goto out;
3587 if (inode->i_nlink)
3588 ext4_orphan_del(handle, inode);
3589 if (ret > 0) {
3590 loff_t end = offset + ret;
3591 if (end > inode->i_size) {
3592 ei->i_disksize = end;
3593 i_size_write(inode, end);
3595 * We're going to return a positive `ret'
3596 * here due to non-zero-length I/O, so there's
3597 * no way of reporting error returns from
3598 * ext4_mark_inode_dirty() to userspace. So
3599 * ignore it.
3601 ext4_mark_inode_dirty(handle, inode);
3604 err = ext4_journal_stop(handle);
3605 if (ret == 0)
3606 ret = err;
3608 out:
3609 return ret;
3613 * ext4_get_block used when preparing for a DIO write or buffer write.
3614 * We allocate an uinitialized extent if blocks haven't been allocated.
3615 * The extent will be converted to initialized after the IO is complete.
3617 static int ext4_get_block_write(struct inode *inode, sector_t iblock,
3618 struct buffer_head *bh_result, int create)
3620 ext4_debug("ext4_get_block_write: inode %lu, create flag %d\n",
3621 inode->i_ino, create);
3622 return _ext4_get_block(inode, iblock, bh_result,
3623 EXT4_GET_BLOCKS_IO_CREATE_EXT);
3626 static void dump_completed_IO(struct inode * inode)
3628 #ifdef EXT4_DEBUG
3629 struct list_head *cur, *before, *after;
3630 ext4_io_end_t *io, *io0, *io1;
3631 unsigned long flags;
3633 if (list_empty(&EXT4_I(inode)->i_completed_io_list)){
3634 ext4_debug("inode %lu completed_io list is empty\n", inode->i_ino);
3635 return;
3638 ext4_debug("Dump inode %lu completed_io list \n", inode->i_ino);
3639 spin_lock_irqsave(&EXT4_I(inode)->i_completed_io_lock, flags);
3640 list_for_each_entry(io, &EXT4_I(inode)->i_completed_io_list, list){
3641 cur = &io->list;
3642 before = cur->prev;
3643 io0 = container_of(before, ext4_io_end_t, list);
3644 after = cur->next;
3645 io1 = container_of(after, ext4_io_end_t, list);
3647 ext4_debug("io 0x%p from inode %lu,prev 0x%p,next 0x%p\n",
3648 io, inode->i_ino, io0, io1);
3650 spin_unlock_irqrestore(&EXT4_I(inode)->i_completed_io_lock, flags);
3651 #endif
3655 * check a range of space and convert unwritten extents to written.
3657 static int ext4_end_io_nolock(ext4_io_end_t *io)
3659 struct inode *inode = io->inode;
3660 loff_t offset = io->offset;
3661 ssize_t size = io->size;
3662 int ret = 0;
3664 ext4_debug("ext4_end_io_nolock: io 0x%p from inode %lu,list->next 0x%p,"
3665 "list->prev 0x%p\n",
3666 io, inode->i_ino, io->list.next, io->list.prev);
3668 if (list_empty(&io->list))
3669 return ret;
3671 if (io->flag != EXT4_IO_UNWRITTEN)
3672 return ret;
3674 ret = ext4_convert_unwritten_extents(inode, offset, size);
3675 if (ret < 0) {
3676 printk(KERN_EMERG "%s: failed to convert unwritten"
3677 "extents to written extents, error is %d"
3678 " io is still on inode %lu aio dio list\n",
3679 __func__, ret, inode->i_ino);
3680 return ret;
3683 if (io->iocb)
3684 aio_complete(io->iocb, io->result, 0);
3685 /* clear the DIO AIO unwritten flag */
3686 io->flag = 0;
3687 return ret;
3691 * work on completed aio dio IO, to convert unwritten extents to extents
3693 static void ext4_end_io_work(struct work_struct *work)
3695 ext4_io_end_t *io = container_of(work, ext4_io_end_t, work);
3696 struct inode *inode = io->inode;
3697 struct ext4_inode_info *ei = EXT4_I(inode);
3698 unsigned long flags;
3699 int ret;
3701 mutex_lock(&inode->i_mutex);
3702 ret = ext4_end_io_nolock(io);
3703 if (ret < 0) {
3704 mutex_unlock(&inode->i_mutex);
3705 return;
3708 spin_lock_irqsave(&ei->i_completed_io_lock, flags);
3709 if (!list_empty(&io->list))
3710 list_del_init(&io->list);
3711 spin_unlock_irqrestore(&ei->i_completed_io_lock, flags);
3712 mutex_unlock(&inode->i_mutex);
3713 ext4_free_io_end(io);
3717 * This function is called from ext4_sync_file().
3719 * When IO is completed, the work to convert unwritten extents to
3720 * written is queued on workqueue but may not get immediately
3721 * scheduled. When fsync is called, we need to ensure the
3722 * conversion is complete before fsync returns.
3723 * The inode keeps track of a list of pending/completed IO that
3724 * might needs to do the conversion. This function walks through
3725 * the list and convert the related unwritten extents for completed IO
3726 * to written.
3727 * The function return the number of pending IOs on success.
3729 int flush_completed_IO(struct inode *inode)
3731 ext4_io_end_t *io;
3732 struct ext4_inode_info *ei = EXT4_I(inode);
3733 unsigned long flags;
3734 int ret = 0;
3735 int ret2 = 0;
3737 if (list_empty(&ei->i_completed_io_list))
3738 return ret;
3740 dump_completed_IO(inode);
3741 spin_lock_irqsave(&ei->i_completed_io_lock, flags);
3742 while (!list_empty(&ei->i_completed_io_list)){
3743 io = list_entry(ei->i_completed_io_list.next,
3744 ext4_io_end_t, list);
3746 * Calling ext4_end_io_nolock() to convert completed
3747 * IO to written.
3749 * When ext4_sync_file() is called, run_queue() may already
3750 * about to flush the work corresponding to this io structure.
3751 * It will be upset if it founds the io structure related
3752 * to the work-to-be schedule is freed.
3754 * Thus we need to keep the io structure still valid here after
3755 * convertion finished. The io structure has a flag to
3756 * avoid double converting from both fsync and background work
3757 * queue work.
3759 spin_unlock_irqrestore(&ei->i_completed_io_lock, flags);
3760 ret = ext4_end_io_nolock(io);
3761 spin_lock_irqsave(&ei->i_completed_io_lock, flags);
3762 if (ret < 0)
3763 ret2 = ret;
3764 else
3765 list_del_init(&io->list);
3767 spin_unlock_irqrestore(&ei->i_completed_io_lock, flags);
3768 return (ret2 < 0) ? ret2 : 0;
3771 static ext4_io_end_t *ext4_init_io_end (struct inode *inode, gfp_t flags)
3773 ext4_io_end_t *io = NULL;
3775 io = kmalloc(sizeof(*io), flags);
3777 if (io) {
3778 igrab(inode);
3779 io->inode = inode;
3780 io->flag = 0;
3781 io->offset = 0;
3782 io->size = 0;
3783 io->page = NULL;
3784 io->iocb = NULL;
3785 io->result = 0;
3786 INIT_WORK(&io->work, ext4_end_io_work);
3787 INIT_LIST_HEAD(&io->list);
3790 return io;
3793 static void ext4_end_io_dio(struct kiocb *iocb, loff_t offset,
3794 ssize_t size, void *private, int ret,
3795 bool is_async)
3797 ext4_io_end_t *io_end = iocb->private;
3798 struct workqueue_struct *wq;
3799 unsigned long flags;
3800 struct ext4_inode_info *ei;
3802 /* if not async direct IO or dio with 0 bytes write, just return */
3803 if (!io_end || !size)
3804 goto out;
3806 ext_debug("ext4_end_io_dio(): io_end 0x%p"
3807 "for inode %lu, iocb 0x%p, offset %llu, size %llu\n",
3808 iocb->private, io_end->inode->i_ino, iocb, offset,
3809 size);
3811 /* if not aio dio with unwritten extents, just free io and return */
3812 if (io_end->flag != EXT4_IO_UNWRITTEN){
3813 ext4_free_io_end(io_end);
3814 iocb->private = NULL;
3815 out:
3816 if (is_async)
3817 aio_complete(iocb, ret, 0);
3818 return;
3821 io_end->offset = offset;
3822 io_end->size = size;
3823 if (is_async) {
3824 io_end->iocb = iocb;
3825 io_end->result = ret;
3827 wq = EXT4_SB(io_end->inode->i_sb)->dio_unwritten_wq;
3829 /* queue the work to convert unwritten extents to written */
3830 queue_work(wq, &io_end->work);
3832 /* Add the io_end to per-inode completed aio dio list*/
3833 ei = EXT4_I(io_end->inode);
3834 spin_lock_irqsave(&ei->i_completed_io_lock, flags);
3835 list_add_tail(&io_end->list, &ei->i_completed_io_list);
3836 spin_unlock_irqrestore(&ei->i_completed_io_lock, flags);
3837 iocb->private = NULL;
3840 static void ext4_end_io_buffer_write(struct buffer_head *bh, int uptodate)
3842 ext4_io_end_t *io_end = bh->b_private;
3843 struct workqueue_struct *wq;
3844 struct inode *inode;
3845 unsigned long flags;
3847 if (!test_clear_buffer_uninit(bh) || !io_end)
3848 goto out;
3850 if (!(io_end->inode->i_sb->s_flags & MS_ACTIVE)) {
3851 printk("sb umounted, discard end_io request for inode %lu\n",
3852 io_end->inode->i_ino);
3853 ext4_free_io_end(io_end);
3854 goto out;
3857 io_end->flag = EXT4_IO_UNWRITTEN;
3858 inode = io_end->inode;
3860 /* Add the io_end to per-inode completed io list*/
3861 spin_lock_irqsave(&EXT4_I(inode)->i_completed_io_lock, flags);
3862 list_add_tail(&io_end->list, &EXT4_I(inode)->i_completed_io_list);
3863 spin_unlock_irqrestore(&EXT4_I(inode)->i_completed_io_lock, flags);
3865 wq = EXT4_SB(inode->i_sb)->dio_unwritten_wq;
3866 /* queue the work to convert unwritten extents to written */
3867 queue_work(wq, &io_end->work);
3868 out:
3869 bh->b_private = NULL;
3870 bh->b_end_io = NULL;
3871 clear_buffer_uninit(bh);
3872 end_buffer_async_write(bh, uptodate);
3875 static int ext4_set_bh_endio(struct buffer_head *bh, struct inode *inode)
3877 ext4_io_end_t *io_end;
3878 struct page *page = bh->b_page;
3879 loff_t offset = (sector_t)page->index << PAGE_CACHE_SHIFT;
3880 size_t size = bh->b_size;
3882 retry:
3883 io_end = ext4_init_io_end(inode, GFP_ATOMIC);
3884 if (!io_end) {
3885 if (printk_ratelimit())
3886 printk(KERN_WARNING "%s: allocation fail\n", __func__);
3887 schedule();
3888 goto retry;
3890 io_end->offset = offset;
3891 io_end->size = size;
3893 * We need to hold a reference to the page to make sure it
3894 * doesn't get evicted before ext4_end_io_work() has a chance
3895 * to convert the extent from written to unwritten.
3897 io_end->page = page;
3898 get_page(io_end->page);
3900 bh->b_private = io_end;
3901 bh->b_end_io = ext4_end_io_buffer_write;
3902 return 0;
3906 * For ext4 extent files, ext4 will do direct-io write to holes,
3907 * preallocated extents, and those write extend the file, no need to
3908 * fall back to buffered IO.
3910 * For holes, we fallocate those blocks, mark them as unintialized
3911 * If those blocks were preallocated, we mark sure they are splited, but
3912 * still keep the range to write as unintialized.
3914 * The unwrritten extents will be converted to written when DIO is completed.
3915 * For async direct IO, since the IO may still pending when return, we
3916 * set up an end_io call back function, which will do the convertion
3917 * when async direct IO completed.
3919 * If the O_DIRECT write will extend the file then add this inode to the
3920 * orphan list. So recovery will truncate it back to the original size
3921 * if the machine crashes during the write.
3924 static ssize_t ext4_ext_direct_IO(int rw, struct kiocb *iocb,
3925 const struct iovec *iov, loff_t offset,
3926 unsigned long nr_segs)
3928 struct file *file = iocb->ki_filp;
3929 struct inode *inode = file->f_mapping->host;
3930 ssize_t ret;
3931 size_t count = iov_length(iov, nr_segs);
3933 loff_t final_size = offset + count;
3934 if (rw == WRITE && final_size <= inode->i_size) {
3936 * We could direct write to holes and fallocate.
3938 * Allocated blocks to fill the hole are marked as uninitialized
3939 * to prevent paralel buffered read to expose the stale data
3940 * before DIO complete the data IO.
3942 * As to previously fallocated extents, ext4 get_block
3943 * will just simply mark the buffer mapped but still
3944 * keep the extents uninitialized.
3946 * for non AIO case, we will convert those unwritten extents
3947 * to written after return back from blockdev_direct_IO.
3949 * for async DIO, the conversion needs to be defered when
3950 * the IO is completed. The ext4 end_io callback function
3951 * will be called to take care of the conversion work.
3952 * Here for async case, we allocate an io_end structure to
3953 * hook to the iocb.
3955 iocb->private = NULL;
3956 EXT4_I(inode)->cur_aio_dio = NULL;
3957 if (!is_sync_kiocb(iocb)) {
3958 iocb->private = ext4_init_io_end(inode, GFP_NOFS);
3959 if (!iocb->private)
3960 return -ENOMEM;
3962 * we save the io structure for current async
3963 * direct IO, so that later ext4_map_blocks()
3964 * could flag the io structure whether there
3965 * is a unwritten extents needs to be converted
3966 * when IO is completed.
3968 EXT4_I(inode)->cur_aio_dio = iocb->private;
3971 ret = blockdev_direct_IO(rw, iocb, inode,
3972 inode->i_sb->s_bdev, iov,
3973 offset, nr_segs,
3974 ext4_get_block_write,
3975 ext4_end_io_dio);
3976 if (iocb->private)
3977 EXT4_I(inode)->cur_aio_dio = NULL;
3979 * The io_end structure takes a reference to the inode,
3980 * that structure needs to be destroyed and the
3981 * reference to the inode need to be dropped, when IO is
3982 * complete, even with 0 byte write, or failed.
3984 * In the successful AIO DIO case, the io_end structure will be
3985 * desctroyed and the reference to the inode will be dropped
3986 * after the end_io call back function is called.
3988 * In the case there is 0 byte write, or error case, since
3989 * VFS direct IO won't invoke the end_io call back function,
3990 * we need to free the end_io structure here.
3992 if (ret != -EIOCBQUEUED && ret <= 0 && iocb->private) {
3993 ext4_free_io_end(iocb->private);
3994 iocb->private = NULL;
3995 } else if (ret > 0 && ext4_test_inode_state(inode,
3996 EXT4_STATE_DIO_UNWRITTEN)) {
3997 int err;
3999 * for non AIO case, since the IO is already
4000 * completed, we could do the convertion right here
4002 err = ext4_convert_unwritten_extents(inode,
4003 offset, ret);
4004 if (err < 0)
4005 ret = err;
4006 ext4_clear_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN);
4008 return ret;
4011 /* for write the the end of file case, we fall back to old way */
4012 return ext4_ind_direct_IO(rw, iocb, iov, offset, nr_segs);
4015 static ssize_t ext4_direct_IO(int rw, struct kiocb *iocb,
4016 const struct iovec *iov, loff_t offset,
4017 unsigned long nr_segs)
4019 struct file *file = iocb->ki_filp;
4020 struct inode *inode = file->f_mapping->host;
4022 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4023 return ext4_ext_direct_IO(rw, iocb, iov, offset, nr_segs);
4025 return ext4_ind_direct_IO(rw, iocb, iov, offset, nr_segs);
4029 * Pages can be marked dirty completely asynchronously from ext4's journalling
4030 * activity. By filemap_sync_pte(), try_to_unmap_one(), etc. We cannot do
4031 * much here because ->set_page_dirty is called under VFS locks. The page is
4032 * not necessarily locked.
4034 * We cannot just dirty the page and leave attached buffers clean, because the
4035 * buffers' dirty state is "definitive". We cannot just set the buffers dirty
4036 * or jbddirty because all the journalling code will explode.
4038 * So what we do is to mark the page "pending dirty" and next time writepage
4039 * is called, propagate that into the buffers appropriately.
4041 static int ext4_journalled_set_page_dirty(struct page *page)
4043 SetPageChecked(page);
4044 return __set_page_dirty_nobuffers(page);
4047 static const struct address_space_operations ext4_ordered_aops = {
4048 .readpage = ext4_readpage,
4049 .readpages = ext4_readpages,
4050 .writepage = ext4_writepage,
4051 .sync_page = block_sync_page,
4052 .write_begin = ext4_write_begin,
4053 .write_end = ext4_ordered_write_end,
4054 .bmap = ext4_bmap,
4055 .invalidatepage = ext4_invalidatepage,
4056 .releasepage = ext4_releasepage,
4057 .direct_IO = ext4_direct_IO,
4058 .migratepage = buffer_migrate_page,
4059 .is_partially_uptodate = block_is_partially_uptodate,
4060 .error_remove_page = generic_error_remove_page,
4063 static const struct address_space_operations ext4_writeback_aops = {
4064 .readpage = ext4_readpage,
4065 .readpages = ext4_readpages,
4066 .writepage = ext4_writepage,
4067 .sync_page = block_sync_page,
4068 .write_begin = ext4_write_begin,
4069 .write_end = ext4_writeback_write_end,
4070 .bmap = ext4_bmap,
4071 .invalidatepage = ext4_invalidatepage,
4072 .releasepage = ext4_releasepage,
4073 .direct_IO = ext4_direct_IO,
4074 .migratepage = buffer_migrate_page,
4075 .is_partially_uptodate = block_is_partially_uptodate,
4076 .error_remove_page = generic_error_remove_page,
4079 static const struct address_space_operations ext4_journalled_aops = {
4080 .readpage = ext4_readpage,
4081 .readpages = ext4_readpages,
4082 .writepage = ext4_writepage,
4083 .sync_page = block_sync_page,
4084 .write_begin = ext4_write_begin,
4085 .write_end = ext4_journalled_write_end,
4086 .set_page_dirty = ext4_journalled_set_page_dirty,
4087 .bmap = ext4_bmap,
4088 .invalidatepage = ext4_invalidatepage,
4089 .releasepage = ext4_releasepage,
4090 .is_partially_uptodate = block_is_partially_uptodate,
4091 .error_remove_page = generic_error_remove_page,
4094 static const struct address_space_operations ext4_da_aops = {
4095 .readpage = ext4_readpage,
4096 .readpages = ext4_readpages,
4097 .writepage = ext4_writepage,
4098 .writepages = ext4_da_writepages,
4099 .sync_page = block_sync_page,
4100 .write_begin = ext4_da_write_begin,
4101 .write_end = ext4_da_write_end,
4102 .bmap = ext4_bmap,
4103 .invalidatepage = ext4_da_invalidatepage,
4104 .releasepage = ext4_releasepage,
4105 .direct_IO = ext4_direct_IO,
4106 .migratepage = buffer_migrate_page,
4107 .is_partially_uptodate = block_is_partially_uptodate,
4108 .error_remove_page = generic_error_remove_page,
4111 void ext4_set_aops(struct inode *inode)
4113 if (ext4_should_order_data(inode) &&
4114 test_opt(inode->i_sb, DELALLOC))
4115 inode->i_mapping->a_ops = &ext4_da_aops;
4116 else if (ext4_should_order_data(inode))
4117 inode->i_mapping->a_ops = &ext4_ordered_aops;
4118 else if (ext4_should_writeback_data(inode) &&
4119 test_opt(inode->i_sb, DELALLOC))
4120 inode->i_mapping->a_ops = &ext4_da_aops;
4121 else if (ext4_should_writeback_data(inode))
4122 inode->i_mapping->a_ops = &ext4_writeback_aops;
4123 else
4124 inode->i_mapping->a_ops = &ext4_journalled_aops;
4128 * ext4_block_truncate_page() zeroes out a mapping from file offset `from'
4129 * up to the end of the block which corresponds to `from'.
4130 * This required during truncate. We need to physically zero the tail end
4131 * of that block so it doesn't yield old data if the file is later grown.
4133 int ext4_block_truncate_page(handle_t *handle,
4134 struct address_space *mapping, loff_t from)
4136 ext4_fsblk_t index = from >> PAGE_CACHE_SHIFT;
4137 unsigned offset = from & (PAGE_CACHE_SIZE-1);
4138 unsigned blocksize, length, pos;
4139 ext4_lblk_t iblock;
4140 struct inode *inode = mapping->host;
4141 struct buffer_head *bh;
4142 struct page *page;
4143 int err = 0;
4145 page = find_or_create_page(mapping, from >> PAGE_CACHE_SHIFT,
4146 mapping_gfp_mask(mapping) & ~__GFP_FS);
4147 if (!page)
4148 return -EINVAL;
4150 blocksize = inode->i_sb->s_blocksize;
4151 length = blocksize - (offset & (blocksize - 1));
4152 iblock = index << (PAGE_CACHE_SHIFT - inode->i_sb->s_blocksize_bits);
4154 if (!page_has_buffers(page))
4155 create_empty_buffers(page, blocksize, 0);
4157 /* Find the buffer that contains "offset" */
4158 bh = page_buffers(page);
4159 pos = blocksize;
4160 while (offset >= pos) {
4161 bh = bh->b_this_page;
4162 iblock++;
4163 pos += blocksize;
4166 err = 0;
4167 if (buffer_freed(bh)) {
4168 BUFFER_TRACE(bh, "freed: skip");
4169 goto unlock;
4172 if (!buffer_mapped(bh)) {
4173 BUFFER_TRACE(bh, "unmapped");
4174 ext4_get_block(inode, iblock, bh, 0);
4175 /* unmapped? It's a hole - nothing to do */
4176 if (!buffer_mapped(bh)) {
4177 BUFFER_TRACE(bh, "still unmapped");
4178 goto unlock;
4182 /* Ok, it's mapped. Make sure it's up-to-date */
4183 if (PageUptodate(page))
4184 set_buffer_uptodate(bh);
4186 if (!buffer_uptodate(bh)) {
4187 err = -EIO;
4188 ll_rw_block(READ, 1, &bh);
4189 wait_on_buffer(bh);
4190 /* Uhhuh. Read error. Complain and punt. */
4191 if (!buffer_uptodate(bh))
4192 goto unlock;
4195 if (ext4_should_journal_data(inode)) {
4196 BUFFER_TRACE(bh, "get write access");
4197 err = ext4_journal_get_write_access(handle, bh);
4198 if (err)
4199 goto unlock;
4202 zero_user(page, offset, length);
4204 BUFFER_TRACE(bh, "zeroed end of block");
4206 err = 0;
4207 if (ext4_should_journal_data(inode)) {
4208 err = ext4_handle_dirty_metadata(handle, inode, bh);
4209 } else {
4210 if (ext4_should_order_data(inode))
4211 err = ext4_jbd2_file_inode(handle, inode);
4212 mark_buffer_dirty(bh);
4215 unlock:
4216 unlock_page(page);
4217 page_cache_release(page);
4218 return err;
4222 * Probably it should be a library function... search for first non-zero word
4223 * or memcmp with zero_page, whatever is better for particular architecture.
4224 * Linus?
4226 static inline int all_zeroes(__le32 *p, __le32 *q)
4228 while (p < q)
4229 if (*p++)
4230 return 0;
4231 return 1;
4235 * ext4_find_shared - find the indirect blocks for partial truncation.
4236 * @inode: inode in question
4237 * @depth: depth of the affected branch
4238 * @offsets: offsets of pointers in that branch (see ext4_block_to_path)
4239 * @chain: place to store the pointers to partial indirect blocks
4240 * @top: place to the (detached) top of branch
4242 * This is a helper function used by ext4_truncate().
4244 * When we do truncate() we may have to clean the ends of several
4245 * indirect blocks but leave the blocks themselves alive. Block is
4246 * partially truncated if some data below the new i_size is refered
4247 * from it (and it is on the path to the first completely truncated
4248 * data block, indeed). We have to free the top of that path along
4249 * with everything to the right of the path. Since no allocation
4250 * past the truncation point is possible until ext4_truncate()
4251 * finishes, we may safely do the latter, but top of branch may
4252 * require special attention - pageout below the truncation point
4253 * might try to populate it.
4255 * We atomically detach the top of branch from the tree, store the
4256 * block number of its root in *@top, pointers to buffer_heads of
4257 * partially truncated blocks - in @chain[].bh and pointers to
4258 * their last elements that should not be removed - in
4259 * @chain[].p. Return value is the pointer to last filled element
4260 * of @chain.
4262 * The work left to caller to do the actual freeing of subtrees:
4263 * a) free the subtree starting from *@top
4264 * b) free the subtrees whose roots are stored in
4265 * (@chain[i].p+1 .. end of @chain[i].bh->b_data)
4266 * c) free the subtrees growing from the inode past the @chain[0].
4267 * (no partially truncated stuff there). */
4269 static Indirect *ext4_find_shared(struct inode *inode, int depth,
4270 ext4_lblk_t offsets[4], Indirect chain[4],
4271 __le32 *top)
4273 Indirect *partial, *p;
4274 int k, err;
4276 *top = 0;
4277 /* Make k index the deepest non-null offset + 1 */
4278 for (k = depth; k > 1 && !offsets[k-1]; k--)
4280 partial = ext4_get_branch(inode, k, offsets, chain, &err);
4281 /* Writer: pointers */
4282 if (!partial)
4283 partial = chain + k-1;
4285 * If the branch acquired continuation since we've looked at it -
4286 * fine, it should all survive and (new) top doesn't belong to us.
4288 if (!partial->key && *partial->p)
4289 /* Writer: end */
4290 goto no_top;
4291 for (p = partial; (p > chain) && all_zeroes((__le32 *) p->bh->b_data, p->p); p--)
4294 * OK, we've found the last block that must survive. The rest of our
4295 * branch should be detached before unlocking. However, if that rest
4296 * of branch is all ours and does not grow immediately from the inode
4297 * it's easier to cheat and just decrement partial->p.
4299 if (p == chain + k - 1 && p > chain) {
4300 p->p--;
4301 } else {
4302 *top = *p->p;
4303 /* Nope, don't do this in ext4. Must leave the tree intact */
4305 /* Writer: end */
4307 while (partial > p) {
4308 brelse(partial->bh);
4309 partial--;
4311 no_top:
4312 return partial;
4316 * Zero a number of block pointers in either an inode or an indirect block.
4317 * If we restart the transaction we must again get write access to the
4318 * indirect block for further modification.
4320 * We release `count' blocks on disk, but (last - first) may be greater
4321 * than `count' because there can be holes in there.
4323 static int ext4_clear_blocks(handle_t *handle, struct inode *inode,
4324 struct buffer_head *bh,
4325 ext4_fsblk_t block_to_free,
4326 unsigned long count, __le32 *first,
4327 __le32 *last)
4329 __le32 *p;
4330 int flags = EXT4_FREE_BLOCKS_FORGET | EXT4_FREE_BLOCKS_VALIDATED;
4332 if (S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode))
4333 flags |= EXT4_FREE_BLOCKS_METADATA;
4335 if (!ext4_data_block_valid(EXT4_SB(inode->i_sb), block_to_free,
4336 count)) {
4337 EXT4_ERROR_INODE(inode, "attempt to clear invalid "
4338 "blocks %llu len %lu",
4339 (unsigned long long) block_to_free, count);
4340 return 1;
4343 if (try_to_extend_transaction(handle, inode)) {
4344 if (bh) {
4345 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
4346 ext4_handle_dirty_metadata(handle, inode, bh);
4348 ext4_mark_inode_dirty(handle, inode);
4349 ext4_truncate_restart_trans(handle, inode,
4350 blocks_for_truncate(inode));
4351 if (bh) {
4352 BUFFER_TRACE(bh, "retaking write access");
4353 ext4_journal_get_write_access(handle, bh);
4357 for (p = first; p < last; p++)
4358 *p = 0;
4360 ext4_free_blocks(handle, inode, 0, block_to_free, count, flags);
4361 return 0;
4365 * ext4_free_data - free a list of data blocks
4366 * @handle: handle for this transaction
4367 * @inode: inode we are dealing with
4368 * @this_bh: indirect buffer_head which contains *@first and *@last
4369 * @first: array of block numbers
4370 * @last: points immediately past the end of array
4372 * We are freeing all blocks refered from that array (numbers are stored as
4373 * little-endian 32-bit) and updating @inode->i_blocks appropriately.
4375 * We accumulate contiguous runs of blocks to free. Conveniently, if these
4376 * blocks are contiguous then releasing them at one time will only affect one
4377 * or two bitmap blocks (+ group descriptor(s) and superblock) and we won't
4378 * actually use a lot of journal space.
4380 * @this_bh will be %NULL if @first and @last point into the inode's direct
4381 * block pointers.
4383 static void ext4_free_data(handle_t *handle, struct inode *inode,
4384 struct buffer_head *this_bh,
4385 __le32 *first, __le32 *last)
4387 ext4_fsblk_t block_to_free = 0; /* Starting block # of a run */
4388 unsigned long count = 0; /* Number of blocks in the run */
4389 __le32 *block_to_free_p = NULL; /* Pointer into inode/ind
4390 corresponding to
4391 block_to_free */
4392 ext4_fsblk_t nr; /* Current block # */
4393 __le32 *p; /* Pointer into inode/ind
4394 for current block */
4395 int err;
4397 if (this_bh) { /* For indirect block */
4398 BUFFER_TRACE(this_bh, "get_write_access");
4399 err = ext4_journal_get_write_access(handle, this_bh);
4400 /* Important: if we can't update the indirect pointers
4401 * to the blocks, we can't free them. */
4402 if (err)
4403 return;
4406 for (p = first; p < last; p++) {
4407 nr = le32_to_cpu(*p);
4408 if (nr) {
4409 /* accumulate blocks to free if they're contiguous */
4410 if (count == 0) {
4411 block_to_free = nr;
4412 block_to_free_p = p;
4413 count = 1;
4414 } else if (nr == block_to_free + count) {
4415 count++;
4416 } else {
4417 if (ext4_clear_blocks(handle, inode, this_bh,
4418 block_to_free, count,
4419 block_to_free_p, p))
4420 break;
4421 block_to_free = nr;
4422 block_to_free_p = p;
4423 count = 1;
4428 if (count > 0)
4429 ext4_clear_blocks(handle, inode, this_bh, block_to_free,
4430 count, block_to_free_p, p);
4432 if (this_bh) {
4433 BUFFER_TRACE(this_bh, "call ext4_handle_dirty_metadata");
4436 * The buffer head should have an attached journal head at this
4437 * point. However, if the data is corrupted and an indirect
4438 * block pointed to itself, it would have been detached when
4439 * the block was cleared. Check for this instead of OOPSing.
4441 if ((EXT4_JOURNAL(inode) == NULL) || bh2jh(this_bh))
4442 ext4_handle_dirty_metadata(handle, inode, this_bh);
4443 else
4444 EXT4_ERROR_INODE(inode,
4445 "circular indirect block detected at "
4446 "block %llu",
4447 (unsigned long long) this_bh->b_blocknr);
4452 * ext4_free_branches - free an array of branches
4453 * @handle: JBD handle for this transaction
4454 * @inode: inode we are dealing with
4455 * @parent_bh: the buffer_head which contains *@first and *@last
4456 * @first: array of block numbers
4457 * @last: pointer immediately past the end of array
4458 * @depth: depth of the branches to free
4460 * We are freeing all blocks refered from these branches (numbers are
4461 * stored as little-endian 32-bit) and updating @inode->i_blocks
4462 * appropriately.
4464 static void ext4_free_branches(handle_t *handle, struct inode *inode,
4465 struct buffer_head *parent_bh,
4466 __le32 *first, __le32 *last, int depth)
4468 ext4_fsblk_t nr;
4469 __le32 *p;
4471 if (ext4_handle_is_aborted(handle))
4472 return;
4474 if (depth--) {
4475 struct buffer_head *bh;
4476 int addr_per_block = EXT4_ADDR_PER_BLOCK(inode->i_sb);
4477 p = last;
4478 while (--p >= first) {
4479 nr = le32_to_cpu(*p);
4480 if (!nr)
4481 continue; /* A hole */
4483 if (!ext4_data_block_valid(EXT4_SB(inode->i_sb),
4484 nr, 1)) {
4485 EXT4_ERROR_INODE(inode,
4486 "invalid indirect mapped "
4487 "block %lu (level %d)",
4488 (unsigned long) nr, depth);
4489 break;
4492 /* Go read the buffer for the next level down */
4493 bh = sb_bread(inode->i_sb, nr);
4496 * A read failure? Report error and clear slot
4497 * (should be rare).
4499 if (!bh) {
4500 EXT4_ERROR_INODE_BLOCK(inode, nr,
4501 "Read failure");
4502 continue;
4505 /* This zaps the entire block. Bottom up. */
4506 BUFFER_TRACE(bh, "free child branches");
4507 ext4_free_branches(handle, inode, bh,
4508 (__le32 *) bh->b_data,
4509 (__le32 *) bh->b_data + addr_per_block,
4510 depth);
4511 brelse(bh);
4514 * Everything below this this pointer has been
4515 * released. Now let this top-of-subtree go.
4517 * We want the freeing of this indirect block to be
4518 * atomic in the journal with the updating of the
4519 * bitmap block which owns it. So make some room in
4520 * the journal.
4522 * We zero the parent pointer *after* freeing its
4523 * pointee in the bitmaps, so if extend_transaction()
4524 * for some reason fails to put the bitmap changes and
4525 * the release into the same transaction, recovery
4526 * will merely complain about releasing a free block,
4527 * rather than leaking blocks.
4529 if (ext4_handle_is_aborted(handle))
4530 return;
4531 if (try_to_extend_transaction(handle, inode)) {
4532 ext4_mark_inode_dirty(handle, inode);
4533 ext4_truncate_restart_trans(handle, inode,
4534 blocks_for_truncate(inode));
4538 * The forget flag here is critical because if
4539 * we are journaling (and not doing data
4540 * journaling), we have to make sure a revoke
4541 * record is written to prevent the journal
4542 * replay from overwriting the (former)
4543 * indirect block if it gets reallocated as a
4544 * data block. This must happen in the same
4545 * transaction where the data blocks are
4546 * actually freed.
4548 ext4_free_blocks(handle, inode, 0, nr, 1,
4549 EXT4_FREE_BLOCKS_METADATA|
4550 EXT4_FREE_BLOCKS_FORGET);
4552 if (parent_bh) {
4554 * The block which we have just freed is
4555 * pointed to by an indirect block: journal it
4557 BUFFER_TRACE(parent_bh, "get_write_access");
4558 if (!ext4_journal_get_write_access(handle,
4559 parent_bh)){
4560 *p = 0;
4561 BUFFER_TRACE(parent_bh,
4562 "call ext4_handle_dirty_metadata");
4563 ext4_handle_dirty_metadata(handle,
4564 inode,
4565 parent_bh);
4569 } else {
4570 /* We have reached the bottom of the tree. */
4571 BUFFER_TRACE(parent_bh, "free data blocks");
4572 ext4_free_data(handle, inode, parent_bh, first, last);
4576 int ext4_can_truncate(struct inode *inode)
4578 if (IS_APPEND(inode) || IS_IMMUTABLE(inode))
4579 return 0;
4580 if (S_ISREG(inode->i_mode))
4581 return 1;
4582 if (S_ISDIR(inode->i_mode))
4583 return 1;
4584 if (S_ISLNK(inode->i_mode))
4585 return !ext4_inode_is_fast_symlink(inode);
4586 return 0;
4590 * ext4_truncate()
4592 * We block out ext4_get_block() block instantiations across the entire
4593 * transaction, and VFS/VM ensures that ext4_truncate() cannot run
4594 * simultaneously on behalf of the same inode.
4596 * As we work through the truncate and commmit bits of it to the journal there
4597 * is one core, guiding principle: the file's tree must always be consistent on
4598 * disk. We must be able to restart the truncate after a crash.
4600 * The file's tree may be transiently inconsistent in memory (although it
4601 * probably isn't), but whenever we close off and commit a journal transaction,
4602 * the contents of (the filesystem + the journal) must be consistent and
4603 * restartable. It's pretty simple, really: bottom up, right to left (although
4604 * left-to-right works OK too).
4606 * Note that at recovery time, journal replay occurs *before* the restart of
4607 * truncate against the orphan inode list.
4609 * The committed inode has the new, desired i_size (which is the same as
4610 * i_disksize in this case). After a crash, ext4_orphan_cleanup() will see
4611 * that this inode's truncate did not complete and it will again call
4612 * ext4_truncate() to have another go. So there will be instantiated blocks
4613 * to the right of the truncation point in a crashed ext4 filesystem. But
4614 * that's fine - as long as they are linked from the inode, the post-crash
4615 * ext4_truncate() run will find them and release them.
4617 void ext4_truncate(struct inode *inode)
4619 handle_t *handle;
4620 struct ext4_inode_info *ei = EXT4_I(inode);
4621 __le32 *i_data = ei->i_data;
4622 int addr_per_block = EXT4_ADDR_PER_BLOCK(inode->i_sb);
4623 struct address_space *mapping = inode->i_mapping;
4624 ext4_lblk_t offsets[4];
4625 Indirect chain[4];
4626 Indirect *partial;
4627 __le32 nr = 0;
4628 int n;
4629 ext4_lblk_t last_block;
4630 unsigned blocksize = inode->i_sb->s_blocksize;
4632 if (!ext4_can_truncate(inode))
4633 return;
4635 ext4_clear_inode_flag(inode, EXT4_INODE_EOFBLOCKS);
4637 if (inode->i_size == 0 && !test_opt(inode->i_sb, NO_AUTO_DA_ALLOC))
4638 ext4_set_inode_state(inode, EXT4_STATE_DA_ALLOC_CLOSE);
4640 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
4641 ext4_ext_truncate(inode);
4642 return;
4645 handle = start_transaction(inode);
4646 if (IS_ERR(handle))
4647 return; /* AKPM: return what? */
4649 last_block = (inode->i_size + blocksize-1)
4650 >> EXT4_BLOCK_SIZE_BITS(inode->i_sb);
4652 if (inode->i_size & (blocksize - 1))
4653 if (ext4_block_truncate_page(handle, mapping, inode->i_size))
4654 goto out_stop;
4656 n = ext4_block_to_path(inode, last_block, offsets, NULL);
4657 if (n == 0)
4658 goto out_stop; /* error */
4661 * OK. This truncate is going to happen. We add the inode to the
4662 * orphan list, so that if this truncate spans multiple transactions,
4663 * and we crash, we will resume the truncate when the filesystem
4664 * recovers. It also marks the inode dirty, to catch the new size.
4666 * Implication: the file must always be in a sane, consistent
4667 * truncatable state while each transaction commits.
4669 if (ext4_orphan_add(handle, inode))
4670 goto out_stop;
4673 * From here we block out all ext4_get_block() callers who want to
4674 * modify the block allocation tree.
4676 down_write(&ei->i_data_sem);
4678 ext4_discard_preallocations(inode);
4681 * The orphan list entry will now protect us from any crash which
4682 * occurs before the truncate completes, so it is now safe to propagate
4683 * the new, shorter inode size (held for now in i_size) into the
4684 * on-disk inode. We do this via i_disksize, which is the value which
4685 * ext4 *really* writes onto the disk inode.
4687 ei->i_disksize = inode->i_size;
4689 if (n == 1) { /* direct blocks */
4690 ext4_free_data(handle, inode, NULL, i_data+offsets[0],
4691 i_data + EXT4_NDIR_BLOCKS);
4692 goto do_indirects;
4695 partial = ext4_find_shared(inode, n, offsets, chain, &nr);
4696 /* Kill the top of shared branch (not detached) */
4697 if (nr) {
4698 if (partial == chain) {
4699 /* Shared branch grows from the inode */
4700 ext4_free_branches(handle, inode, NULL,
4701 &nr, &nr+1, (chain+n-1) - partial);
4702 *partial->p = 0;
4704 * We mark the inode dirty prior to restart,
4705 * and prior to stop. No need for it here.
4707 } else {
4708 /* Shared branch grows from an indirect block */
4709 BUFFER_TRACE(partial->bh, "get_write_access");
4710 ext4_free_branches(handle, inode, partial->bh,
4711 partial->p,
4712 partial->p+1, (chain+n-1) - partial);
4715 /* Clear the ends of indirect blocks on the shared branch */
4716 while (partial > chain) {
4717 ext4_free_branches(handle, inode, partial->bh, partial->p + 1,
4718 (__le32*)partial->bh->b_data+addr_per_block,
4719 (chain+n-1) - partial);
4720 BUFFER_TRACE(partial->bh, "call brelse");
4721 brelse(partial->bh);
4722 partial--;
4724 do_indirects:
4725 /* Kill the remaining (whole) subtrees */
4726 switch (offsets[0]) {
4727 default:
4728 nr = i_data[EXT4_IND_BLOCK];
4729 if (nr) {
4730 ext4_free_branches(handle, inode, NULL, &nr, &nr+1, 1);
4731 i_data[EXT4_IND_BLOCK] = 0;
4733 case EXT4_IND_BLOCK:
4734 nr = i_data[EXT4_DIND_BLOCK];
4735 if (nr) {
4736 ext4_free_branches(handle, inode, NULL, &nr, &nr+1, 2);
4737 i_data[EXT4_DIND_BLOCK] = 0;
4739 case EXT4_DIND_BLOCK:
4740 nr = i_data[EXT4_TIND_BLOCK];
4741 if (nr) {
4742 ext4_free_branches(handle, inode, NULL, &nr, &nr+1, 3);
4743 i_data[EXT4_TIND_BLOCK] = 0;
4745 case EXT4_TIND_BLOCK:
4749 up_write(&ei->i_data_sem);
4750 inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
4751 ext4_mark_inode_dirty(handle, inode);
4754 * In a multi-transaction truncate, we only make the final transaction
4755 * synchronous
4757 if (IS_SYNC(inode))
4758 ext4_handle_sync(handle);
4759 out_stop:
4761 * If this was a simple ftruncate(), and the file will remain alive
4762 * then we need to clear up the orphan record which we created above.
4763 * However, if this was a real unlink then we were called by
4764 * ext4_delete_inode(), and we allow that function to clean up the
4765 * orphan info for us.
4767 if (inode->i_nlink)
4768 ext4_orphan_del(handle, inode);
4770 ext4_journal_stop(handle);
4774 * ext4_get_inode_loc returns with an extra refcount against the inode's
4775 * underlying buffer_head on success. If 'in_mem' is true, we have all
4776 * data in memory that is needed to recreate the on-disk version of this
4777 * inode.
4779 static int __ext4_get_inode_loc(struct inode *inode,
4780 struct ext4_iloc *iloc, int in_mem)
4782 struct ext4_group_desc *gdp;
4783 struct buffer_head *bh;
4784 struct super_block *sb = inode->i_sb;
4785 ext4_fsblk_t block;
4786 int inodes_per_block, inode_offset;
4788 iloc->bh = NULL;
4789 if (!ext4_valid_inum(sb, inode->i_ino))
4790 return -EIO;
4792 iloc->block_group = (inode->i_ino - 1) / EXT4_INODES_PER_GROUP(sb);
4793 gdp = ext4_get_group_desc(sb, iloc->block_group, NULL);
4794 if (!gdp)
4795 return -EIO;
4798 * Figure out the offset within the block group inode table
4800 inodes_per_block = (EXT4_BLOCK_SIZE(sb) / EXT4_INODE_SIZE(sb));
4801 inode_offset = ((inode->i_ino - 1) %
4802 EXT4_INODES_PER_GROUP(sb));
4803 block = ext4_inode_table(sb, gdp) + (inode_offset / inodes_per_block);
4804 iloc->offset = (inode_offset % inodes_per_block) * EXT4_INODE_SIZE(sb);
4806 bh = sb_getblk(sb, block);
4807 if (!bh) {
4808 EXT4_ERROR_INODE_BLOCK(inode, block,
4809 "unable to read itable block");
4810 return -EIO;
4812 if (!buffer_uptodate(bh)) {
4813 lock_buffer(bh);
4816 * If the buffer has the write error flag, we have failed
4817 * to write out another inode in the same block. In this
4818 * case, we don't have to read the block because we may
4819 * read the old inode data successfully.
4821 if (buffer_write_io_error(bh) && !buffer_uptodate(bh))
4822 set_buffer_uptodate(bh);
4824 if (buffer_uptodate(bh)) {
4825 /* someone brought it uptodate while we waited */
4826 unlock_buffer(bh);
4827 goto has_buffer;
4831 * If we have all information of the inode in memory and this
4832 * is the only valid inode in the block, we need not read the
4833 * block.
4835 if (in_mem) {
4836 struct buffer_head *bitmap_bh;
4837 int i, start;
4839 start = inode_offset & ~(inodes_per_block - 1);
4841 /* Is the inode bitmap in cache? */
4842 bitmap_bh = sb_getblk(sb, ext4_inode_bitmap(sb, gdp));
4843 if (!bitmap_bh)
4844 goto make_io;
4847 * If the inode bitmap isn't in cache then the
4848 * optimisation may end up performing two reads instead
4849 * of one, so skip it.
4851 if (!buffer_uptodate(bitmap_bh)) {
4852 brelse(bitmap_bh);
4853 goto make_io;
4855 for (i = start; i < start + inodes_per_block; i++) {
4856 if (i == inode_offset)
4857 continue;
4858 if (ext4_test_bit(i, bitmap_bh->b_data))
4859 break;
4861 brelse(bitmap_bh);
4862 if (i == start + inodes_per_block) {
4863 /* all other inodes are free, so skip I/O */
4864 memset(bh->b_data, 0, bh->b_size);
4865 set_buffer_uptodate(bh);
4866 unlock_buffer(bh);
4867 goto has_buffer;
4871 make_io:
4873 * If we need to do any I/O, try to pre-readahead extra
4874 * blocks from the inode table.
4876 if (EXT4_SB(sb)->s_inode_readahead_blks) {
4877 ext4_fsblk_t b, end, table;
4878 unsigned num;
4880 table = ext4_inode_table(sb, gdp);
4881 /* s_inode_readahead_blks is always a power of 2 */
4882 b = block & ~(EXT4_SB(sb)->s_inode_readahead_blks-1);
4883 if (table > b)
4884 b = table;
4885 end = b + EXT4_SB(sb)->s_inode_readahead_blks;
4886 num = EXT4_INODES_PER_GROUP(sb);
4887 if (EXT4_HAS_RO_COMPAT_FEATURE(sb,
4888 EXT4_FEATURE_RO_COMPAT_GDT_CSUM))
4889 num -= ext4_itable_unused_count(sb, gdp);
4890 table += num / inodes_per_block;
4891 if (end > table)
4892 end = table;
4893 while (b <= end)
4894 sb_breadahead(sb, b++);
4898 * There are other valid inodes in the buffer, this inode
4899 * has in-inode xattrs, or we don't have this inode in memory.
4900 * Read the block from disk.
4902 get_bh(bh);
4903 bh->b_end_io = end_buffer_read_sync;
4904 submit_bh(READ_META, bh);
4905 wait_on_buffer(bh);
4906 if (!buffer_uptodate(bh)) {
4907 EXT4_ERROR_INODE_BLOCK(inode, block,
4908 "unable to read itable block");
4909 brelse(bh);
4910 return -EIO;
4913 has_buffer:
4914 iloc->bh = bh;
4915 return 0;
4918 int ext4_get_inode_loc(struct inode *inode, struct ext4_iloc *iloc)
4920 /* We have all inode data except xattrs in memory here. */
4921 return __ext4_get_inode_loc(inode, iloc,
4922 !ext4_test_inode_state(inode, EXT4_STATE_XATTR));
4925 void ext4_set_inode_flags(struct inode *inode)
4927 unsigned int flags = EXT4_I(inode)->i_flags;
4929 inode->i_flags &= ~(S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME|S_DIRSYNC);
4930 if (flags & EXT4_SYNC_FL)
4931 inode->i_flags |= S_SYNC;
4932 if (flags & EXT4_APPEND_FL)
4933 inode->i_flags |= S_APPEND;
4934 if (flags & EXT4_IMMUTABLE_FL)
4935 inode->i_flags |= S_IMMUTABLE;
4936 if (flags & EXT4_NOATIME_FL)
4937 inode->i_flags |= S_NOATIME;
4938 if (flags & EXT4_DIRSYNC_FL)
4939 inode->i_flags |= S_DIRSYNC;
4942 /* Propagate flags from i_flags to EXT4_I(inode)->i_flags */
4943 void ext4_get_inode_flags(struct ext4_inode_info *ei)
4945 unsigned int vfs_fl;
4946 unsigned long old_fl, new_fl;
4948 do {
4949 vfs_fl = ei->vfs_inode.i_flags;
4950 old_fl = ei->i_flags;
4951 new_fl = old_fl & ~(EXT4_SYNC_FL|EXT4_APPEND_FL|
4952 EXT4_IMMUTABLE_FL|EXT4_NOATIME_FL|
4953 EXT4_DIRSYNC_FL);
4954 if (vfs_fl & S_SYNC)
4955 new_fl |= EXT4_SYNC_FL;
4956 if (vfs_fl & S_APPEND)
4957 new_fl |= EXT4_APPEND_FL;
4958 if (vfs_fl & S_IMMUTABLE)
4959 new_fl |= EXT4_IMMUTABLE_FL;
4960 if (vfs_fl & S_NOATIME)
4961 new_fl |= EXT4_NOATIME_FL;
4962 if (vfs_fl & S_DIRSYNC)
4963 new_fl |= EXT4_DIRSYNC_FL;
4964 } while (cmpxchg(&ei->i_flags, old_fl, new_fl) != old_fl);
4967 static blkcnt_t ext4_inode_blocks(struct ext4_inode *raw_inode,
4968 struct ext4_inode_info *ei)
4970 blkcnt_t i_blocks ;
4971 struct inode *inode = &(ei->vfs_inode);
4972 struct super_block *sb = inode->i_sb;
4974 if (EXT4_HAS_RO_COMPAT_FEATURE(sb,
4975 EXT4_FEATURE_RO_COMPAT_HUGE_FILE)) {
4976 /* we are using combined 48 bit field */
4977 i_blocks = ((u64)le16_to_cpu(raw_inode->i_blocks_high)) << 32 |
4978 le32_to_cpu(raw_inode->i_blocks_lo);
4979 if (ext4_test_inode_flag(inode, EXT4_INODE_HUGE_FILE)) {
4980 /* i_blocks represent file system block size */
4981 return i_blocks << (inode->i_blkbits - 9);
4982 } else {
4983 return i_blocks;
4985 } else {
4986 return le32_to_cpu(raw_inode->i_blocks_lo);
4990 struct inode *ext4_iget(struct super_block *sb, unsigned long ino)
4992 struct ext4_iloc iloc;
4993 struct ext4_inode *raw_inode;
4994 struct ext4_inode_info *ei;
4995 struct inode *inode;
4996 journal_t *journal = EXT4_SB(sb)->s_journal;
4997 long ret;
4998 int block;
5000 inode = iget_locked(sb, ino);
5001 if (!inode)
5002 return ERR_PTR(-ENOMEM);
5003 if (!(inode->i_state & I_NEW))
5004 return inode;
5006 ei = EXT4_I(inode);
5007 iloc.bh = 0;
5009 ret = __ext4_get_inode_loc(inode, &iloc, 0);
5010 if (ret < 0)
5011 goto bad_inode;
5012 raw_inode = ext4_raw_inode(&iloc);
5013 inode->i_mode = le16_to_cpu(raw_inode->i_mode);
5014 inode->i_uid = (uid_t)le16_to_cpu(raw_inode->i_uid_low);
5015 inode->i_gid = (gid_t)le16_to_cpu(raw_inode->i_gid_low);
5016 if (!(test_opt(inode->i_sb, NO_UID32))) {
5017 inode->i_uid |= le16_to_cpu(raw_inode->i_uid_high) << 16;
5018 inode->i_gid |= le16_to_cpu(raw_inode->i_gid_high) << 16;
5020 inode->i_nlink = le16_to_cpu(raw_inode->i_links_count);
5022 ei->i_state_flags = 0;
5023 ei->i_dir_start_lookup = 0;
5024 ei->i_dtime = le32_to_cpu(raw_inode->i_dtime);
5025 /* We now have enough fields to check if the inode was active or not.
5026 * This is needed because nfsd might try to access dead inodes
5027 * the test is that same one that e2fsck uses
5028 * NeilBrown 1999oct15
5030 if (inode->i_nlink == 0) {
5031 if (inode->i_mode == 0 ||
5032 !(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_ORPHAN_FS)) {
5033 /* this inode is deleted */
5034 ret = -ESTALE;
5035 goto bad_inode;
5037 /* The only unlinked inodes we let through here have
5038 * valid i_mode and are being read by the orphan
5039 * recovery code: that's fine, we're about to complete
5040 * the process of deleting those. */
5042 ei->i_flags = le32_to_cpu(raw_inode->i_flags);
5043 inode->i_blocks = ext4_inode_blocks(raw_inode, ei);
5044 ei->i_file_acl = le32_to_cpu(raw_inode->i_file_acl_lo);
5045 if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_64BIT))
5046 ei->i_file_acl |=
5047 ((__u64)le16_to_cpu(raw_inode->i_file_acl_high)) << 32;
5048 inode->i_size = ext4_isize(raw_inode);
5049 ei->i_disksize = inode->i_size;
5050 #ifdef CONFIG_QUOTA
5051 ei->i_reserved_quota = 0;
5052 #endif
5053 inode->i_generation = le32_to_cpu(raw_inode->i_generation);
5054 ei->i_block_group = iloc.block_group;
5055 ei->i_last_alloc_group = ~0;
5057 * NOTE! The in-memory inode i_data array is in little-endian order
5058 * even on big-endian machines: we do NOT byteswap the block numbers!
5060 for (block = 0; block < EXT4_N_BLOCKS; block++)
5061 ei->i_data[block] = raw_inode->i_block[block];
5062 INIT_LIST_HEAD(&ei->i_orphan);
5065 * Set transaction id's of transactions that have to be committed
5066 * to finish f[data]sync. We set them to currently running transaction
5067 * as we cannot be sure that the inode or some of its metadata isn't
5068 * part of the transaction - the inode could have been reclaimed and
5069 * now it is reread from disk.
5071 if (journal) {
5072 transaction_t *transaction;
5073 tid_t tid;
5075 read_lock(&journal->j_state_lock);
5076 if (journal->j_running_transaction)
5077 transaction = journal->j_running_transaction;
5078 else
5079 transaction = journal->j_committing_transaction;
5080 if (transaction)
5081 tid = transaction->t_tid;
5082 else
5083 tid = journal->j_commit_sequence;
5084 read_unlock(&journal->j_state_lock);
5085 ei->i_sync_tid = tid;
5086 ei->i_datasync_tid = tid;
5089 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
5090 ei->i_extra_isize = le16_to_cpu(raw_inode->i_extra_isize);
5091 if (EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize >
5092 EXT4_INODE_SIZE(inode->i_sb)) {
5093 ret = -EIO;
5094 goto bad_inode;
5096 if (ei->i_extra_isize == 0) {
5097 /* The extra space is currently unused. Use it. */
5098 ei->i_extra_isize = sizeof(struct ext4_inode) -
5099 EXT4_GOOD_OLD_INODE_SIZE;
5100 } else {
5101 __le32 *magic = (void *)raw_inode +
5102 EXT4_GOOD_OLD_INODE_SIZE +
5103 ei->i_extra_isize;
5104 if (*magic == cpu_to_le32(EXT4_XATTR_MAGIC))
5105 ext4_set_inode_state(inode, EXT4_STATE_XATTR);
5107 } else
5108 ei->i_extra_isize = 0;
5110 EXT4_INODE_GET_XTIME(i_ctime, inode, raw_inode);
5111 EXT4_INODE_GET_XTIME(i_mtime, inode, raw_inode);
5112 EXT4_INODE_GET_XTIME(i_atime, inode, raw_inode);
5113 EXT4_EINODE_GET_XTIME(i_crtime, ei, raw_inode);
5115 inode->i_version = le32_to_cpu(raw_inode->i_disk_version);
5116 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
5117 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
5118 inode->i_version |=
5119 (__u64)(le32_to_cpu(raw_inode->i_version_hi)) << 32;
5122 ret = 0;
5123 if (ei->i_file_acl &&
5124 !ext4_data_block_valid(EXT4_SB(sb), ei->i_file_acl, 1)) {
5125 EXT4_ERROR_INODE(inode, "bad extended attribute block %llu",
5126 ei->i_file_acl);
5127 ret = -EIO;
5128 goto bad_inode;
5129 } else if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
5130 if (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
5131 (S_ISLNK(inode->i_mode) &&
5132 !ext4_inode_is_fast_symlink(inode)))
5133 /* Validate extent which is part of inode */
5134 ret = ext4_ext_check_inode(inode);
5135 } else if (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
5136 (S_ISLNK(inode->i_mode) &&
5137 !ext4_inode_is_fast_symlink(inode))) {
5138 /* Validate block references which are part of inode */
5139 ret = ext4_check_inode_blockref(inode);
5141 if (ret)
5142 goto bad_inode;
5144 if (S_ISREG(inode->i_mode)) {
5145 inode->i_op = &ext4_file_inode_operations;
5146 inode->i_fop = &ext4_file_operations;
5147 ext4_set_aops(inode);
5148 } else if (S_ISDIR(inode->i_mode)) {
5149 inode->i_op = &ext4_dir_inode_operations;
5150 inode->i_fop = &ext4_dir_operations;
5151 } else if (S_ISLNK(inode->i_mode)) {
5152 if (ext4_inode_is_fast_symlink(inode)) {
5153 inode->i_op = &ext4_fast_symlink_inode_operations;
5154 nd_terminate_link(ei->i_data, inode->i_size,
5155 sizeof(ei->i_data) - 1);
5156 } else {
5157 inode->i_op = &ext4_symlink_inode_operations;
5158 ext4_set_aops(inode);
5160 } else if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode) ||
5161 S_ISFIFO(inode->i_mode) || S_ISSOCK(inode->i_mode)) {
5162 inode->i_op = &ext4_special_inode_operations;
5163 if (raw_inode->i_block[0])
5164 init_special_inode(inode, inode->i_mode,
5165 old_decode_dev(le32_to_cpu(raw_inode->i_block[0])));
5166 else
5167 init_special_inode(inode, inode->i_mode,
5168 new_decode_dev(le32_to_cpu(raw_inode->i_block[1])));
5169 } else {
5170 ret = -EIO;
5171 EXT4_ERROR_INODE(inode, "bogus i_mode (%o)", inode->i_mode);
5172 goto bad_inode;
5174 brelse(iloc.bh);
5175 ext4_set_inode_flags(inode);
5176 unlock_new_inode(inode);
5177 return inode;
5179 bad_inode:
5180 brelse(iloc.bh);
5181 iget_failed(inode);
5182 return ERR_PTR(ret);
5185 static int ext4_inode_blocks_set(handle_t *handle,
5186 struct ext4_inode *raw_inode,
5187 struct ext4_inode_info *ei)
5189 struct inode *inode = &(ei->vfs_inode);
5190 u64 i_blocks = inode->i_blocks;
5191 struct super_block *sb = inode->i_sb;
5193 if (i_blocks <= ~0U) {
5195 * i_blocks can be represnted in a 32 bit variable
5196 * as multiple of 512 bytes
5198 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
5199 raw_inode->i_blocks_high = 0;
5200 ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
5201 return 0;
5203 if (!EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_HUGE_FILE))
5204 return -EFBIG;
5206 if (i_blocks <= 0xffffffffffffULL) {
5208 * i_blocks can be represented in a 48 bit variable
5209 * as multiple of 512 bytes
5211 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
5212 raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
5213 ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
5214 } else {
5215 ext4_set_inode_flag(inode, EXT4_INODE_HUGE_FILE);
5216 /* i_block is stored in file system block size */
5217 i_blocks = i_blocks >> (inode->i_blkbits - 9);
5218 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
5219 raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
5221 return 0;
5225 * Post the struct inode info into an on-disk inode location in the
5226 * buffer-cache. This gobbles the caller's reference to the
5227 * buffer_head in the inode location struct.
5229 * The caller must have write access to iloc->bh.
5231 static int ext4_do_update_inode(handle_t *handle,
5232 struct inode *inode,
5233 struct ext4_iloc *iloc)
5235 struct ext4_inode *raw_inode = ext4_raw_inode(iloc);
5236 struct ext4_inode_info *ei = EXT4_I(inode);
5237 struct buffer_head *bh = iloc->bh;
5238 int err = 0, rc, block;
5240 /* For fields not not tracking in the in-memory inode,
5241 * initialise them to zero for new inodes. */
5242 if (ext4_test_inode_state(inode, EXT4_STATE_NEW))
5243 memset(raw_inode, 0, EXT4_SB(inode->i_sb)->s_inode_size);
5245 ext4_get_inode_flags(ei);
5246 raw_inode->i_mode = cpu_to_le16(inode->i_mode);
5247 if (!(test_opt(inode->i_sb, NO_UID32))) {
5248 raw_inode->i_uid_low = cpu_to_le16(low_16_bits(inode->i_uid));
5249 raw_inode->i_gid_low = cpu_to_le16(low_16_bits(inode->i_gid));
5251 * Fix up interoperability with old kernels. Otherwise, old inodes get
5252 * re-used with the upper 16 bits of the uid/gid intact
5254 if (!ei->i_dtime) {
5255 raw_inode->i_uid_high =
5256 cpu_to_le16(high_16_bits(inode->i_uid));
5257 raw_inode->i_gid_high =
5258 cpu_to_le16(high_16_bits(inode->i_gid));
5259 } else {
5260 raw_inode->i_uid_high = 0;
5261 raw_inode->i_gid_high = 0;
5263 } else {
5264 raw_inode->i_uid_low =
5265 cpu_to_le16(fs_high2lowuid(inode->i_uid));
5266 raw_inode->i_gid_low =
5267 cpu_to_le16(fs_high2lowgid(inode->i_gid));
5268 raw_inode->i_uid_high = 0;
5269 raw_inode->i_gid_high = 0;
5271 raw_inode->i_links_count = cpu_to_le16(inode->i_nlink);
5273 EXT4_INODE_SET_XTIME(i_ctime, inode, raw_inode);
5274 EXT4_INODE_SET_XTIME(i_mtime, inode, raw_inode);
5275 EXT4_INODE_SET_XTIME(i_atime, inode, raw_inode);
5276 EXT4_EINODE_SET_XTIME(i_crtime, ei, raw_inode);
5278 if (ext4_inode_blocks_set(handle, raw_inode, ei))
5279 goto out_brelse;
5280 raw_inode->i_dtime = cpu_to_le32(ei->i_dtime);
5281 raw_inode->i_flags = cpu_to_le32(ei->i_flags);
5282 if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
5283 cpu_to_le32(EXT4_OS_HURD))
5284 raw_inode->i_file_acl_high =
5285 cpu_to_le16(ei->i_file_acl >> 32);
5286 raw_inode->i_file_acl_lo = cpu_to_le32(ei->i_file_acl);
5287 ext4_isize_set(raw_inode, ei->i_disksize);
5288 if (ei->i_disksize > 0x7fffffffULL) {
5289 struct super_block *sb = inode->i_sb;
5290 if (!EXT4_HAS_RO_COMPAT_FEATURE(sb,
5291 EXT4_FEATURE_RO_COMPAT_LARGE_FILE) ||
5292 EXT4_SB(sb)->s_es->s_rev_level ==
5293 cpu_to_le32(EXT4_GOOD_OLD_REV)) {
5294 /* If this is the first large file
5295 * created, add a flag to the superblock.
5297 err = ext4_journal_get_write_access(handle,
5298 EXT4_SB(sb)->s_sbh);
5299 if (err)
5300 goto out_brelse;
5301 ext4_update_dynamic_rev(sb);
5302 EXT4_SET_RO_COMPAT_FEATURE(sb,
5303 EXT4_FEATURE_RO_COMPAT_LARGE_FILE);
5304 sb->s_dirt = 1;
5305 ext4_handle_sync(handle);
5306 err = ext4_handle_dirty_metadata(handle, NULL,
5307 EXT4_SB(sb)->s_sbh);
5310 raw_inode->i_generation = cpu_to_le32(inode->i_generation);
5311 if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) {
5312 if (old_valid_dev(inode->i_rdev)) {
5313 raw_inode->i_block[0] =
5314 cpu_to_le32(old_encode_dev(inode->i_rdev));
5315 raw_inode->i_block[1] = 0;
5316 } else {
5317 raw_inode->i_block[0] = 0;
5318 raw_inode->i_block[1] =
5319 cpu_to_le32(new_encode_dev(inode->i_rdev));
5320 raw_inode->i_block[2] = 0;
5322 } else
5323 for (block = 0; block < EXT4_N_BLOCKS; block++)
5324 raw_inode->i_block[block] = ei->i_data[block];
5326 raw_inode->i_disk_version = cpu_to_le32(inode->i_version);
5327 if (ei->i_extra_isize) {
5328 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
5329 raw_inode->i_version_hi =
5330 cpu_to_le32(inode->i_version >> 32);
5331 raw_inode->i_extra_isize = cpu_to_le16(ei->i_extra_isize);
5334 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
5335 rc = ext4_handle_dirty_metadata(handle, NULL, bh);
5336 if (!err)
5337 err = rc;
5338 ext4_clear_inode_state(inode, EXT4_STATE_NEW);
5340 ext4_update_inode_fsync_trans(handle, inode, 0);
5341 out_brelse:
5342 brelse(bh);
5343 ext4_std_error(inode->i_sb, err);
5344 return err;
5348 * ext4_write_inode()
5350 * We are called from a few places:
5352 * - Within generic_file_write() for O_SYNC files.
5353 * Here, there will be no transaction running. We wait for any running
5354 * trasnaction to commit.
5356 * - Within sys_sync(), kupdate and such.
5357 * We wait on commit, if tol to.
5359 * - Within prune_icache() (PF_MEMALLOC == true)
5360 * Here we simply return. We can't afford to block kswapd on the
5361 * journal commit.
5363 * In all cases it is actually safe for us to return without doing anything,
5364 * because the inode has been copied into a raw inode buffer in
5365 * ext4_mark_inode_dirty(). This is a correctness thing for O_SYNC and for
5366 * knfsd.
5368 * Note that we are absolutely dependent upon all inode dirtiers doing the
5369 * right thing: they *must* call mark_inode_dirty() after dirtying info in
5370 * which we are interested.
5372 * It would be a bug for them to not do this. The code:
5374 * mark_inode_dirty(inode)
5375 * stuff();
5376 * inode->i_size = expr;
5378 * is in error because a kswapd-driven write_inode() could occur while
5379 * `stuff()' is running, and the new i_size will be lost. Plus the inode
5380 * will no longer be on the superblock's dirty inode list.
5382 int ext4_write_inode(struct inode *inode, struct writeback_control *wbc)
5384 int err;
5386 if (current->flags & PF_MEMALLOC)
5387 return 0;
5389 if (EXT4_SB(inode->i_sb)->s_journal) {
5390 if (ext4_journal_current_handle()) {
5391 jbd_debug(1, "called recursively, non-PF_MEMALLOC!\n");
5392 dump_stack();
5393 return -EIO;
5396 if (wbc->sync_mode != WB_SYNC_ALL)
5397 return 0;
5399 err = ext4_force_commit(inode->i_sb);
5400 } else {
5401 struct ext4_iloc iloc;
5403 err = __ext4_get_inode_loc(inode, &iloc, 0);
5404 if (err)
5405 return err;
5406 if (wbc->sync_mode == WB_SYNC_ALL)
5407 sync_dirty_buffer(iloc.bh);
5408 if (buffer_req(iloc.bh) && !buffer_uptodate(iloc.bh)) {
5409 EXT4_ERROR_INODE_BLOCK(inode, iloc.bh->b_blocknr,
5410 "IO error syncing inode");
5411 err = -EIO;
5413 brelse(iloc.bh);
5415 return err;
5419 * ext4_setattr()
5421 * Called from notify_change.
5423 * We want to trap VFS attempts to truncate the file as soon as
5424 * possible. In particular, we want to make sure that when the VFS
5425 * shrinks i_size, we put the inode on the orphan list and modify
5426 * i_disksize immediately, so that during the subsequent flushing of
5427 * dirty pages and freeing of disk blocks, we can guarantee that any
5428 * commit will leave the blocks being flushed in an unused state on
5429 * disk. (On recovery, the inode will get truncated and the blocks will
5430 * be freed, so we have a strong guarantee that no future commit will
5431 * leave these blocks visible to the user.)
5433 * Another thing we have to assure is that if we are in ordered mode
5434 * and inode is still attached to the committing transaction, we must
5435 * we start writeout of all the dirty pages which are being truncated.
5436 * This way we are sure that all the data written in the previous
5437 * transaction are already on disk (truncate waits for pages under
5438 * writeback).
5440 * Called with inode->i_mutex down.
5442 int ext4_setattr(struct dentry *dentry, struct iattr *attr)
5444 struct inode *inode = dentry->d_inode;
5445 int error, rc = 0;
5446 const unsigned int ia_valid = attr->ia_valid;
5448 error = inode_change_ok(inode, attr);
5449 if (error)
5450 return error;
5452 if (is_quota_modification(inode, attr))
5453 dquot_initialize(inode);
5454 if ((ia_valid & ATTR_UID && attr->ia_uid != inode->i_uid) ||
5455 (ia_valid & ATTR_GID && attr->ia_gid != inode->i_gid)) {
5456 handle_t *handle;
5458 /* (user+group)*(old+new) structure, inode write (sb,
5459 * inode block, ? - but truncate inode update has it) */
5460 handle = ext4_journal_start(inode, (EXT4_MAXQUOTAS_INIT_BLOCKS(inode->i_sb)+
5461 EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb))+3);
5462 if (IS_ERR(handle)) {
5463 error = PTR_ERR(handle);
5464 goto err_out;
5466 error = dquot_transfer(inode, attr);
5467 if (error) {
5468 ext4_journal_stop(handle);
5469 return error;
5471 /* Update corresponding info in inode so that everything is in
5472 * one transaction */
5473 if (attr->ia_valid & ATTR_UID)
5474 inode->i_uid = attr->ia_uid;
5475 if (attr->ia_valid & ATTR_GID)
5476 inode->i_gid = attr->ia_gid;
5477 error = ext4_mark_inode_dirty(handle, inode);
5478 ext4_journal_stop(handle);
5481 if (attr->ia_valid & ATTR_SIZE) {
5482 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
5483 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
5485 if (attr->ia_size > sbi->s_bitmap_maxbytes)
5486 return -EFBIG;
5490 if (S_ISREG(inode->i_mode) &&
5491 attr->ia_valid & ATTR_SIZE &&
5492 (attr->ia_size < inode->i_size ||
5493 (ext4_test_inode_flag(inode, EXT4_INODE_EOFBLOCKS)))) {
5494 handle_t *handle;
5496 handle = ext4_journal_start(inode, 3);
5497 if (IS_ERR(handle)) {
5498 error = PTR_ERR(handle);
5499 goto err_out;
5502 error = ext4_orphan_add(handle, inode);
5503 EXT4_I(inode)->i_disksize = attr->ia_size;
5504 rc = ext4_mark_inode_dirty(handle, inode);
5505 if (!error)
5506 error = rc;
5507 ext4_journal_stop(handle);
5509 if (ext4_should_order_data(inode)) {
5510 error = ext4_begin_ordered_truncate(inode,
5511 attr->ia_size);
5512 if (error) {
5513 /* Do as much error cleanup as possible */
5514 handle = ext4_journal_start(inode, 3);
5515 if (IS_ERR(handle)) {
5516 ext4_orphan_del(NULL, inode);
5517 goto err_out;
5519 ext4_orphan_del(handle, inode);
5520 ext4_journal_stop(handle);
5521 goto err_out;
5524 /* ext4_truncate will clear the flag */
5525 if ((ext4_test_inode_flag(inode, EXT4_INODE_EOFBLOCKS)))
5526 ext4_truncate(inode);
5529 if ((attr->ia_valid & ATTR_SIZE) &&
5530 attr->ia_size != i_size_read(inode))
5531 rc = vmtruncate(inode, attr->ia_size);
5533 if (!rc) {
5534 setattr_copy(inode, attr);
5535 mark_inode_dirty(inode);
5539 * If the call to ext4_truncate failed to get a transaction handle at
5540 * all, we need to clean up the in-core orphan list manually.
5542 if (inode->i_nlink)
5543 ext4_orphan_del(NULL, inode);
5545 if (!rc && (ia_valid & ATTR_MODE))
5546 rc = ext4_acl_chmod(inode);
5548 err_out:
5549 ext4_std_error(inode->i_sb, error);
5550 if (!error)
5551 error = rc;
5552 return error;
5555 int ext4_getattr(struct vfsmount *mnt, struct dentry *dentry,
5556 struct kstat *stat)
5558 struct inode *inode;
5559 unsigned long delalloc_blocks;
5561 inode = dentry->d_inode;
5562 generic_fillattr(inode, stat);
5565 * We can't update i_blocks if the block allocation is delayed
5566 * otherwise in the case of system crash before the real block
5567 * allocation is done, we will have i_blocks inconsistent with
5568 * on-disk file blocks.
5569 * We always keep i_blocks updated together with real
5570 * allocation. But to not confuse with user, stat
5571 * will return the blocks that include the delayed allocation
5572 * blocks for this file.
5574 spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
5575 delalloc_blocks = EXT4_I(inode)->i_reserved_data_blocks;
5576 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
5578 stat->blocks += (delalloc_blocks << inode->i_sb->s_blocksize_bits)>>9;
5579 return 0;
5582 static int ext4_indirect_trans_blocks(struct inode *inode, int nrblocks,
5583 int chunk)
5585 int indirects;
5587 /* if nrblocks are contiguous */
5588 if (chunk) {
5590 * With N contiguous data blocks, it need at most
5591 * N/EXT4_ADDR_PER_BLOCK(inode->i_sb) indirect blocks
5592 * 2 dindirect blocks
5593 * 1 tindirect block
5595 indirects = nrblocks / EXT4_ADDR_PER_BLOCK(inode->i_sb);
5596 return indirects + 3;
5599 * if nrblocks are not contiguous, worse case, each block touch
5600 * a indirect block, and each indirect block touch a double indirect
5601 * block, plus a triple indirect block
5603 indirects = nrblocks * 2 + 1;
5604 return indirects;
5607 static int ext4_index_trans_blocks(struct inode *inode, int nrblocks, int chunk)
5609 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
5610 return ext4_indirect_trans_blocks(inode, nrblocks, chunk);
5611 return ext4_ext_index_trans_blocks(inode, nrblocks, chunk);
5615 * Account for index blocks, block groups bitmaps and block group
5616 * descriptor blocks if modify datablocks and index blocks
5617 * worse case, the indexs blocks spread over different block groups
5619 * If datablocks are discontiguous, they are possible to spread over
5620 * different block groups too. If they are contiuguous, with flexbg,
5621 * they could still across block group boundary.
5623 * Also account for superblock, inode, quota and xattr blocks
5625 int ext4_meta_trans_blocks(struct inode *inode, int nrblocks, int chunk)
5627 ext4_group_t groups, ngroups = ext4_get_groups_count(inode->i_sb);
5628 int gdpblocks;
5629 int idxblocks;
5630 int ret = 0;
5633 * How many index blocks need to touch to modify nrblocks?
5634 * The "Chunk" flag indicating whether the nrblocks is
5635 * physically contiguous on disk
5637 * For Direct IO and fallocate, they calls get_block to allocate
5638 * one single extent at a time, so they could set the "Chunk" flag
5640 idxblocks = ext4_index_trans_blocks(inode, nrblocks, chunk);
5642 ret = idxblocks;
5645 * Now let's see how many group bitmaps and group descriptors need
5646 * to account
5648 groups = idxblocks;
5649 if (chunk)
5650 groups += 1;
5651 else
5652 groups += nrblocks;
5654 gdpblocks = groups;
5655 if (groups > ngroups)
5656 groups = ngroups;
5657 if (groups > EXT4_SB(inode->i_sb)->s_gdb_count)
5658 gdpblocks = EXT4_SB(inode->i_sb)->s_gdb_count;
5660 /* bitmaps and block group descriptor blocks */
5661 ret += groups + gdpblocks;
5663 /* Blocks for super block, inode, quota and xattr blocks */
5664 ret += EXT4_META_TRANS_BLOCKS(inode->i_sb);
5666 return ret;
5670 * Calulate the total number of credits to reserve to fit
5671 * the modification of a single pages into a single transaction,
5672 * which may include multiple chunks of block allocations.
5674 * This could be called via ext4_write_begin()
5676 * We need to consider the worse case, when
5677 * one new block per extent.
5679 int ext4_writepage_trans_blocks(struct inode *inode)
5681 int bpp = ext4_journal_blocks_per_page(inode);
5682 int ret;
5684 ret = ext4_meta_trans_blocks(inode, bpp, 0);
5686 /* Account for data blocks for journalled mode */
5687 if (ext4_should_journal_data(inode))
5688 ret += bpp;
5689 return ret;
5693 * Calculate the journal credits for a chunk of data modification.
5695 * This is called from DIO, fallocate or whoever calling
5696 * ext4_map_blocks() to map/allocate a chunk of contiguous disk blocks.
5698 * journal buffers for data blocks are not included here, as DIO
5699 * and fallocate do no need to journal data buffers.
5701 int ext4_chunk_trans_blocks(struct inode *inode, int nrblocks)
5703 return ext4_meta_trans_blocks(inode, nrblocks, 1);
5707 * The caller must have previously called ext4_reserve_inode_write().
5708 * Give this, we know that the caller already has write access to iloc->bh.
5710 int ext4_mark_iloc_dirty(handle_t *handle,
5711 struct inode *inode, struct ext4_iloc *iloc)
5713 int err = 0;
5715 if (test_opt(inode->i_sb, I_VERSION))
5716 inode_inc_iversion(inode);
5718 /* the do_update_inode consumes one bh->b_count */
5719 get_bh(iloc->bh);
5721 /* ext4_do_update_inode() does jbd2_journal_dirty_metadata */
5722 err = ext4_do_update_inode(handle, inode, iloc);
5723 put_bh(iloc->bh);
5724 return err;
5728 * On success, We end up with an outstanding reference count against
5729 * iloc->bh. This _must_ be cleaned up later.
5733 ext4_reserve_inode_write(handle_t *handle, struct inode *inode,
5734 struct ext4_iloc *iloc)
5736 int err;
5738 err = ext4_get_inode_loc(inode, iloc);
5739 if (!err) {
5740 BUFFER_TRACE(iloc->bh, "get_write_access");
5741 err = ext4_journal_get_write_access(handle, iloc->bh);
5742 if (err) {
5743 brelse(iloc->bh);
5744 iloc->bh = NULL;
5747 ext4_std_error(inode->i_sb, err);
5748 return err;
5752 * Expand an inode by new_extra_isize bytes.
5753 * Returns 0 on success or negative error number on failure.
5755 static int ext4_expand_extra_isize(struct inode *inode,
5756 unsigned int new_extra_isize,
5757 struct ext4_iloc iloc,
5758 handle_t *handle)
5760 struct ext4_inode *raw_inode;
5761 struct ext4_xattr_ibody_header *header;
5763 if (EXT4_I(inode)->i_extra_isize >= new_extra_isize)
5764 return 0;
5766 raw_inode = ext4_raw_inode(&iloc);
5768 header = IHDR(inode, raw_inode);
5770 /* No extended attributes present */
5771 if (!ext4_test_inode_state(inode, EXT4_STATE_XATTR) ||
5772 header->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC)) {
5773 memset((void *)raw_inode + EXT4_GOOD_OLD_INODE_SIZE, 0,
5774 new_extra_isize);
5775 EXT4_I(inode)->i_extra_isize = new_extra_isize;
5776 return 0;
5779 /* try to expand with EAs present */
5780 return ext4_expand_extra_isize_ea(inode, new_extra_isize,
5781 raw_inode, handle);
5785 * What we do here is to mark the in-core inode as clean with respect to inode
5786 * dirtiness (it may still be data-dirty).
5787 * This means that the in-core inode may be reaped by prune_icache
5788 * without having to perform any I/O. This is a very good thing,
5789 * because *any* task may call prune_icache - even ones which
5790 * have a transaction open against a different journal.
5792 * Is this cheating? Not really. Sure, we haven't written the
5793 * inode out, but prune_icache isn't a user-visible syncing function.
5794 * Whenever the user wants stuff synced (sys_sync, sys_msync, sys_fsync)
5795 * we start and wait on commits.
5797 * Is this efficient/effective? Well, we're being nice to the system
5798 * by cleaning up our inodes proactively so they can be reaped
5799 * without I/O. But we are potentially leaving up to five seconds'
5800 * worth of inodes floating about which prune_icache wants us to
5801 * write out. One way to fix that would be to get prune_icache()
5802 * to do a write_super() to free up some memory. It has the desired
5803 * effect.
5805 int ext4_mark_inode_dirty(handle_t *handle, struct inode *inode)
5807 struct ext4_iloc iloc;
5808 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
5809 static unsigned int mnt_count;
5810 int err, ret;
5812 might_sleep();
5813 err = ext4_reserve_inode_write(handle, inode, &iloc);
5814 if (ext4_handle_valid(handle) &&
5815 EXT4_I(inode)->i_extra_isize < sbi->s_want_extra_isize &&
5816 !ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND)) {
5818 * We need extra buffer credits since we may write into EA block
5819 * with this same handle. If journal_extend fails, then it will
5820 * only result in a minor loss of functionality for that inode.
5821 * If this is felt to be critical, then e2fsck should be run to
5822 * force a large enough s_min_extra_isize.
5824 if ((jbd2_journal_extend(handle,
5825 EXT4_DATA_TRANS_BLOCKS(inode->i_sb))) == 0) {
5826 ret = ext4_expand_extra_isize(inode,
5827 sbi->s_want_extra_isize,
5828 iloc, handle);
5829 if (ret) {
5830 ext4_set_inode_state(inode,
5831 EXT4_STATE_NO_EXPAND);
5832 if (mnt_count !=
5833 le16_to_cpu(sbi->s_es->s_mnt_count)) {
5834 ext4_warning(inode->i_sb,
5835 "Unable to expand inode %lu. Delete"
5836 " some EAs or run e2fsck.",
5837 inode->i_ino);
5838 mnt_count =
5839 le16_to_cpu(sbi->s_es->s_mnt_count);
5844 if (!err)
5845 err = ext4_mark_iloc_dirty(handle, inode, &iloc);
5846 return err;
5850 * ext4_dirty_inode() is called from __mark_inode_dirty()
5852 * We're really interested in the case where a file is being extended.
5853 * i_size has been changed by generic_commit_write() and we thus need
5854 * to include the updated inode in the current transaction.
5856 * Also, dquot_alloc_block() will always dirty the inode when blocks
5857 * are allocated to the file.
5859 * If the inode is marked synchronous, we don't honour that here - doing
5860 * so would cause a commit on atime updates, which we don't bother doing.
5861 * We handle synchronous inodes at the highest possible level.
5863 void ext4_dirty_inode(struct inode *inode)
5865 handle_t *handle;
5867 handle = ext4_journal_start(inode, 2);
5868 if (IS_ERR(handle))
5869 goto out;
5871 ext4_mark_inode_dirty(handle, inode);
5873 ext4_journal_stop(handle);
5874 out:
5875 return;
5879 int ext4_change_inode_journal_flag(struct inode *inode, int val)
5881 journal_t *journal;
5882 handle_t *handle;
5883 int err;
5886 * We have to be very careful here: changing a data block's
5887 * journaling status dynamically is dangerous. If we write a
5888 * data block to the journal, change the status and then delete
5889 * that block, we risk forgetting to revoke the old log record
5890 * from the journal and so a subsequent replay can corrupt data.
5891 * So, first we make sure that the journal is empty and that
5892 * nobody is changing anything.
5895 journal = EXT4_JOURNAL(inode);
5896 if (!journal)
5897 return 0;
5898 if (is_journal_aborted(journal))
5899 return -EROFS;
5901 jbd2_journal_lock_updates(journal);
5902 jbd2_journal_flush(journal);
5905 * OK, there are no updates running now, and all cached data is
5906 * synced to disk. We are now in a completely consistent state
5907 * which doesn't have anything in the journal, and we know that
5908 * no filesystem updates are running, so it is safe to modify
5909 * the inode's in-core data-journaling state flag now.
5912 if (val)
5913 ext4_set_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
5914 else
5915 ext4_clear_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
5916 ext4_set_aops(inode);
5918 jbd2_journal_unlock_updates(journal);
5920 /* Finally we can mark the inode as dirty. */
5922 handle = ext4_journal_start(inode, 1);
5923 if (IS_ERR(handle))
5924 return PTR_ERR(handle);
5926 err = ext4_mark_inode_dirty(handle, inode);
5927 ext4_handle_sync(handle);
5928 ext4_journal_stop(handle);
5929 ext4_std_error(inode->i_sb, err);
5931 return err;
5934 static int ext4_bh_unmapped(handle_t *handle, struct buffer_head *bh)
5936 return !buffer_mapped(bh);
5939 int ext4_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
5941 struct page *page = vmf->page;
5942 loff_t size;
5943 unsigned long len;
5944 int ret = -EINVAL;
5945 void *fsdata;
5946 struct file *file = vma->vm_file;
5947 struct inode *inode = file->f_path.dentry->d_inode;
5948 struct address_space *mapping = inode->i_mapping;
5951 * Get i_alloc_sem to stop truncates messing with the inode. We cannot
5952 * get i_mutex because we are already holding mmap_sem.
5954 down_read(&inode->i_alloc_sem);
5955 size = i_size_read(inode);
5956 if (page->mapping != mapping || size <= page_offset(page)
5957 || !PageUptodate(page)) {
5958 /* page got truncated from under us? */
5959 goto out_unlock;
5961 ret = 0;
5962 if (PageMappedToDisk(page))
5963 goto out_unlock;
5965 if (page->index == size >> PAGE_CACHE_SHIFT)
5966 len = size & ~PAGE_CACHE_MASK;
5967 else
5968 len = PAGE_CACHE_SIZE;
5970 lock_page(page);
5972 * return if we have all the buffers mapped. This avoid
5973 * the need to call write_begin/write_end which does a
5974 * journal_start/journal_stop which can block and take
5975 * long time
5977 if (page_has_buffers(page)) {
5978 if (!walk_page_buffers(NULL, page_buffers(page), 0, len, NULL,
5979 ext4_bh_unmapped)) {
5980 unlock_page(page);
5981 goto out_unlock;
5984 unlock_page(page);
5986 * OK, we need to fill the hole... Do write_begin write_end
5987 * to do block allocation/reservation.We are not holding
5988 * inode.i__mutex here. That allow * parallel write_begin,
5989 * write_end call. lock_page prevent this from happening
5990 * on the same page though
5992 ret = mapping->a_ops->write_begin(file, mapping, page_offset(page),
5993 len, AOP_FLAG_UNINTERRUPTIBLE, &page, &fsdata);
5994 if (ret < 0)
5995 goto out_unlock;
5996 ret = mapping->a_ops->write_end(file, mapping, page_offset(page),
5997 len, len, page, fsdata);
5998 if (ret < 0)
5999 goto out_unlock;
6000 ret = 0;
6001 out_unlock:
6002 if (ret)
6003 ret = VM_FAULT_SIGBUS;
6004 up_read(&inode->i_alloc_sem);
6005 return ret;