md: Fix unfortunate interaction with evms
[linux-2.6/mini2440.git] / fs / ext4 / inode.c
blob38b21549def95cb1434393d2064d8006473ae0c0
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>
42 #include "ext4_jbd2.h"
43 #include "xattr.h"
44 #include "acl.h"
45 #include "ext4_extents.h"
47 #include <trace/events/ext4.h>
49 #define MPAGE_DA_EXTENT_TAIL 0x01
51 static inline int ext4_begin_ordered_truncate(struct inode *inode,
52 loff_t new_size)
54 return jbd2_journal_begin_ordered_truncate(
55 EXT4_SB(inode->i_sb)->s_journal,
56 &EXT4_I(inode)->jinode,
57 new_size);
60 static void ext4_invalidatepage(struct page *page, unsigned long offset);
63 * Test whether an inode is a fast symlink.
65 static int ext4_inode_is_fast_symlink(struct inode *inode)
67 int ea_blocks = EXT4_I(inode)->i_file_acl ?
68 (inode->i_sb->s_blocksize >> 9) : 0;
70 return (S_ISLNK(inode->i_mode) && inode->i_blocks - ea_blocks == 0);
74 * The ext4 forget function must perform a revoke if we are freeing data
75 * which has been journaled. Metadata (eg. indirect blocks) must be
76 * revoked in all cases.
78 * "bh" may be NULL: a metadata block may have been freed from memory
79 * but there may still be a record of it in the journal, and that record
80 * still needs to be revoked.
82 * If the handle isn't valid we're not journaling, but we still need to
83 * call into ext4_journal_revoke() to put the buffer head.
85 int ext4_forget(handle_t *handle, int is_metadata, struct inode *inode,
86 struct buffer_head *bh, ext4_fsblk_t blocknr)
88 int err;
90 might_sleep();
92 BUFFER_TRACE(bh, "enter");
94 jbd_debug(4, "forgetting bh %p: is_metadata = %d, mode %o, "
95 "data mode %x\n",
96 bh, is_metadata, inode->i_mode,
97 test_opt(inode->i_sb, DATA_FLAGS));
99 /* Never use the revoke function if we are doing full data
100 * journaling: there is no need to, and a V1 superblock won't
101 * support it. Otherwise, only skip the revoke on un-journaled
102 * data blocks. */
104 if (test_opt(inode->i_sb, DATA_FLAGS) == EXT4_MOUNT_JOURNAL_DATA ||
105 (!is_metadata && !ext4_should_journal_data(inode))) {
106 if (bh) {
107 BUFFER_TRACE(bh, "call jbd2_journal_forget");
108 return ext4_journal_forget(handle, bh);
110 return 0;
114 * data!=journal && (is_metadata || should_journal_data(inode))
116 BUFFER_TRACE(bh, "call ext4_journal_revoke");
117 err = ext4_journal_revoke(handle, blocknr, bh);
118 if (err)
119 ext4_abort(inode->i_sb, __func__,
120 "error %d when attempting revoke", err);
121 BUFFER_TRACE(bh, "exit");
122 return err;
126 * Work out how many blocks we need to proceed with the next chunk of a
127 * truncate transaction.
129 static unsigned long blocks_for_truncate(struct inode *inode)
131 ext4_lblk_t needed;
133 needed = inode->i_blocks >> (inode->i_sb->s_blocksize_bits - 9);
135 /* Give ourselves just enough room to cope with inodes in which
136 * i_blocks is corrupt: we've seen disk corruptions in the past
137 * which resulted in random data in an inode which looked enough
138 * like a regular file for ext4 to try to delete it. Things
139 * will go a bit crazy if that happens, but at least we should
140 * try not to panic the whole kernel. */
141 if (needed < 2)
142 needed = 2;
144 /* But we need to bound the transaction so we don't overflow the
145 * journal. */
146 if (needed > EXT4_MAX_TRANS_DATA)
147 needed = EXT4_MAX_TRANS_DATA;
149 return EXT4_DATA_TRANS_BLOCKS(inode->i_sb) + needed;
153 * Truncate transactions can be complex and absolutely huge. So we need to
154 * be able to restart the transaction at a conventient checkpoint to make
155 * sure we don't overflow the journal.
157 * start_transaction gets us a new handle for a truncate transaction,
158 * and extend_transaction tries to extend the existing one a bit. If
159 * extend fails, we need to propagate the failure up and restart the
160 * transaction in the top-level truncate loop. --sct
162 static handle_t *start_transaction(struct inode *inode)
164 handle_t *result;
166 result = ext4_journal_start(inode, blocks_for_truncate(inode));
167 if (!IS_ERR(result))
168 return result;
170 ext4_std_error(inode->i_sb, PTR_ERR(result));
171 return result;
175 * Try to extend this transaction for the purposes of truncation.
177 * Returns 0 if we managed to create more room. If we can't create more
178 * room, and the transaction must be restarted we return 1.
180 static int try_to_extend_transaction(handle_t *handle, struct inode *inode)
182 if (!ext4_handle_valid(handle))
183 return 0;
184 if (ext4_handle_has_enough_credits(handle, EXT4_RESERVE_TRANS_BLOCKS+1))
185 return 0;
186 if (!ext4_journal_extend(handle, blocks_for_truncate(inode)))
187 return 0;
188 return 1;
192 * Restart the transaction associated with *handle. This does a commit,
193 * so before we call here everything must be consistently dirtied against
194 * this transaction.
196 int ext4_truncate_restart_trans(handle_t *handle, struct inode *inode,
197 int nblocks)
199 int ret;
202 * Drop i_data_sem to avoid deadlock with ext4_get_blocks At this
203 * moment, get_block can be called only for blocks inside i_size since
204 * page cache has been already dropped and writes are blocked by
205 * i_mutex. So we can safely drop the i_data_sem here.
207 BUG_ON(EXT4_JOURNAL(inode) == NULL);
208 jbd_debug(2, "restarting handle %p\n", handle);
209 up_write(&EXT4_I(inode)->i_data_sem);
210 ret = ext4_journal_restart(handle, blocks_for_truncate(inode));
211 down_write(&EXT4_I(inode)->i_data_sem);
212 ext4_discard_preallocations(inode);
214 return ret;
218 * Called at the last iput() if i_nlink is zero.
220 void ext4_delete_inode(struct inode *inode)
222 handle_t *handle;
223 int err;
225 if (ext4_should_order_data(inode))
226 ext4_begin_ordered_truncate(inode, 0);
227 truncate_inode_pages(&inode->i_data, 0);
229 if (is_bad_inode(inode))
230 goto no_delete;
232 handle = ext4_journal_start(inode, blocks_for_truncate(inode)+3);
233 if (IS_ERR(handle)) {
234 ext4_std_error(inode->i_sb, PTR_ERR(handle));
236 * If we're going to skip the normal cleanup, we still need to
237 * make sure that the in-core orphan linked list is properly
238 * cleaned up.
240 ext4_orphan_del(NULL, inode);
241 goto no_delete;
244 if (IS_SYNC(inode))
245 ext4_handle_sync(handle);
246 inode->i_size = 0;
247 err = ext4_mark_inode_dirty(handle, inode);
248 if (err) {
249 ext4_warning(inode->i_sb, __func__,
250 "couldn't mark inode dirty (err %d)", err);
251 goto stop_handle;
253 if (inode->i_blocks)
254 ext4_truncate(inode);
257 * ext4_ext_truncate() doesn't reserve any slop when it
258 * restarts journal transactions; therefore there may not be
259 * enough credits left in the handle to remove the inode from
260 * the orphan list and set the dtime field.
262 if (!ext4_handle_has_enough_credits(handle, 3)) {
263 err = ext4_journal_extend(handle, 3);
264 if (err > 0)
265 err = ext4_journal_restart(handle, 3);
266 if (err != 0) {
267 ext4_warning(inode->i_sb, __func__,
268 "couldn't extend journal (err %d)", err);
269 stop_handle:
270 ext4_journal_stop(handle);
271 goto no_delete;
276 * Kill off the orphan record which ext4_truncate created.
277 * AKPM: I think this can be inside the above `if'.
278 * Note that ext4_orphan_del() has to be able to cope with the
279 * deletion of a non-existent orphan - this is because we don't
280 * know if ext4_truncate() actually created an orphan record.
281 * (Well, we could do this if we need to, but heck - it works)
283 ext4_orphan_del(handle, inode);
284 EXT4_I(inode)->i_dtime = get_seconds();
287 * One subtle ordering requirement: if anything has gone wrong
288 * (transaction abort, IO errors, whatever), then we can still
289 * do these next steps (the fs will already have been marked as
290 * having errors), but we can't free the inode if the mark_dirty
291 * fails.
293 if (ext4_mark_inode_dirty(handle, inode))
294 /* If that failed, just do the required in-core inode clear. */
295 clear_inode(inode);
296 else
297 ext4_free_inode(handle, inode);
298 ext4_journal_stop(handle);
299 return;
300 no_delete:
301 clear_inode(inode); /* We must guarantee clearing of inode... */
304 typedef struct {
305 __le32 *p;
306 __le32 key;
307 struct buffer_head *bh;
308 } Indirect;
310 static inline void add_chain(Indirect *p, struct buffer_head *bh, __le32 *v)
312 p->key = *(p->p = v);
313 p->bh = bh;
317 * ext4_block_to_path - parse the block number into array of offsets
318 * @inode: inode in question (we are only interested in its superblock)
319 * @i_block: block number to be parsed
320 * @offsets: array to store the offsets in
321 * @boundary: set this non-zero if the referred-to block is likely to be
322 * followed (on disk) by an indirect block.
324 * To store the locations of file's data ext4 uses a data structure common
325 * for UNIX filesystems - tree of pointers anchored in the inode, with
326 * data blocks at leaves and indirect blocks in intermediate nodes.
327 * This function translates the block number into path in that tree -
328 * return value is the path length and @offsets[n] is the offset of
329 * pointer to (n+1)th node in the nth one. If @block is out of range
330 * (negative or too large) warning is printed and zero returned.
332 * Note: function doesn't find node addresses, so no IO is needed. All
333 * we need to know is the capacity of indirect blocks (taken from the
334 * inode->i_sb).
338 * Portability note: the last comparison (check that we fit into triple
339 * indirect block) is spelled differently, because otherwise on an
340 * architecture with 32-bit longs and 8Kb pages we might get into trouble
341 * if our filesystem had 8Kb blocks. We might use long long, but that would
342 * kill us on x86. Oh, well, at least the sign propagation does not matter -
343 * i_block would have to be negative in the very beginning, so we would not
344 * get there at all.
347 static int ext4_block_to_path(struct inode *inode,
348 ext4_lblk_t i_block,
349 ext4_lblk_t offsets[4], int *boundary)
351 int ptrs = EXT4_ADDR_PER_BLOCK(inode->i_sb);
352 int ptrs_bits = EXT4_ADDR_PER_BLOCK_BITS(inode->i_sb);
353 const long direct_blocks = EXT4_NDIR_BLOCKS,
354 indirect_blocks = ptrs,
355 double_blocks = (1 << (ptrs_bits * 2));
356 int n = 0;
357 int final = 0;
359 if (i_block < 0) {
360 ext4_warning(inode->i_sb, "ext4_block_to_path", "block < 0");
361 } else if (i_block < direct_blocks) {
362 offsets[n++] = i_block;
363 final = direct_blocks;
364 } else if ((i_block -= direct_blocks) < indirect_blocks) {
365 offsets[n++] = EXT4_IND_BLOCK;
366 offsets[n++] = i_block;
367 final = ptrs;
368 } else if ((i_block -= indirect_blocks) < double_blocks) {
369 offsets[n++] = EXT4_DIND_BLOCK;
370 offsets[n++] = i_block >> ptrs_bits;
371 offsets[n++] = i_block & (ptrs - 1);
372 final = ptrs;
373 } else if (((i_block -= double_blocks) >> (ptrs_bits * 2)) < ptrs) {
374 offsets[n++] = EXT4_TIND_BLOCK;
375 offsets[n++] = i_block >> (ptrs_bits * 2);
376 offsets[n++] = (i_block >> ptrs_bits) & (ptrs - 1);
377 offsets[n++] = i_block & (ptrs - 1);
378 final = ptrs;
379 } else {
380 ext4_warning(inode->i_sb, "ext4_block_to_path",
381 "block %lu > max in inode %lu",
382 i_block + direct_blocks +
383 indirect_blocks + double_blocks, inode->i_ino);
385 if (boundary)
386 *boundary = final - 1 - (i_block & (ptrs - 1));
387 return n;
390 static int __ext4_check_blockref(const char *function, struct inode *inode,
391 __le32 *p, unsigned int max)
393 __le32 *bref = p;
394 unsigned int blk;
396 while (bref < p+max) {
397 blk = le32_to_cpu(*bref++);
398 if (blk &&
399 unlikely(!ext4_data_block_valid(EXT4_SB(inode->i_sb),
400 blk, 1))) {
401 ext4_error(inode->i_sb, function,
402 "invalid block reference %u "
403 "in inode #%lu", blk, inode->i_ino);
404 return -EIO;
407 return 0;
411 #define ext4_check_indirect_blockref(inode, bh) \
412 __ext4_check_blockref(__func__, inode, (__le32 *)(bh)->b_data, \
413 EXT4_ADDR_PER_BLOCK((inode)->i_sb))
415 #define ext4_check_inode_blockref(inode) \
416 __ext4_check_blockref(__func__, inode, EXT4_I(inode)->i_data, \
417 EXT4_NDIR_BLOCKS)
420 * ext4_get_branch - read the chain of indirect blocks leading to data
421 * @inode: inode in question
422 * @depth: depth of the chain (1 - direct pointer, etc.)
423 * @offsets: offsets of pointers in inode/indirect blocks
424 * @chain: place to store the result
425 * @err: here we store the error value
427 * Function fills the array of triples <key, p, bh> and returns %NULL
428 * if everything went OK or the pointer to the last filled triple
429 * (incomplete one) otherwise. Upon the return chain[i].key contains
430 * the number of (i+1)-th block in the chain (as it is stored in memory,
431 * i.e. little-endian 32-bit), chain[i].p contains the address of that
432 * number (it points into struct inode for i==0 and into the bh->b_data
433 * for i>0) and chain[i].bh points to the buffer_head of i-th indirect
434 * block for i>0 and NULL for i==0. In other words, it holds the block
435 * numbers of the chain, addresses they were taken from (and where we can
436 * verify that chain did not change) and buffer_heads hosting these
437 * numbers.
439 * Function stops when it stumbles upon zero pointer (absent block)
440 * (pointer to last triple returned, *@err == 0)
441 * or when it gets an IO error reading an indirect block
442 * (ditto, *@err == -EIO)
443 * or when it reads all @depth-1 indirect blocks successfully and finds
444 * the whole chain, all way to the data (returns %NULL, *err == 0).
446 * Need to be called with
447 * down_read(&EXT4_I(inode)->i_data_sem)
449 static Indirect *ext4_get_branch(struct inode *inode, int depth,
450 ext4_lblk_t *offsets,
451 Indirect chain[4], int *err)
453 struct super_block *sb = inode->i_sb;
454 Indirect *p = chain;
455 struct buffer_head *bh;
457 *err = 0;
458 /* i_data is not going away, no lock needed */
459 add_chain(chain, NULL, EXT4_I(inode)->i_data + *offsets);
460 if (!p->key)
461 goto no_block;
462 while (--depth) {
463 bh = sb_getblk(sb, le32_to_cpu(p->key));
464 if (unlikely(!bh))
465 goto failure;
467 if (!bh_uptodate_or_lock(bh)) {
468 if (bh_submit_read(bh) < 0) {
469 put_bh(bh);
470 goto failure;
472 /* validate block references */
473 if (ext4_check_indirect_blockref(inode, bh)) {
474 put_bh(bh);
475 goto failure;
479 add_chain(++p, bh, (__le32 *)bh->b_data + *++offsets);
480 /* Reader: end */
481 if (!p->key)
482 goto no_block;
484 return NULL;
486 failure:
487 *err = -EIO;
488 no_block:
489 return p;
493 * ext4_find_near - find a place for allocation with sufficient locality
494 * @inode: owner
495 * @ind: descriptor of indirect block.
497 * This function returns the preferred place for block allocation.
498 * It is used when heuristic for sequential allocation fails.
499 * Rules are:
500 * + if there is a block to the left of our position - allocate near it.
501 * + if pointer will live in indirect block - allocate near that block.
502 * + if pointer will live in inode - allocate in the same
503 * cylinder group.
505 * In the latter case we colour the starting block by the callers PID to
506 * prevent it from clashing with concurrent allocations for a different inode
507 * in the same block group. The PID is used here so that functionally related
508 * files will be close-by on-disk.
510 * Caller must make sure that @ind is valid and will stay that way.
512 static ext4_fsblk_t ext4_find_near(struct inode *inode, Indirect *ind)
514 struct ext4_inode_info *ei = EXT4_I(inode);
515 __le32 *start = ind->bh ? (__le32 *) ind->bh->b_data : ei->i_data;
516 __le32 *p;
517 ext4_fsblk_t bg_start;
518 ext4_fsblk_t last_block;
519 ext4_grpblk_t colour;
520 ext4_group_t block_group;
521 int flex_size = ext4_flex_bg_size(EXT4_SB(inode->i_sb));
523 /* Try to find previous block */
524 for (p = ind->p - 1; p >= start; p--) {
525 if (*p)
526 return le32_to_cpu(*p);
529 /* No such thing, so let's try location of indirect block */
530 if (ind->bh)
531 return ind->bh->b_blocknr;
534 * It is going to be referred to from the inode itself? OK, just put it
535 * into the same cylinder group then.
537 block_group = ei->i_block_group;
538 if (flex_size >= EXT4_FLEX_SIZE_DIR_ALLOC_SCHEME) {
539 block_group &= ~(flex_size-1);
540 if (S_ISREG(inode->i_mode))
541 block_group++;
543 bg_start = ext4_group_first_block_no(inode->i_sb, block_group);
544 last_block = ext4_blocks_count(EXT4_SB(inode->i_sb)->s_es) - 1;
547 * If we are doing delayed allocation, we don't need take
548 * colour into account.
550 if (test_opt(inode->i_sb, DELALLOC))
551 return bg_start;
553 if (bg_start + EXT4_BLOCKS_PER_GROUP(inode->i_sb) <= last_block)
554 colour = (current->pid % 16) *
555 (EXT4_BLOCKS_PER_GROUP(inode->i_sb) / 16);
556 else
557 colour = (current->pid % 16) * ((last_block - bg_start) / 16);
558 return bg_start + colour;
562 * ext4_find_goal - find a preferred place for allocation.
563 * @inode: owner
564 * @block: block we want
565 * @partial: pointer to the last triple within a chain
567 * Normally this function find the preferred place for block allocation,
568 * returns it.
569 * Because this is only used for non-extent files, we limit the block nr
570 * to 32 bits.
572 static ext4_fsblk_t ext4_find_goal(struct inode *inode, ext4_lblk_t block,
573 Indirect *partial)
575 ext4_fsblk_t goal;
578 * XXX need to get goal block from mballoc's data structures
581 goal = ext4_find_near(inode, partial);
582 goal = goal & EXT4_MAX_BLOCK_FILE_PHYS;
583 return goal;
587 * ext4_blks_to_allocate: Look up the block map and count the number
588 * of direct blocks need to be allocated for the given branch.
590 * @branch: chain of indirect blocks
591 * @k: number of blocks need for indirect blocks
592 * @blks: number of data blocks to be mapped.
593 * @blocks_to_boundary: the offset in the indirect block
595 * return the total number of blocks to be allocate, including the
596 * direct and indirect blocks.
598 static int ext4_blks_to_allocate(Indirect *branch, int k, unsigned int blks,
599 int blocks_to_boundary)
601 unsigned int count = 0;
604 * Simple case, [t,d]Indirect block(s) has not allocated yet
605 * then it's clear blocks on that path have not allocated
607 if (k > 0) {
608 /* right now we don't handle cross boundary allocation */
609 if (blks < blocks_to_boundary + 1)
610 count += blks;
611 else
612 count += blocks_to_boundary + 1;
613 return count;
616 count++;
617 while (count < blks && count <= blocks_to_boundary &&
618 le32_to_cpu(*(branch[0].p + count)) == 0) {
619 count++;
621 return count;
625 * ext4_alloc_blocks: multiple allocate blocks needed for a branch
626 * @indirect_blks: the number of blocks need to allocate for indirect
627 * blocks
629 * @new_blocks: on return it will store the new block numbers for
630 * the indirect blocks(if needed) and the first direct block,
631 * @blks: on return it will store the total number of allocated
632 * direct blocks
634 static int ext4_alloc_blocks(handle_t *handle, struct inode *inode,
635 ext4_lblk_t iblock, ext4_fsblk_t goal,
636 int indirect_blks, int blks,
637 ext4_fsblk_t new_blocks[4], int *err)
639 struct ext4_allocation_request ar;
640 int target, i;
641 unsigned long count = 0, blk_allocated = 0;
642 int index = 0;
643 ext4_fsblk_t current_block = 0;
644 int ret = 0;
647 * Here we try to allocate the requested multiple blocks at once,
648 * on a best-effort basis.
649 * To build a branch, we should allocate blocks for
650 * the indirect blocks(if not allocated yet), and at least
651 * the first direct block of this branch. That's the
652 * minimum number of blocks need to allocate(required)
654 /* first we try to allocate the indirect blocks */
655 target = indirect_blks;
656 while (target > 0) {
657 count = target;
658 /* allocating blocks for indirect blocks and direct blocks */
659 current_block = ext4_new_meta_blocks(handle, inode,
660 goal, &count, err);
661 if (*err)
662 goto failed_out;
664 BUG_ON(current_block + count > EXT4_MAX_BLOCK_FILE_PHYS);
666 target -= count;
667 /* allocate blocks for indirect blocks */
668 while (index < indirect_blks && count) {
669 new_blocks[index++] = current_block++;
670 count--;
672 if (count > 0) {
674 * save the new block number
675 * for the first direct block
677 new_blocks[index] = current_block;
678 printk(KERN_INFO "%s returned more blocks than "
679 "requested\n", __func__);
680 WARN_ON(1);
681 break;
685 target = blks - count ;
686 blk_allocated = count;
687 if (!target)
688 goto allocated;
689 /* Now allocate data blocks */
690 memset(&ar, 0, sizeof(ar));
691 ar.inode = inode;
692 ar.goal = goal;
693 ar.len = target;
694 ar.logical = iblock;
695 if (S_ISREG(inode->i_mode))
696 /* enable in-core preallocation only for regular files */
697 ar.flags = EXT4_MB_HINT_DATA;
699 current_block = ext4_mb_new_blocks(handle, &ar, err);
700 BUG_ON(current_block + ar.len > EXT4_MAX_BLOCK_FILE_PHYS);
702 if (*err && (target == blks)) {
704 * if the allocation failed and we didn't allocate
705 * any blocks before
707 goto failed_out;
709 if (!*err) {
710 if (target == blks) {
712 * save the new block number
713 * for the first direct block
715 new_blocks[index] = current_block;
717 blk_allocated += ar.len;
719 allocated:
720 /* total number of blocks allocated for direct blocks */
721 ret = blk_allocated;
722 *err = 0;
723 return ret;
724 failed_out:
725 for (i = 0; i < index; i++)
726 ext4_free_blocks(handle, inode, new_blocks[i], 1, 0);
727 return ret;
731 * ext4_alloc_branch - allocate and set up a chain of blocks.
732 * @inode: owner
733 * @indirect_blks: number of allocated indirect blocks
734 * @blks: number of allocated direct blocks
735 * @offsets: offsets (in the blocks) to store the pointers to next.
736 * @branch: place to store the chain in.
738 * This function allocates blocks, zeroes out all but the last one,
739 * links them into chain and (if we are synchronous) writes them to disk.
740 * In other words, it prepares a branch that can be spliced onto the
741 * inode. It stores the information about that chain in the branch[], in
742 * the same format as ext4_get_branch() would do. We are calling it after
743 * we had read the existing part of chain and partial points to the last
744 * triple of that (one with zero ->key). Upon the exit we have the same
745 * picture as after the successful ext4_get_block(), except that in one
746 * place chain is disconnected - *branch->p is still zero (we did not
747 * set the last link), but branch->key contains the number that should
748 * be placed into *branch->p to fill that gap.
750 * If allocation fails we free all blocks we've allocated (and forget
751 * their buffer_heads) and return the error value the from failed
752 * ext4_alloc_block() (normally -ENOSPC). Otherwise we set the chain
753 * as described above and return 0.
755 static int ext4_alloc_branch(handle_t *handle, struct inode *inode,
756 ext4_lblk_t iblock, int indirect_blks,
757 int *blks, ext4_fsblk_t goal,
758 ext4_lblk_t *offsets, Indirect *branch)
760 int blocksize = inode->i_sb->s_blocksize;
761 int i, n = 0;
762 int err = 0;
763 struct buffer_head *bh;
764 int num;
765 ext4_fsblk_t new_blocks[4];
766 ext4_fsblk_t current_block;
768 num = ext4_alloc_blocks(handle, inode, iblock, goal, indirect_blks,
769 *blks, new_blocks, &err);
770 if (err)
771 return err;
773 branch[0].key = cpu_to_le32(new_blocks[0]);
775 * metadata blocks and data blocks are allocated.
777 for (n = 1; n <= indirect_blks; n++) {
779 * Get buffer_head for parent block, zero it out
780 * and set the pointer to new one, then send
781 * parent to disk.
783 bh = sb_getblk(inode->i_sb, new_blocks[n-1]);
784 branch[n].bh = bh;
785 lock_buffer(bh);
786 BUFFER_TRACE(bh, "call get_create_access");
787 err = ext4_journal_get_create_access(handle, bh);
788 if (err) {
789 unlock_buffer(bh);
790 brelse(bh);
791 goto failed;
794 memset(bh->b_data, 0, blocksize);
795 branch[n].p = (__le32 *) bh->b_data + offsets[n];
796 branch[n].key = cpu_to_le32(new_blocks[n]);
797 *branch[n].p = branch[n].key;
798 if (n == indirect_blks) {
799 current_block = new_blocks[n];
801 * End of chain, update the last new metablock of
802 * the chain to point to the new allocated
803 * data blocks numbers
805 for (i = 1; i < num; i++)
806 *(branch[n].p + i) = cpu_to_le32(++current_block);
808 BUFFER_TRACE(bh, "marking uptodate");
809 set_buffer_uptodate(bh);
810 unlock_buffer(bh);
812 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
813 err = ext4_handle_dirty_metadata(handle, inode, bh);
814 if (err)
815 goto failed;
817 *blks = num;
818 return err;
819 failed:
820 /* Allocation failed, free what we already allocated */
821 for (i = 1; i <= n ; i++) {
822 BUFFER_TRACE(branch[i].bh, "call jbd2_journal_forget");
823 ext4_journal_forget(handle, branch[i].bh);
825 for (i = 0; i < indirect_blks; i++)
826 ext4_free_blocks(handle, inode, new_blocks[i], 1, 0);
828 ext4_free_blocks(handle, inode, new_blocks[i], num, 0);
830 return err;
834 * ext4_splice_branch - splice the allocated branch onto inode.
835 * @inode: owner
836 * @block: (logical) number of block we are adding
837 * @chain: chain of indirect blocks (with a missing link - see
838 * ext4_alloc_branch)
839 * @where: location of missing link
840 * @num: number of indirect blocks we are adding
841 * @blks: number of direct blocks we are adding
843 * This function fills the missing link and does all housekeeping needed in
844 * inode (->i_blocks, etc.). In case of success we end up with the full
845 * chain to new block and return 0.
847 static int ext4_splice_branch(handle_t *handle, struct inode *inode,
848 ext4_lblk_t block, Indirect *where, int num,
849 int blks)
851 int i;
852 int err = 0;
853 ext4_fsblk_t current_block;
856 * If we're splicing into a [td]indirect block (as opposed to the
857 * inode) then we need to get write access to the [td]indirect block
858 * before the splice.
860 if (where->bh) {
861 BUFFER_TRACE(where->bh, "get_write_access");
862 err = ext4_journal_get_write_access(handle, where->bh);
863 if (err)
864 goto err_out;
866 /* That's it */
868 *where->p = where->key;
871 * Update the host buffer_head or inode to point to more just allocated
872 * direct blocks blocks
874 if (num == 0 && blks > 1) {
875 current_block = le32_to_cpu(where->key) + 1;
876 for (i = 1; i < blks; i++)
877 *(where->p + i) = cpu_to_le32(current_block++);
880 /* We are done with atomic stuff, now do the rest of housekeeping */
881 /* had we spliced it onto indirect block? */
882 if (where->bh) {
884 * If we spliced it onto an indirect block, we haven't
885 * altered the inode. Note however that if it is being spliced
886 * onto an indirect block at the very end of the file (the
887 * file is growing) then we *will* alter the inode to reflect
888 * the new i_size. But that is not done here - it is done in
889 * generic_commit_write->__mark_inode_dirty->ext4_dirty_inode.
891 jbd_debug(5, "splicing indirect only\n");
892 BUFFER_TRACE(where->bh, "call ext4_handle_dirty_metadata");
893 err = ext4_handle_dirty_metadata(handle, inode, where->bh);
894 if (err)
895 goto err_out;
896 } else {
898 * OK, we spliced it into the inode itself on a direct block.
900 ext4_mark_inode_dirty(handle, inode);
901 jbd_debug(5, "splicing direct\n");
903 return err;
905 err_out:
906 for (i = 1; i <= num; i++) {
907 BUFFER_TRACE(where[i].bh, "call jbd2_journal_forget");
908 ext4_journal_forget(handle, where[i].bh);
909 ext4_free_blocks(handle, inode,
910 le32_to_cpu(where[i-1].key), 1, 0);
912 ext4_free_blocks(handle, inode, le32_to_cpu(where[num].key), blks, 0);
914 return err;
918 * The ext4_ind_get_blocks() function handles non-extents inodes
919 * (i.e., using the traditional indirect/double-indirect i_blocks
920 * scheme) for ext4_get_blocks().
922 * Allocation strategy is simple: if we have to allocate something, we will
923 * have to go the whole way to leaf. So let's do it before attaching anything
924 * to tree, set linkage between the newborn blocks, write them if sync is
925 * required, recheck the path, free and repeat if check fails, otherwise
926 * set the last missing link (that will protect us from any truncate-generated
927 * removals - all blocks on the path are immune now) and possibly force the
928 * write on the parent block.
929 * That has a nice additional property: no special recovery from the failed
930 * allocations is needed - we simply release blocks and do not touch anything
931 * reachable from inode.
933 * `handle' can be NULL if create == 0.
935 * return > 0, # of blocks mapped or allocated.
936 * return = 0, if plain lookup failed.
937 * return < 0, error case.
939 * The ext4_ind_get_blocks() function should be called with
940 * down_write(&EXT4_I(inode)->i_data_sem) if allocating filesystem
941 * blocks (i.e., flags has EXT4_GET_BLOCKS_CREATE set) or
942 * down_read(&EXT4_I(inode)->i_data_sem) if not allocating file system
943 * blocks.
945 static int ext4_ind_get_blocks(handle_t *handle, struct inode *inode,
946 ext4_lblk_t iblock, unsigned int maxblocks,
947 struct buffer_head *bh_result,
948 int flags)
950 int err = -EIO;
951 ext4_lblk_t offsets[4];
952 Indirect chain[4];
953 Indirect *partial;
954 ext4_fsblk_t goal;
955 int indirect_blks;
956 int blocks_to_boundary = 0;
957 int depth;
958 int count = 0;
959 ext4_fsblk_t first_block = 0;
961 J_ASSERT(!(EXT4_I(inode)->i_flags & EXT4_EXTENTS_FL));
962 J_ASSERT(handle != NULL || (flags & EXT4_GET_BLOCKS_CREATE) == 0);
963 depth = ext4_block_to_path(inode, iblock, offsets,
964 &blocks_to_boundary);
966 if (depth == 0)
967 goto out;
969 partial = ext4_get_branch(inode, depth, offsets, chain, &err);
971 /* Simplest case - block found, no allocation needed */
972 if (!partial) {
973 first_block = le32_to_cpu(chain[depth - 1].key);
974 clear_buffer_new(bh_result);
975 count++;
976 /*map more blocks*/
977 while (count < maxblocks && count <= blocks_to_boundary) {
978 ext4_fsblk_t blk;
980 blk = le32_to_cpu(*(chain[depth-1].p + count));
982 if (blk == first_block + count)
983 count++;
984 else
985 break;
987 goto got_it;
990 /* Next simple case - plain lookup or failed read of indirect block */
991 if ((flags & EXT4_GET_BLOCKS_CREATE) == 0 || err == -EIO)
992 goto cleanup;
995 * Okay, we need to do block allocation.
997 goal = ext4_find_goal(inode, iblock, partial);
999 /* the number of blocks need to allocate for [d,t]indirect blocks */
1000 indirect_blks = (chain + depth) - partial - 1;
1003 * Next look up the indirect map to count the totoal number of
1004 * direct blocks to allocate for this branch.
1006 count = ext4_blks_to_allocate(partial, indirect_blks,
1007 maxblocks, blocks_to_boundary);
1009 * Block out ext4_truncate while we alter the tree
1011 err = ext4_alloc_branch(handle, inode, iblock, indirect_blks,
1012 &count, goal,
1013 offsets + (partial - chain), partial);
1016 * The ext4_splice_branch call will free and forget any buffers
1017 * on the new chain if there is a failure, but that risks using
1018 * up transaction credits, especially for bitmaps where the
1019 * credits cannot be returned. Can we handle this somehow? We
1020 * may need to return -EAGAIN upwards in the worst case. --sct
1022 if (!err)
1023 err = ext4_splice_branch(handle, inode, iblock,
1024 partial, indirect_blks, count);
1025 if (err)
1026 goto cleanup;
1028 set_buffer_new(bh_result);
1030 ext4_update_inode_fsync_trans(handle, inode, 1);
1031 got_it:
1032 map_bh(bh_result, inode->i_sb, le32_to_cpu(chain[depth-1].key));
1033 if (count > blocks_to_boundary)
1034 set_buffer_boundary(bh_result);
1035 err = count;
1036 /* Clean up and exit */
1037 partial = chain + depth - 1; /* the whole chain */
1038 cleanup:
1039 while (partial > chain) {
1040 BUFFER_TRACE(partial->bh, "call brelse");
1041 brelse(partial->bh);
1042 partial--;
1044 BUFFER_TRACE(bh_result, "returned");
1045 out:
1046 return err;
1049 qsize_t ext4_get_reserved_space(struct inode *inode)
1051 unsigned long long total;
1053 spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
1054 total = EXT4_I(inode)->i_reserved_data_blocks +
1055 EXT4_I(inode)->i_reserved_meta_blocks;
1056 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
1058 return (total << inode->i_blkbits);
1061 * Calculate the number of metadata blocks need to reserve
1062 * to allocate @blocks for non extent file based file
1064 static int ext4_indirect_calc_metadata_amount(struct inode *inode, int blocks)
1066 int icap = EXT4_ADDR_PER_BLOCK(inode->i_sb);
1067 int ind_blks, dind_blks, tind_blks;
1069 /* number of new indirect blocks needed */
1070 ind_blks = (blocks + icap - 1) / icap;
1072 dind_blks = (ind_blks + icap - 1) / icap;
1074 tind_blks = 1;
1076 return ind_blks + dind_blks + tind_blks;
1080 * Calculate the number of metadata blocks need to reserve
1081 * to allocate given number of blocks
1083 static int ext4_calc_metadata_amount(struct inode *inode, int blocks)
1085 if (!blocks)
1086 return 0;
1088 if (EXT4_I(inode)->i_flags & EXT4_EXTENTS_FL)
1089 return ext4_ext_calc_metadata_amount(inode, blocks);
1091 return ext4_indirect_calc_metadata_amount(inode, blocks);
1094 static void ext4_da_update_reserve_space(struct inode *inode, int used)
1096 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1097 int total, mdb, mdb_free;
1099 spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
1100 /* recalculate the number of metablocks still need to be reserved */
1101 total = EXT4_I(inode)->i_reserved_data_blocks - used;
1102 mdb = ext4_calc_metadata_amount(inode, total);
1104 /* figure out how many metablocks to release */
1105 BUG_ON(mdb > EXT4_I(inode)->i_reserved_meta_blocks);
1106 mdb_free = EXT4_I(inode)->i_reserved_meta_blocks - mdb;
1108 if (mdb_free) {
1109 /* Account for allocated meta_blocks */
1110 mdb_free -= EXT4_I(inode)->i_allocated_meta_blocks;
1112 /* update fs dirty blocks counter */
1113 percpu_counter_sub(&sbi->s_dirtyblocks_counter, mdb_free);
1114 EXT4_I(inode)->i_allocated_meta_blocks = 0;
1115 EXT4_I(inode)->i_reserved_meta_blocks = mdb;
1118 /* update per-inode reservations */
1119 BUG_ON(used > EXT4_I(inode)->i_reserved_data_blocks);
1120 EXT4_I(inode)->i_reserved_data_blocks -= used;
1121 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
1124 * free those over-booking quota for metadata blocks
1126 if (mdb_free)
1127 vfs_dq_release_reservation_block(inode, mdb_free);
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 (!total && (atomic_read(&inode->i_writecount) == 0))
1135 ext4_discard_preallocations(inode);
1138 static int check_block_validity(struct inode *inode, const char *msg,
1139 sector_t logical, sector_t phys, int len)
1141 if (!ext4_data_block_valid(EXT4_SB(inode->i_sb), phys, len)) {
1142 ext4_error(inode->i_sb, msg,
1143 "inode #%lu logical block %llu mapped to %llu "
1144 "(size %d)", inode->i_ino,
1145 (unsigned long long) logical,
1146 (unsigned long long) phys, len);
1147 return -EIO;
1149 return 0;
1153 * Return the number of contiguous dirty pages in a given inode
1154 * starting at page frame idx.
1156 static pgoff_t ext4_num_dirty_pages(struct inode *inode, pgoff_t idx,
1157 unsigned int max_pages)
1159 struct address_space *mapping = inode->i_mapping;
1160 pgoff_t index;
1161 struct pagevec pvec;
1162 pgoff_t num = 0;
1163 int i, nr_pages, done = 0;
1165 if (max_pages == 0)
1166 return 0;
1167 pagevec_init(&pvec, 0);
1168 while (!done) {
1169 index = idx;
1170 nr_pages = pagevec_lookup_tag(&pvec, mapping, &index,
1171 PAGECACHE_TAG_DIRTY,
1172 (pgoff_t)PAGEVEC_SIZE);
1173 if (nr_pages == 0)
1174 break;
1175 for (i = 0; i < nr_pages; i++) {
1176 struct page *page = pvec.pages[i];
1177 struct buffer_head *bh, *head;
1179 lock_page(page);
1180 if (unlikely(page->mapping != mapping) ||
1181 !PageDirty(page) ||
1182 PageWriteback(page) ||
1183 page->index != idx) {
1184 done = 1;
1185 unlock_page(page);
1186 break;
1188 if (page_has_buffers(page)) {
1189 bh = head = page_buffers(page);
1190 do {
1191 if (!buffer_delay(bh) &&
1192 !buffer_unwritten(bh))
1193 done = 1;
1194 bh = bh->b_this_page;
1195 } while (!done && (bh != head));
1197 unlock_page(page);
1198 if (done)
1199 break;
1200 idx++;
1201 num++;
1202 if (num >= max_pages)
1203 break;
1205 pagevec_release(&pvec);
1207 return num;
1211 * The ext4_get_blocks() function tries to look up the requested blocks,
1212 * and returns if the blocks are already mapped.
1214 * Otherwise it takes the write lock of the i_data_sem and allocate blocks
1215 * and store the allocated blocks in the result buffer head and mark it
1216 * mapped.
1218 * If file type is extents based, it will call ext4_ext_get_blocks(),
1219 * Otherwise, call with ext4_ind_get_blocks() to handle indirect mapping
1220 * based files
1222 * On success, it returns the number of blocks being mapped or allocate.
1223 * if create==0 and the blocks are pre-allocated and uninitialized block,
1224 * the result buffer head is unmapped. If the create ==1, it will make sure
1225 * the buffer head is mapped.
1227 * It returns 0 if plain look up failed (blocks have not been allocated), in
1228 * that casem, buffer head is unmapped
1230 * It returns the error in case of allocation failure.
1232 int ext4_get_blocks(handle_t *handle, struct inode *inode, sector_t block,
1233 unsigned int max_blocks, struct buffer_head *bh,
1234 int flags)
1236 int retval;
1238 clear_buffer_mapped(bh);
1239 clear_buffer_unwritten(bh);
1241 ext_debug("ext4_get_blocks(): inode %lu, flag %d, max_blocks %u,"
1242 "logical block %lu\n", inode->i_ino, flags, max_blocks,
1243 (unsigned long)block);
1245 * Try to see if we can get the block without requesting a new
1246 * file system block.
1248 down_read((&EXT4_I(inode)->i_data_sem));
1249 if (EXT4_I(inode)->i_flags & EXT4_EXTENTS_FL) {
1250 retval = ext4_ext_get_blocks(handle, inode, block, max_blocks,
1251 bh, 0);
1252 } else {
1253 retval = ext4_ind_get_blocks(handle, inode, block, max_blocks,
1254 bh, 0);
1256 up_read((&EXT4_I(inode)->i_data_sem));
1258 if (retval > 0 && buffer_mapped(bh)) {
1259 int ret = check_block_validity(inode, "file system corruption",
1260 block, bh->b_blocknr, retval);
1261 if (ret != 0)
1262 return ret;
1265 /* If it is only a block(s) look up */
1266 if ((flags & EXT4_GET_BLOCKS_CREATE) == 0)
1267 return retval;
1270 * Returns if the blocks have already allocated
1272 * Note that if blocks have been preallocated
1273 * ext4_ext_get_block() returns th create = 0
1274 * with buffer head unmapped.
1276 if (retval > 0 && buffer_mapped(bh))
1277 return retval;
1280 * When we call get_blocks without the create flag, the
1281 * BH_Unwritten flag could have gotten set if the blocks
1282 * requested were part of a uninitialized extent. We need to
1283 * clear this flag now that we are committed to convert all or
1284 * part of the uninitialized extent to be an initialized
1285 * extent. This is because we need to avoid the combination
1286 * of BH_Unwritten and BH_Mapped flags being simultaneously
1287 * set on the buffer_head.
1289 clear_buffer_unwritten(bh);
1292 * New blocks allocate and/or writing to uninitialized extent
1293 * will possibly result in updating i_data, so we take
1294 * the write lock of i_data_sem, and call get_blocks()
1295 * with create == 1 flag.
1297 down_write((&EXT4_I(inode)->i_data_sem));
1300 * if the caller is from delayed allocation writeout path
1301 * we have already reserved fs blocks for allocation
1302 * let the underlying get_block() function know to
1303 * avoid double accounting
1305 if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
1306 EXT4_I(inode)->i_delalloc_reserved_flag = 1;
1308 * We need to check for EXT4 here because migrate
1309 * could have changed the inode type in between
1311 if (EXT4_I(inode)->i_flags & EXT4_EXTENTS_FL) {
1312 retval = ext4_ext_get_blocks(handle, inode, block, max_blocks,
1313 bh, flags);
1314 } else {
1315 retval = ext4_ind_get_blocks(handle, inode, block,
1316 max_blocks, bh, flags);
1318 if (retval > 0 && buffer_new(bh)) {
1320 * We allocated new blocks which will result in
1321 * i_data's format changing. Force the migrate
1322 * to fail by clearing migrate flags
1324 EXT4_I(inode)->i_state &= ~EXT4_STATE_EXT_MIGRATE;
1328 if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
1329 EXT4_I(inode)->i_delalloc_reserved_flag = 0;
1332 * Update reserved blocks/metadata blocks after successful
1333 * block allocation which had been deferred till now.
1335 if ((retval > 0) && (flags & EXT4_GET_BLOCKS_UPDATE_RESERVE_SPACE))
1336 ext4_da_update_reserve_space(inode, retval);
1338 up_write((&EXT4_I(inode)->i_data_sem));
1339 if (retval > 0 && buffer_mapped(bh)) {
1340 int ret = check_block_validity(inode, "file system "
1341 "corruption after allocation",
1342 block, bh->b_blocknr, retval);
1343 if (ret != 0)
1344 return ret;
1346 return retval;
1349 /* Maximum number of blocks we map for direct IO at once. */
1350 #define DIO_MAX_BLOCKS 4096
1352 int ext4_get_block(struct inode *inode, sector_t iblock,
1353 struct buffer_head *bh_result, int create)
1355 handle_t *handle = ext4_journal_current_handle();
1356 int ret = 0, started = 0;
1357 unsigned max_blocks = bh_result->b_size >> inode->i_blkbits;
1358 int dio_credits;
1360 if (create && !handle) {
1361 /* Direct IO write... */
1362 if (max_blocks > DIO_MAX_BLOCKS)
1363 max_blocks = DIO_MAX_BLOCKS;
1364 dio_credits = ext4_chunk_trans_blocks(inode, max_blocks);
1365 handle = ext4_journal_start(inode, dio_credits);
1366 if (IS_ERR(handle)) {
1367 ret = PTR_ERR(handle);
1368 goto out;
1370 started = 1;
1373 ret = ext4_get_blocks(handle, inode, iblock, max_blocks, bh_result,
1374 create ? EXT4_GET_BLOCKS_CREATE : 0);
1375 if (ret > 0) {
1376 bh_result->b_size = (ret << inode->i_blkbits);
1377 ret = 0;
1379 if (started)
1380 ext4_journal_stop(handle);
1381 out:
1382 return ret;
1386 * `handle' can be NULL if create is zero
1388 struct buffer_head *ext4_getblk(handle_t *handle, struct inode *inode,
1389 ext4_lblk_t block, int create, int *errp)
1391 struct buffer_head dummy;
1392 int fatal = 0, err;
1393 int flags = 0;
1395 J_ASSERT(handle != NULL || create == 0);
1397 dummy.b_state = 0;
1398 dummy.b_blocknr = -1000;
1399 buffer_trace_init(&dummy.b_history);
1400 if (create)
1401 flags |= EXT4_GET_BLOCKS_CREATE;
1402 err = ext4_get_blocks(handle, inode, block, 1, &dummy, flags);
1404 * ext4_get_blocks() returns number of blocks mapped. 0 in
1405 * case of a HOLE.
1407 if (err > 0) {
1408 if (err > 1)
1409 WARN_ON(1);
1410 err = 0;
1412 *errp = err;
1413 if (!err && buffer_mapped(&dummy)) {
1414 struct buffer_head *bh;
1415 bh = sb_getblk(inode->i_sb, dummy.b_blocknr);
1416 if (!bh) {
1417 *errp = -EIO;
1418 goto err;
1420 if (buffer_new(&dummy)) {
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;
1453 err:
1454 return NULL;
1457 struct buffer_head *ext4_bread(handle_t *handle, struct inode *inode,
1458 ext4_lblk_t block, int create, int *err)
1460 struct buffer_head *bh;
1462 bh = ext4_getblk(handle, inode, block, create, err);
1463 if (!bh)
1464 return bh;
1465 if (buffer_uptodate(bh))
1466 return bh;
1467 ll_rw_block(READ_META, 1, &bh);
1468 wait_on_buffer(bh);
1469 if (buffer_uptodate(bh))
1470 return bh;
1471 put_bh(bh);
1472 *err = -EIO;
1473 return NULL;
1476 static int walk_page_buffers(handle_t *handle,
1477 struct buffer_head *head,
1478 unsigned from,
1479 unsigned to,
1480 int *partial,
1481 int (*fn)(handle_t *handle,
1482 struct buffer_head *bh))
1484 struct buffer_head *bh;
1485 unsigned block_start, block_end;
1486 unsigned blocksize = head->b_size;
1487 int err, ret = 0;
1488 struct buffer_head *next;
1490 for (bh = head, block_start = 0;
1491 ret == 0 && (bh != head || !block_start);
1492 block_start = block_end, bh = next) {
1493 next = bh->b_this_page;
1494 block_end = block_start + blocksize;
1495 if (block_end <= from || block_start >= to) {
1496 if (partial && !buffer_uptodate(bh))
1497 *partial = 1;
1498 continue;
1500 err = (*fn)(handle, bh);
1501 if (!ret)
1502 ret = err;
1504 return ret;
1508 * To preserve ordering, it is essential that the hole instantiation and
1509 * the data write be encapsulated in a single transaction. We cannot
1510 * close off a transaction and start a new one between the ext4_get_block()
1511 * and the commit_write(). So doing the jbd2_journal_start at the start of
1512 * prepare_write() is the right place.
1514 * Also, this function can nest inside ext4_writepage() ->
1515 * block_write_full_page(). In that case, we *know* that ext4_writepage()
1516 * has generated enough buffer credits to do the whole page. So we won't
1517 * block on the journal in that case, which is good, because the caller may
1518 * be PF_MEMALLOC.
1520 * By accident, ext4 can be reentered when a transaction is open via
1521 * quota file writes. If we were to commit the transaction while thus
1522 * reentered, there can be a deadlock - we would be holding a quota
1523 * lock, and the commit would never complete if another thread had a
1524 * transaction open and was blocking on the quota lock - a ranking
1525 * violation.
1527 * So what we do is to rely on the fact that jbd2_journal_stop/journal_start
1528 * will _not_ run commit under these circumstances because handle->h_ref
1529 * is elevated. We'll still have enough credits for the tiny quotafile
1530 * write.
1532 static int do_journal_get_write_access(handle_t *handle,
1533 struct buffer_head *bh)
1535 if (!buffer_mapped(bh) || buffer_freed(bh))
1536 return 0;
1537 return ext4_journal_get_write_access(handle, bh);
1541 * Truncate blocks that were not used by write. We have to truncate the
1542 * pagecache as well so that corresponding buffers get properly unmapped.
1544 static void ext4_truncate_failed_write(struct inode *inode)
1546 truncate_inode_pages(inode->i_mapping, inode->i_size);
1547 ext4_truncate(inode);
1550 static int ext4_write_begin(struct file *file, struct address_space *mapping,
1551 loff_t pos, unsigned len, unsigned flags,
1552 struct page **pagep, void **fsdata)
1554 struct inode *inode = mapping->host;
1555 int ret, needed_blocks;
1556 handle_t *handle;
1557 int retries = 0;
1558 struct page *page;
1559 pgoff_t index;
1560 unsigned from, to;
1562 trace_ext4_write_begin(inode, pos, len, flags);
1564 * Reserve one block more for addition to orphan list in case
1565 * we allocate blocks but write fails for some reason
1567 needed_blocks = ext4_writepage_trans_blocks(inode) + 1;
1568 index = pos >> PAGE_CACHE_SHIFT;
1569 from = pos & (PAGE_CACHE_SIZE - 1);
1570 to = from + len;
1572 retry:
1573 handle = ext4_journal_start(inode, needed_blocks);
1574 if (IS_ERR(handle)) {
1575 ret = PTR_ERR(handle);
1576 goto out;
1579 /* We cannot recurse into the filesystem as the transaction is already
1580 * started */
1581 flags |= AOP_FLAG_NOFS;
1583 page = grab_cache_page_write_begin(mapping, index, flags);
1584 if (!page) {
1585 ext4_journal_stop(handle);
1586 ret = -ENOMEM;
1587 goto out;
1589 *pagep = page;
1591 ret = block_write_begin(file, mapping, pos, len, flags, pagep, fsdata,
1592 ext4_get_block);
1594 if (!ret && ext4_should_journal_data(inode)) {
1595 ret = walk_page_buffers(handle, page_buffers(page),
1596 from, to, NULL, do_journal_get_write_access);
1599 if (ret) {
1600 unlock_page(page);
1601 page_cache_release(page);
1603 * block_write_begin may have instantiated a few blocks
1604 * outside i_size. Trim these off again. Don't need
1605 * i_size_read because we hold i_mutex.
1607 * Add inode to orphan list in case we crash before
1608 * truncate finishes
1610 if (pos + len > inode->i_size && ext4_can_truncate(inode))
1611 ext4_orphan_add(handle, inode);
1613 ext4_journal_stop(handle);
1614 if (pos + len > inode->i_size) {
1615 ext4_truncate_failed_write(inode);
1617 * If truncate failed early the inode might
1618 * still be on the orphan list; we need to
1619 * make sure the inode is removed from the
1620 * orphan list in that case.
1622 if (inode->i_nlink)
1623 ext4_orphan_del(NULL, inode);
1627 if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
1628 goto retry;
1629 out:
1630 return ret;
1633 /* For write_end() in data=journal mode */
1634 static int write_end_fn(handle_t *handle, struct buffer_head *bh)
1636 if (!buffer_mapped(bh) || buffer_freed(bh))
1637 return 0;
1638 set_buffer_uptodate(bh);
1639 return ext4_handle_dirty_metadata(handle, NULL, bh);
1642 static int ext4_generic_write_end(struct file *file,
1643 struct address_space *mapping,
1644 loff_t pos, unsigned len, unsigned copied,
1645 struct page *page, void *fsdata)
1647 int i_size_changed = 0;
1648 struct inode *inode = mapping->host;
1649 handle_t *handle = ext4_journal_current_handle();
1651 copied = block_write_end(file, mapping, pos, len, copied, page, fsdata);
1654 * No need to use i_size_read() here, the i_size
1655 * cannot change under us because we hold i_mutex.
1657 * But it's important to update i_size while still holding page lock:
1658 * page writeout could otherwise come in and zero beyond i_size.
1660 if (pos + copied > inode->i_size) {
1661 i_size_write(inode, pos + copied);
1662 i_size_changed = 1;
1665 if (pos + copied > EXT4_I(inode)->i_disksize) {
1666 /* We need to mark inode dirty even if
1667 * new_i_size is less that inode->i_size
1668 * bu greater than i_disksize.(hint delalloc)
1670 ext4_update_i_disksize(inode, (pos + copied));
1671 i_size_changed = 1;
1673 unlock_page(page);
1674 page_cache_release(page);
1677 * Don't mark the inode dirty under page lock. First, it unnecessarily
1678 * makes the holding time of page lock longer. Second, it forces lock
1679 * ordering of page lock and transaction start for journaling
1680 * filesystems.
1682 if (i_size_changed)
1683 ext4_mark_inode_dirty(handle, inode);
1685 return copied;
1689 * We need to pick up the new inode size which generic_commit_write gave us
1690 * `file' can be NULL - eg, when called from page_symlink().
1692 * ext4 never places buffers on inode->i_mapping->private_list. metadata
1693 * buffers are managed internally.
1695 static int ext4_ordered_write_end(struct file *file,
1696 struct address_space *mapping,
1697 loff_t pos, unsigned len, unsigned copied,
1698 struct page *page, void *fsdata)
1700 handle_t *handle = ext4_journal_current_handle();
1701 struct inode *inode = mapping->host;
1702 int ret = 0, ret2;
1704 trace_ext4_ordered_write_end(inode, pos, len, copied);
1705 ret = ext4_jbd2_file_inode(handle, inode);
1707 if (ret == 0) {
1708 ret2 = ext4_generic_write_end(file, mapping, pos, len, copied,
1709 page, fsdata);
1710 copied = ret2;
1711 if (pos + len > inode->i_size && ext4_can_truncate(inode))
1712 /* if we have allocated more blocks and copied
1713 * less. We will have blocks allocated outside
1714 * inode->i_size. So truncate them
1716 ext4_orphan_add(handle, inode);
1717 if (ret2 < 0)
1718 ret = ret2;
1720 ret2 = ext4_journal_stop(handle);
1721 if (!ret)
1722 ret = ret2;
1724 if (pos + len > inode->i_size) {
1725 ext4_truncate_failed_write(inode);
1727 * If truncate failed early the inode might still be
1728 * on the orphan list; we need to make sure the inode
1729 * is removed from the orphan list in that case.
1731 if (inode->i_nlink)
1732 ext4_orphan_del(NULL, inode);
1736 return ret ? ret : copied;
1739 static int ext4_writeback_write_end(struct file *file,
1740 struct address_space *mapping,
1741 loff_t pos, unsigned len, unsigned copied,
1742 struct page *page, void *fsdata)
1744 handle_t *handle = ext4_journal_current_handle();
1745 struct inode *inode = mapping->host;
1746 int ret = 0, ret2;
1748 trace_ext4_writeback_write_end(inode, pos, len, copied);
1749 ret2 = ext4_generic_write_end(file, mapping, pos, len, copied,
1750 page, fsdata);
1751 copied = ret2;
1752 if (pos + len > inode->i_size && ext4_can_truncate(inode))
1753 /* if we have allocated more blocks and copied
1754 * less. We will have blocks allocated outside
1755 * inode->i_size. So truncate them
1757 ext4_orphan_add(handle, inode);
1759 if (ret2 < 0)
1760 ret = ret2;
1762 ret2 = ext4_journal_stop(handle);
1763 if (!ret)
1764 ret = ret2;
1766 if (pos + len > inode->i_size) {
1767 ext4_truncate_failed_write(inode);
1769 * If truncate failed early the inode might still be
1770 * on the orphan list; we need to make sure the inode
1771 * is removed from the orphan list in that case.
1773 if (inode->i_nlink)
1774 ext4_orphan_del(NULL, inode);
1777 return ret ? ret : copied;
1780 static int ext4_journalled_write_end(struct file *file,
1781 struct address_space *mapping,
1782 loff_t pos, unsigned len, unsigned copied,
1783 struct page *page, void *fsdata)
1785 handle_t *handle = ext4_journal_current_handle();
1786 struct inode *inode = mapping->host;
1787 int ret = 0, ret2;
1788 int partial = 0;
1789 unsigned from, to;
1790 loff_t new_i_size;
1792 trace_ext4_journalled_write_end(inode, pos, len, copied);
1793 from = pos & (PAGE_CACHE_SIZE - 1);
1794 to = from + len;
1796 if (copied < len) {
1797 if (!PageUptodate(page))
1798 copied = 0;
1799 page_zero_new_buffers(page, from+copied, to);
1802 ret = walk_page_buffers(handle, page_buffers(page), from,
1803 to, &partial, write_end_fn);
1804 if (!partial)
1805 SetPageUptodate(page);
1806 new_i_size = pos + copied;
1807 if (new_i_size > inode->i_size)
1808 i_size_write(inode, pos+copied);
1809 EXT4_I(inode)->i_state |= EXT4_STATE_JDATA;
1810 if (new_i_size > EXT4_I(inode)->i_disksize) {
1811 ext4_update_i_disksize(inode, new_i_size);
1812 ret2 = ext4_mark_inode_dirty(handle, inode);
1813 if (!ret)
1814 ret = ret2;
1817 unlock_page(page);
1818 page_cache_release(page);
1819 if (pos + len > inode->i_size && ext4_can_truncate(inode))
1820 /* if we have allocated more blocks and copied
1821 * less. We will have blocks allocated outside
1822 * inode->i_size. So truncate them
1824 ext4_orphan_add(handle, inode);
1826 ret2 = ext4_journal_stop(handle);
1827 if (!ret)
1828 ret = ret2;
1829 if (pos + len > inode->i_size) {
1830 ext4_truncate_failed_write(inode);
1832 * If truncate failed early the inode might still be
1833 * on the orphan list; we need to make sure the inode
1834 * is removed from the orphan list in that case.
1836 if (inode->i_nlink)
1837 ext4_orphan_del(NULL, inode);
1840 return ret ? ret : copied;
1843 static int ext4_da_reserve_space(struct inode *inode, int nrblocks)
1845 int retries = 0;
1846 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1847 unsigned long md_needed, mdblocks, total = 0;
1850 * recalculate the amount of metadata blocks to reserve
1851 * in order to allocate nrblocks
1852 * worse case is one extent per block
1854 repeat:
1855 spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
1856 total = EXT4_I(inode)->i_reserved_data_blocks + nrblocks;
1857 mdblocks = ext4_calc_metadata_amount(inode, total);
1858 BUG_ON(mdblocks < EXT4_I(inode)->i_reserved_meta_blocks);
1860 md_needed = mdblocks - EXT4_I(inode)->i_reserved_meta_blocks;
1861 total = md_needed + nrblocks;
1864 * Make quota reservation here to prevent quota overflow
1865 * later. Real quota accounting is done at pages writeout
1866 * time.
1868 if (vfs_dq_reserve_block(inode, total)) {
1869 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
1870 return -EDQUOT;
1873 if (ext4_claim_free_blocks(sbi, total)) {
1874 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
1875 vfs_dq_release_reservation_block(inode, total);
1876 if (ext4_should_retry_alloc(inode->i_sb, &retries)) {
1877 yield();
1878 goto repeat;
1880 return -ENOSPC;
1882 EXT4_I(inode)->i_reserved_data_blocks += nrblocks;
1883 EXT4_I(inode)->i_reserved_meta_blocks = mdblocks;
1885 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
1886 return 0; /* success */
1889 static void ext4_da_release_space(struct inode *inode, int to_free)
1891 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1892 int total, mdb, mdb_free, release;
1894 if (!to_free)
1895 return; /* Nothing to release, exit */
1897 spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
1899 if (!EXT4_I(inode)->i_reserved_data_blocks) {
1901 * if there is no reserved blocks, but we try to free some
1902 * then the counter is messed up somewhere.
1903 * but since this function is called from invalidate
1904 * page, it's harmless to return without any action
1906 printk(KERN_INFO "ext4 delalloc try to release %d reserved "
1907 "blocks for inode %lu, but there is no reserved "
1908 "data blocks\n", to_free, inode->i_ino);
1909 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
1910 return;
1913 /* recalculate the number of metablocks still need to be reserved */
1914 total = EXT4_I(inode)->i_reserved_data_blocks - to_free;
1915 mdb = ext4_calc_metadata_amount(inode, total);
1917 /* figure out how many metablocks to release */
1918 BUG_ON(mdb > EXT4_I(inode)->i_reserved_meta_blocks);
1919 mdb_free = EXT4_I(inode)->i_reserved_meta_blocks - mdb;
1921 release = to_free + mdb_free;
1923 /* update fs dirty blocks counter for truncate case */
1924 percpu_counter_sub(&sbi->s_dirtyblocks_counter, release);
1926 /* update per-inode reservations */
1927 BUG_ON(to_free > EXT4_I(inode)->i_reserved_data_blocks);
1928 EXT4_I(inode)->i_reserved_data_blocks -= to_free;
1930 BUG_ON(mdb > EXT4_I(inode)->i_reserved_meta_blocks);
1931 EXT4_I(inode)->i_reserved_meta_blocks = mdb;
1932 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
1934 vfs_dq_release_reservation_block(inode, release);
1937 static void ext4_da_page_release_reservation(struct page *page,
1938 unsigned long offset)
1940 int to_release = 0;
1941 struct buffer_head *head, *bh;
1942 unsigned int curr_off = 0;
1944 head = page_buffers(page);
1945 bh = head;
1946 do {
1947 unsigned int next_off = curr_off + bh->b_size;
1949 if ((offset <= curr_off) && (buffer_delay(bh))) {
1950 to_release++;
1951 clear_buffer_delay(bh);
1953 curr_off = next_off;
1954 } while ((bh = bh->b_this_page) != head);
1955 ext4_da_release_space(page->mapping->host, to_release);
1959 * mpage_da_submit_io - walks through extent of pages and try to write
1960 * them with writepage() call back
1962 * @mpd->inode: inode
1963 * @mpd->first_page: first page of the extent
1964 * @mpd->next_page: page after the last page of the extent
1966 * By the time mpage_da_submit_io() is called we expect all blocks
1967 * to be allocated. this may be wrong if allocation failed.
1969 * As pages are already locked by write_cache_pages(), we can't use it
1971 static int mpage_da_submit_io(struct mpage_da_data *mpd)
1973 long pages_skipped;
1974 struct pagevec pvec;
1975 unsigned long index, end;
1976 int ret = 0, err, nr_pages, i;
1977 struct inode *inode = mpd->inode;
1978 struct address_space *mapping = inode->i_mapping;
1980 BUG_ON(mpd->next_page <= mpd->first_page);
1982 * We need to start from the first_page to the next_page - 1
1983 * to make sure we also write the mapped dirty buffer_heads.
1984 * If we look at mpd->b_blocknr we would only be looking
1985 * at the currently mapped buffer_heads.
1987 index = mpd->first_page;
1988 end = mpd->next_page - 1;
1990 pagevec_init(&pvec, 0);
1991 while (index <= end) {
1992 nr_pages = pagevec_lookup(&pvec, mapping, index, PAGEVEC_SIZE);
1993 if (nr_pages == 0)
1994 break;
1995 for (i = 0; i < nr_pages; i++) {
1996 struct page *page = pvec.pages[i];
1998 index = page->index;
1999 if (index > end)
2000 break;
2001 index++;
2003 BUG_ON(!PageLocked(page));
2004 BUG_ON(PageWriteback(page));
2006 pages_skipped = mpd->wbc->pages_skipped;
2007 err = mapping->a_ops->writepage(page, mpd->wbc);
2008 if (!err && (pages_skipped == mpd->wbc->pages_skipped))
2010 * have successfully written the page
2011 * without skipping the same
2013 mpd->pages_written++;
2015 * In error case, we have to continue because
2016 * remaining pages are still locked
2017 * XXX: unlock and re-dirty them?
2019 if (ret == 0)
2020 ret = err;
2022 pagevec_release(&pvec);
2024 return ret;
2028 * mpage_put_bnr_to_bhs - walk blocks and assign them actual numbers
2030 * @mpd->inode - inode to walk through
2031 * @exbh->b_blocknr - first block on a disk
2032 * @exbh->b_size - amount of space in bytes
2033 * @logical - first logical block to start assignment with
2035 * the function goes through all passed space and put actual disk
2036 * block numbers into buffer heads, dropping BH_Delay and BH_Unwritten
2038 static void mpage_put_bnr_to_bhs(struct mpage_da_data *mpd, sector_t logical,
2039 struct buffer_head *exbh)
2041 struct inode *inode = mpd->inode;
2042 struct address_space *mapping = inode->i_mapping;
2043 int blocks = exbh->b_size >> inode->i_blkbits;
2044 sector_t pblock = exbh->b_blocknr, cur_logical;
2045 struct buffer_head *head, *bh;
2046 pgoff_t index, end;
2047 struct pagevec pvec;
2048 int nr_pages, i;
2050 index = logical >> (PAGE_CACHE_SHIFT - inode->i_blkbits);
2051 end = (logical + blocks - 1) >> (PAGE_CACHE_SHIFT - inode->i_blkbits);
2052 cur_logical = index << (PAGE_CACHE_SHIFT - inode->i_blkbits);
2054 pagevec_init(&pvec, 0);
2056 while (index <= end) {
2057 /* XXX: optimize tail */
2058 nr_pages = pagevec_lookup(&pvec, mapping, index, PAGEVEC_SIZE);
2059 if (nr_pages == 0)
2060 break;
2061 for (i = 0; i < nr_pages; i++) {
2062 struct page *page = pvec.pages[i];
2064 index = page->index;
2065 if (index > end)
2066 break;
2067 index++;
2069 BUG_ON(!PageLocked(page));
2070 BUG_ON(PageWriteback(page));
2071 BUG_ON(!page_has_buffers(page));
2073 bh = page_buffers(page);
2074 head = bh;
2076 /* skip blocks out of the range */
2077 do {
2078 if (cur_logical >= logical)
2079 break;
2080 cur_logical++;
2081 } while ((bh = bh->b_this_page) != head);
2083 do {
2084 if (cur_logical >= logical + blocks)
2085 break;
2087 if (buffer_delay(bh) ||
2088 buffer_unwritten(bh)) {
2090 BUG_ON(bh->b_bdev != inode->i_sb->s_bdev);
2092 if (buffer_delay(bh)) {
2093 clear_buffer_delay(bh);
2094 bh->b_blocknr = pblock;
2095 } else {
2097 * unwritten already should have
2098 * blocknr assigned. Verify that
2100 clear_buffer_unwritten(bh);
2101 BUG_ON(bh->b_blocknr != pblock);
2104 } else if (buffer_mapped(bh))
2105 BUG_ON(bh->b_blocknr != pblock);
2107 cur_logical++;
2108 pblock++;
2109 } while ((bh = bh->b_this_page) != head);
2111 pagevec_release(&pvec);
2117 * __unmap_underlying_blocks - just a helper function to unmap
2118 * set of blocks described by @bh
2120 static inline void __unmap_underlying_blocks(struct inode *inode,
2121 struct buffer_head *bh)
2123 struct block_device *bdev = inode->i_sb->s_bdev;
2124 int blocks, i;
2126 blocks = bh->b_size >> inode->i_blkbits;
2127 for (i = 0; i < blocks; i++)
2128 unmap_underlying_metadata(bdev, bh->b_blocknr + i);
2131 static void ext4_da_block_invalidatepages(struct mpage_da_data *mpd,
2132 sector_t logical, long blk_cnt)
2134 int nr_pages, i;
2135 pgoff_t index, end;
2136 struct pagevec pvec;
2137 struct inode *inode = mpd->inode;
2138 struct address_space *mapping = inode->i_mapping;
2140 index = logical >> (PAGE_CACHE_SHIFT - inode->i_blkbits);
2141 end = (logical + blk_cnt - 1) >>
2142 (PAGE_CACHE_SHIFT - inode->i_blkbits);
2143 while (index <= end) {
2144 nr_pages = pagevec_lookup(&pvec, mapping, index, PAGEVEC_SIZE);
2145 if (nr_pages == 0)
2146 break;
2147 for (i = 0; i < nr_pages; i++) {
2148 struct page *page = pvec.pages[i];
2149 index = page->index;
2150 if (index > end)
2151 break;
2152 index++;
2154 BUG_ON(!PageLocked(page));
2155 BUG_ON(PageWriteback(page));
2156 block_invalidatepage(page, 0);
2157 ClearPageUptodate(page);
2158 unlock_page(page);
2161 return;
2164 static void ext4_print_free_blocks(struct inode *inode)
2166 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
2167 printk(KERN_EMERG "Total free blocks count %lld\n",
2168 ext4_count_free_blocks(inode->i_sb));
2169 printk(KERN_EMERG "Free/Dirty block details\n");
2170 printk(KERN_EMERG "free_blocks=%lld\n",
2171 (long long)percpu_counter_sum(&sbi->s_freeblocks_counter));
2172 printk(KERN_EMERG "dirty_blocks=%lld\n",
2173 (long long)percpu_counter_sum(&sbi->s_dirtyblocks_counter));
2174 printk(KERN_EMERG "Block reservation details\n");
2175 printk(KERN_EMERG "i_reserved_data_blocks=%u\n",
2176 EXT4_I(inode)->i_reserved_data_blocks);
2177 printk(KERN_EMERG "i_reserved_meta_blocks=%u\n",
2178 EXT4_I(inode)->i_reserved_meta_blocks);
2179 return;
2183 * mpage_da_map_blocks - go through given space
2185 * @mpd - bh describing space
2187 * The function skips space we know is already mapped to disk blocks.
2190 static int mpage_da_map_blocks(struct mpage_da_data *mpd)
2192 int err, blks, get_blocks_flags;
2193 struct buffer_head new;
2194 sector_t next = mpd->b_blocknr;
2195 unsigned max_blocks = mpd->b_size >> mpd->inode->i_blkbits;
2196 loff_t disksize = EXT4_I(mpd->inode)->i_disksize;
2197 handle_t *handle = NULL;
2200 * We consider only non-mapped and non-allocated blocks
2202 if ((mpd->b_state & (1 << BH_Mapped)) &&
2203 !(mpd->b_state & (1 << BH_Delay)) &&
2204 !(mpd->b_state & (1 << BH_Unwritten)))
2205 return 0;
2208 * If we didn't accumulate anything to write simply return
2210 if (!mpd->b_size)
2211 return 0;
2213 handle = ext4_journal_current_handle();
2214 BUG_ON(!handle);
2217 * Call ext4_get_blocks() to allocate any delayed allocation
2218 * blocks, or to convert an uninitialized extent to be
2219 * initialized (in the case where we have written into
2220 * one or more preallocated blocks).
2222 * We pass in the magic EXT4_GET_BLOCKS_DELALLOC_RESERVE to
2223 * indicate that we are on the delayed allocation path. This
2224 * affects functions in many different parts of the allocation
2225 * call path. This flag exists primarily because we don't
2226 * want to change *many* call functions, so ext4_get_blocks()
2227 * will set the magic i_delalloc_reserved_flag once the
2228 * inode's allocation semaphore is taken.
2230 * If the blocks in questions were delalloc blocks, set
2231 * EXT4_GET_BLOCKS_DELALLOC_RESERVE so the delalloc accounting
2232 * variables are updated after the blocks have been allocated.
2234 new.b_state = 0;
2235 get_blocks_flags = (EXT4_GET_BLOCKS_CREATE |
2236 EXT4_GET_BLOCKS_DELALLOC_RESERVE);
2237 if (mpd->b_state & (1 << BH_Delay))
2238 get_blocks_flags |= EXT4_GET_BLOCKS_UPDATE_RESERVE_SPACE;
2239 blks = ext4_get_blocks(handle, mpd->inode, next, max_blocks,
2240 &new, get_blocks_flags);
2241 if (blks < 0) {
2242 err = blks;
2244 * If get block returns with error we simply
2245 * return. Later writepage will redirty the page and
2246 * writepages will find the dirty page again
2248 if (err == -EAGAIN)
2249 return 0;
2251 if (err == -ENOSPC &&
2252 ext4_count_free_blocks(mpd->inode->i_sb)) {
2253 mpd->retval = err;
2254 return 0;
2258 * get block failure will cause us to loop in
2259 * writepages, because a_ops->writepage won't be able
2260 * to make progress. The page will be redirtied by
2261 * writepage and writepages will again try to write
2262 * the same.
2264 printk(KERN_EMERG "%s block allocation failed for inode %lu "
2265 "at logical offset %llu with max blocks "
2266 "%zd with error %d\n",
2267 __func__, mpd->inode->i_ino,
2268 (unsigned long long)next,
2269 mpd->b_size >> mpd->inode->i_blkbits, err);
2270 printk(KERN_EMERG "This should not happen.!! "
2271 "Data will be lost\n");
2272 if (err == -ENOSPC) {
2273 ext4_print_free_blocks(mpd->inode);
2275 /* invalidate all the pages */
2276 ext4_da_block_invalidatepages(mpd, next,
2277 mpd->b_size >> mpd->inode->i_blkbits);
2278 return err;
2280 BUG_ON(blks == 0);
2282 new.b_size = (blks << mpd->inode->i_blkbits);
2284 if (buffer_new(&new))
2285 __unmap_underlying_blocks(mpd->inode, &new);
2288 * If blocks are delayed marked, we need to
2289 * put actual blocknr and drop delayed bit
2291 if ((mpd->b_state & (1 << BH_Delay)) ||
2292 (mpd->b_state & (1 << BH_Unwritten)))
2293 mpage_put_bnr_to_bhs(mpd, next, &new);
2295 if (ext4_should_order_data(mpd->inode)) {
2296 err = ext4_jbd2_file_inode(handle, mpd->inode);
2297 if (err)
2298 return err;
2302 * Update on-disk size along with block allocation.
2304 disksize = ((loff_t) next + blks) << mpd->inode->i_blkbits;
2305 if (disksize > i_size_read(mpd->inode))
2306 disksize = i_size_read(mpd->inode);
2307 if (disksize > EXT4_I(mpd->inode)->i_disksize) {
2308 ext4_update_i_disksize(mpd->inode, disksize);
2309 return ext4_mark_inode_dirty(handle, mpd->inode);
2312 return 0;
2315 #define BH_FLAGS ((1 << BH_Uptodate) | (1 << BH_Mapped) | \
2316 (1 << BH_Delay) | (1 << BH_Unwritten))
2319 * mpage_add_bh_to_extent - try to add one more block to extent of blocks
2321 * @mpd->lbh - extent of blocks
2322 * @logical - logical number of the block in the file
2323 * @bh - bh of the block (used to access block's state)
2325 * the function is used to collect contig. blocks in same state
2327 static void mpage_add_bh_to_extent(struct mpage_da_data *mpd,
2328 sector_t logical, size_t b_size,
2329 unsigned long b_state)
2331 sector_t next;
2332 int nrblocks = mpd->b_size >> mpd->inode->i_blkbits;
2334 /* check if thereserved journal credits might overflow */
2335 if (!(EXT4_I(mpd->inode)->i_flags & EXT4_EXTENTS_FL)) {
2336 if (nrblocks >= EXT4_MAX_TRANS_DATA) {
2338 * With non-extent format we are limited by the journal
2339 * credit available. Total credit needed to insert
2340 * nrblocks contiguous blocks is dependent on the
2341 * nrblocks. So limit nrblocks.
2343 goto flush_it;
2344 } else if ((nrblocks + (b_size >> mpd->inode->i_blkbits)) >
2345 EXT4_MAX_TRANS_DATA) {
2347 * Adding the new buffer_head would make it cross the
2348 * allowed limit for which we have journal credit
2349 * reserved. So limit the new bh->b_size
2351 b_size = (EXT4_MAX_TRANS_DATA - nrblocks) <<
2352 mpd->inode->i_blkbits;
2353 /* we will do mpage_da_submit_io in the next loop */
2357 * First block in the extent
2359 if (mpd->b_size == 0) {
2360 mpd->b_blocknr = logical;
2361 mpd->b_size = b_size;
2362 mpd->b_state = b_state & BH_FLAGS;
2363 return;
2366 next = mpd->b_blocknr + nrblocks;
2368 * Can we merge the block to our big extent?
2370 if (logical == next && (b_state & BH_FLAGS) == mpd->b_state) {
2371 mpd->b_size += b_size;
2372 return;
2375 flush_it:
2377 * We couldn't merge the block to our extent, so we
2378 * need to flush current extent and start new one
2380 if (mpage_da_map_blocks(mpd) == 0)
2381 mpage_da_submit_io(mpd);
2382 mpd->io_done = 1;
2383 return;
2386 static int ext4_bh_delay_or_unwritten(handle_t *handle, struct buffer_head *bh)
2388 return (buffer_delay(bh) || buffer_unwritten(bh)) && buffer_dirty(bh);
2392 * __mpage_da_writepage - finds extent of pages and blocks
2394 * @page: page to consider
2395 * @wbc: not used, we just follow rules
2396 * @data: context
2398 * The function finds extents of pages and scan them for all blocks.
2400 static int __mpage_da_writepage(struct page *page,
2401 struct writeback_control *wbc, void *data)
2403 struct mpage_da_data *mpd = data;
2404 struct inode *inode = mpd->inode;
2405 struct buffer_head *bh, *head;
2406 sector_t logical;
2408 if (mpd->io_done) {
2410 * Rest of the page in the page_vec
2411 * redirty then and skip then. We will
2412 * try to to write them again after
2413 * starting a new transaction
2415 redirty_page_for_writepage(wbc, page);
2416 unlock_page(page);
2417 return MPAGE_DA_EXTENT_TAIL;
2420 * Can we merge this page to current extent?
2422 if (mpd->next_page != page->index) {
2424 * Nope, we can't. So, we map non-allocated blocks
2425 * and start IO on them using writepage()
2427 if (mpd->next_page != mpd->first_page) {
2428 if (mpage_da_map_blocks(mpd) == 0)
2429 mpage_da_submit_io(mpd);
2431 * skip rest of the page in the page_vec
2433 mpd->io_done = 1;
2434 redirty_page_for_writepage(wbc, page);
2435 unlock_page(page);
2436 return MPAGE_DA_EXTENT_TAIL;
2440 * Start next extent of pages ...
2442 mpd->first_page = page->index;
2445 * ... and blocks
2447 mpd->b_size = 0;
2448 mpd->b_state = 0;
2449 mpd->b_blocknr = 0;
2452 mpd->next_page = page->index + 1;
2453 logical = (sector_t) page->index <<
2454 (PAGE_CACHE_SHIFT - inode->i_blkbits);
2456 if (!page_has_buffers(page)) {
2457 mpage_add_bh_to_extent(mpd, logical, PAGE_CACHE_SIZE,
2458 (1 << BH_Dirty) | (1 << BH_Uptodate));
2459 if (mpd->io_done)
2460 return MPAGE_DA_EXTENT_TAIL;
2461 } else {
2463 * Page with regular buffer heads, just add all dirty ones
2465 head = page_buffers(page);
2466 bh = head;
2467 do {
2468 BUG_ON(buffer_locked(bh));
2470 * We need to try to allocate
2471 * unmapped blocks in the same page.
2472 * Otherwise we won't make progress
2473 * with the page in ext4_writepage
2475 if (ext4_bh_delay_or_unwritten(NULL, bh)) {
2476 mpage_add_bh_to_extent(mpd, logical,
2477 bh->b_size,
2478 bh->b_state);
2479 if (mpd->io_done)
2480 return MPAGE_DA_EXTENT_TAIL;
2481 } else if (buffer_dirty(bh) && (buffer_mapped(bh))) {
2483 * mapped dirty buffer. We need to update
2484 * the b_state because we look at
2485 * b_state in mpage_da_map_blocks. We don't
2486 * update b_size because if we find an
2487 * unmapped buffer_head later we need to
2488 * use the b_state flag of that buffer_head.
2490 if (mpd->b_size == 0)
2491 mpd->b_state = bh->b_state & BH_FLAGS;
2493 logical++;
2494 } while ((bh = bh->b_this_page) != head);
2497 return 0;
2501 * This is a special get_blocks_t callback which is used by
2502 * ext4_da_write_begin(). It will either return mapped block or
2503 * reserve space for a single block.
2505 * For delayed buffer_head we have BH_Mapped, BH_New, BH_Delay set.
2506 * We also have b_blocknr = -1 and b_bdev initialized properly
2508 * For unwritten buffer_head we have BH_Mapped, BH_New, BH_Unwritten set.
2509 * We also have b_blocknr = physicalblock mapping unwritten extent and b_bdev
2510 * initialized properly.
2512 static int ext4_da_get_block_prep(struct inode *inode, sector_t iblock,
2513 struct buffer_head *bh_result, int create)
2515 int ret = 0;
2516 sector_t invalid_block = ~((sector_t) 0xffff);
2518 if (invalid_block < ext4_blocks_count(EXT4_SB(inode->i_sb)->s_es))
2519 invalid_block = ~0;
2521 BUG_ON(create == 0);
2522 BUG_ON(bh_result->b_size != inode->i_sb->s_blocksize);
2525 * first, we need to know whether the block is allocated already
2526 * preallocated blocks are unmapped but should treated
2527 * the same as allocated blocks.
2529 ret = ext4_get_blocks(NULL, inode, iblock, 1, bh_result, 0);
2530 if ((ret == 0) && !buffer_delay(bh_result)) {
2531 /* the block isn't (pre)allocated yet, let's reserve space */
2533 * XXX: __block_prepare_write() unmaps passed block,
2534 * is it OK?
2536 ret = ext4_da_reserve_space(inode, 1);
2537 if (ret)
2538 /* not enough space to reserve */
2539 return ret;
2541 map_bh(bh_result, inode->i_sb, invalid_block);
2542 set_buffer_new(bh_result);
2543 set_buffer_delay(bh_result);
2544 } else if (ret > 0) {
2545 bh_result->b_size = (ret << inode->i_blkbits);
2546 if (buffer_unwritten(bh_result)) {
2547 /* A delayed write to unwritten bh should
2548 * be marked new and mapped. Mapped ensures
2549 * that we don't do get_block multiple times
2550 * when we write to the same offset and new
2551 * ensures that we do proper zero out for
2552 * partial write.
2554 set_buffer_new(bh_result);
2555 set_buffer_mapped(bh_result);
2557 ret = 0;
2560 return ret;
2564 * This function is used as a standard get_block_t calback function
2565 * when there is no desire to allocate any blocks. It is used as a
2566 * callback function for block_prepare_write(), nobh_writepage(), and
2567 * block_write_full_page(). These functions should only try to map a
2568 * 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 nobh_writepage() or
2575 * block_write_full_page(). Otherwise, b_blocknr could be left
2576 * unitialized, and the page write functions will be taken by
2577 * surprise.
2579 static int noalloc_get_block_write(struct inode *inode, sector_t iblock,
2580 struct buffer_head *bh_result, int create)
2582 int ret = 0;
2583 unsigned max_blocks = bh_result->b_size >> inode->i_blkbits;
2585 BUG_ON(bh_result->b_size != inode->i_sb->s_blocksize);
2588 * we don't want to do block allocation in writepage
2589 * so call get_block_wrap with create = 0
2591 ret = ext4_get_blocks(NULL, inode, iblock, max_blocks, bh_result, 0);
2592 if (ret > 0) {
2593 bh_result->b_size = (ret << inode->i_blkbits);
2594 ret = 0;
2596 return ret;
2599 static int bget_one(handle_t *handle, struct buffer_head *bh)
2601 get_bh(bh);
2602 return 0;
2605 static int bput_one(handle_t *handle, struct buffer_head *bh)
2607 put_bh(bh);
2608 return 0;
2611 static int __ext4_journalled_writepage(struct page *page,
2612 struct writeback_control *wbc,
2613 unsigned int len)
2615 struct address_space *mapping = page->mapping;
2616 struct inode *inode = mapping->host;
2617 struct buffer_head *page_bufs;
2618 handle_t *handle = NULL;
2619 int ret = 0;
2620 int err;
2622 page_bufs = page_buffers(page);
2623 BUG_ON(!page_bufs);
2624 walk_page_buffers(handle, page_bufs, 0, len, NULL, bget_one);
2625 /* As soon as we unlock the page, it can go away, but we have
2626 * references to buffers so we are safe */
2627 unlock_page(page);
2629 handle = ext4_journal_start(inode, ext4_writepage_trans_blocks(inode));
2630 if (IS_ERR(handle)) {
2631 ret = PTR_ERR(handle);
2632 goto out;
2635 ret = walk_page_buffers(handle, page_bufs, 0, len, NULL,
2636 do_journal_get_write_access);
2638 err = walk_page_buffers(handle, page_bufs, 0, len, NULL,
2639 write_end_fn);
2640 if (ret == 0)
2641 ret = err;
2642 err = ext4_journal_stop(handle);
2643 if (!ret)
2644 ret = err;
2646 walk_page_buffers(handle, page_bufs, 0, len, NULL, bput_one);
2647 EXT4_I(inode)->i_state |= EXT4_STATE_JDATA;
2648 out:
2649 return ret;
2653 * Note that we don't need to start a transaction unless we're journaling data
2654 * because we should have holes filled from ext4_page_mkwrite(). We even don't
2655 * need to file the inode to the transaction's list in ordered mode because if
2656 * we are writing back data added by write(), the inode is already there and if
2657 * we are writing back data modified via mmap(), noone guarantees in which
2658 * transaction the data will hit the disk. In case we are journaling data, we
2659 * cannot start transaction directly because transaction start ranks above page
2660 * lock so we have to do some magic.
2662 * This function can get called via...
2663 * - ext4_da_writepages after taking page lock (have journal handle)
2664 * - journal_submit_inode_data_buffers (no journal handle)
2665 * - shrink_page_list via pdflush (no journal handle)
2666 * - grab_page_cache when doing write_begin (have journal handle)
2668 * We don't do any block allocation in this function. If we have page with
2669 * multiple blocks we need to write those buffer_heads that are mapped. This
2670 * is important for mmaped based write. So if we do with blocksize 1K
2671 * truncate(f, 1024);
2672 * a = mmap(f, 0, 4096);
2673 * a[0] = 'a';
2674 * truncate(f, 4096);
2675 * we have in the page first buffer_head mapped via page_mkwrite call back
2676 * but other bufer_heads would be unmapped but dirty(dirty done via the
2677 * do_wp_page). So writepage should write the first block. If we modify
2678 * the mmap area beyond 1024 we will again get a page_fault and the
2679 * page_mkwrite callback will do the block allocation and mark the
2680 * buffer_heads mapped.
2682 * We redirty the page if we have any buffer_heads that is either delay or
2683 * unwritten in the page.
2685 * We can get recursively called as show below.
2687 * ext4_writepage() -> kmalloc() -> __alloc_pages() -> page_launder() ->
2688 * ext4_writepage()
2690 * But since we don't do any block allocation we should not deadlock.
2691 * Page also have the dirty flag cleared so we don't get recurive page_lock.
2693 static int ext4_writepage(struct page *page,
2694 struct writeback_control *wbc)
2696 int ret = 0;
2697 loff_t size;
2698 unsigned int len;
2699 struct buffer_head *page_bufs;
2700 struct inode *inode = page->mapping->host;
2702 trace_ext4_writepage(inode, page);
2703 size = i_size_read(inode);
2704 if (page->index == size >> PAGE_CACHE_SHIFT)
2705 len = size & ~PAGE_CACHE_MASK;
2706 else
2707 len = PAGE_CACHE_SIZE;
2709 if (page_has_buffers(page)) {
2710 page_bufs = page_buffers(page);
2711 if (walk_page_buffers(NULL, page_bufs, 0, len, NULL,
2712 ext4_bh_delay_or_unwritten)) {
2714 * We don't want to do block allocation
2715 * So redirty the page and return
2716 * We may reach here when we do a journal commit
2717 * via journal_submit_inode_data_buffers.
2718 * If we don't have mapping block we just ignore
2719 * them. We can also reach here via shrink_page_list
2721 redirty_page_for_writepage(wbc, page);
2722 unlock_page(page);
2723 return 0;
2725 } else {
2727 * The test for page_has_buffers() is subtle:
2728 * We know the page is dirty but it lost buffers. That means
2729 * that at some moment in time after write_begin()/write_end()
2730 * has been called all buffers have been clean and thus they
2731 * must have been written at least once. So they are all
2732 * mapped and we can happily proceed with mapping them
2733 * and writing the page.
2735 * Try to initialize the buffer_heads and check whether
2736 * all are mapped and non delay. We don't want to
2737 * do block allocation here.
2739 ret = block_prepare_write(page, 0, len,
2740 noalloc_get_block_write);
2741 if (!ret) {
2742 page_bufs = page_buffers(page);
2743 /* check whether all are mapped and non delay */
2744 if (walk_page_buffers(NULL, page_bufs, 0, len, NULL,
2745 ext4_bh_delay_or_unwritten)) {
2746 redirty_page_for_writepage(wbc, page);
2747 unlock_page(page);
2748 return 0;
2750 } else {
2752 * We can't do block allocation here
2753 * so just redity the page and unlock
2754 * and return
2756 redirty_page_for_writepage(wbc, page);
2757 unlock_page(page);
2758 return 0;
2760 /* now mark the buffer_heads as dirty and uptodate */
2761 block_commit_write(page, 0, len);
2764 if (PageChecked(page) && ext4_should_journal_data(inode)) {
2766 * It's mmapped pagecache. Add buffers and journal it. There
2767 * doesn't seem much point in redirtying the page here.
2769 ClearPageChecked(page);
2770 return __ext4_journalled_writepage(page, wbc, len);
2773 if (test_opt(inode->i_sb, NOBH) && ext4_should_writeback_data(inode))
2774 ret = nobh_writepage(page, noalloc_get_block_write, wbc);
2775 else
2776 ret = block_write_full_page(page, noalloc_get_block_write,
2777 wbc);
2779 return ret;
2783 * This is called via ext4_da_writepages() to
2784 * calulate the total number of credits to reserve to fit
2785 * a single extent allocation into a single transaction,
2786 * ext4_da_writpeages() will loop calling this before
2787 * the block allocation.
2790 static int ext4_da_writepages_trans_blocks(struct inode *inode)
2792 int max_blocks = EXT4_I(inode)->i_reserved_data_blocks;
2795 * With non-extent format the journal credit needed to
2796 * insert nrblocks contiguous block is dependent on
2797 * number of contiguous block. So we will limit
2798 * number of contiguous block to a sane value
2800 if (!(EXT4_I(inode)->i_flags & EXT4_EXTENTS_FL) &&
2801 (max_blocks > EXT4_MAX_TRANS_DATA))
2802 max_blocks = EXT4_MAX_TRANS_DATA;
2804 return ext4_chunk_trans_blocks(inode, max_blocks);
2807 static int ext4_da_writepages(struct address_space *mapping,
2808 struct writeback_control *wbc)
2810 pgoff_t index;
2811 int range_whole = 0;
2812 handle_t *handle = NULL;
2813 struct mpage_da_data mpd;
2814 struct inode *inode = mapping->host;
2815 int no_nrwrite_index_update;
2816 int pages_written = 0;
2817 long pages_skipped;
2818 unsigned int max_pages;
2819 int range_cyclic, cycled = 1, io_done = 0;
2820 int needed_blocks, ret = 0;
2821 long desired_nr_to_write, nr_to_writebump = 0;
2822 loff_t range_start = wbc->range_start;
2823 struct ext4_sb_info *sbi = EXT4_SB(mapping->host->i_sb);
2825 trace_ext4_da_writepages(inode, wbc);
2828 * No pages to write? This is mainly a kludge to avoid starting
2829 * a transaction for special inodes like journal inode on last iput()
2830 * because that could violate lock ordering on umount
2832 if (!mapping->nrpages || !mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
2833 return 0;
2836 * If the filesystem has aborted, it is read-only, so return
2837 * right away instead of dumping stack traces later on that
2838 * will obscure the real source of the problem. We test
2839 * EXT4_MF_FS_ABORTED instead of sb->s_flag's MS_RDONLY because
2840 * the latter could be true if the filesystem is mounted
2841 * read-only, and in that case, ext4_da_writepages should
2842 * *never* be called, so if that ever happens, we would want
2843 * the stack trace.
2845 if (unlikely(sbi->s_mount_flags & EXT4_MF_FS_ABORTED))
2846 return -EROFS;
2848 if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
2849 range_whole = 1;
2851 range_cyclic = wbc->range_cyclic;
2852 if (wbc->range_cyclic) {
2853 index = mapping->writeback_index;
2854 if (index)
2855 cycled = 0;
2856 wbc->range_start = index << PAGE_CACHE_SHIFT;
2857 wbc->range_end = LLONG_MAX;
2858 wbc->range_cyclic = 0;
2859 } else
2860 index = wbc->range_start >> PAGE_CACHE_SHIFT;
2863 * This works around two forms of stupidity. The first is in
2864 * the writeback code, which caps the maximum number of pages
2865 * written to be 1024 pages. This is wrong on multiple
2866 * levels; different architectues have a different page size,
2867 * which changes the maximum amount of data which gets
2868 * written. Secondly, 4 megabytes is way too small. XFS
2869 * forces this value to be 16 megabytes by multiplying
2870 * nr_to_write parameter by four, and then relies on its
2871 * allocator to allocate larger extents to make them
2872 * contiguous. Unfortunately this brings us to the second
2873 * stupidity, which is that ext4's mballoc code only allocates
2874 * at most 2048 blocks. So we force contiguous writes up to
2875 * the number of dirty blocks in the inode, or
2876 * sbi->max_writeback_mb_bump whichever is smaller.
2878 max_pages = sbi->s_max_writeback_mb_bump << (20 - PAGE_CACHE_SHIFT);
2879 if (!range_cyclic && range_whole)
2880 desired_nr_to_write = wbc->nr_to_write * 8;
2881 else
2882 desired_nr_to_write = ext4_num_dirty_pages(inode, index,
2883 max_pages);
2884 if (desired_nr_to_write > max_pages)
2885 desired_nr_to_write = max_pages;
2887 if (wbc->nr_to_write < desired_nr_to_write) {
2888 nr_to_writebump = desired_nr_to_write - wbc->nr_to_write;
2889 wbc->nr_to_write = desired_nr_to_write;
2892 mpd.wbc = wbc;
2893 mpd.inode = mapping->host;
2896 * we don't want write_cache_pages to update
2897 * nr_to_write and writeback_index
2899 no_nrwrite_index_update = wbc->no_nrwrite_index_update;
2900 wbc->no_nrwrite_index_update = 1;
2901 pages_skipped = wbc->pages_skipped;
2903 retry:
2904 while (!ret && wbc->nr_to_write > 0) {
2907 * we insert one extent at a time. So we need
2908 * credit needed for single extent allocation.
2909 * journalled mode is currently not supported
2910 * by delalloc
2912 BUG_ON(ext4_should_journal_data(inode));
2913 needed_blocks = ext4_da_writepages_trans_blocks(inode);
2915 /* start a new transaction*/
2916 handle = ext4_journal_start(inode, needed_blocks);
2917 if (IS_ERR(handle)) {
2918 ret = PTR_ERR(handle);
2919 printk(KERN_CRIT "%s: jbd2_start: "
2920 "%ld pages, ino %lu; err %d\n", __func__,
2921 wbc->nr_to_write, inode->i_ino, ret);
2922 dump_stack();
2923 goto out_writepages;
2927 * Now call __mpage_da_writepage to find the next
2928 * contiguous region of logical blocks that need
2929 * blocks to be allocated by ext4. We don't actually
2930 * submit the blocks for I/O here, even though
2931 * write_cache_pages thinks it will, and will set the
2932 * pages as clean for write before calling
2933 * __mpage_da_writepage().
2935 mpd.b_size = 0;
2936 mpd.b_state = 0;
2937 mpd.b_blocknr = 0;
2938 mpd.first_page = 0;
2939 mpd.next_page = 0;
2940 mpd.io_done = 0;
2941 mpd.pages_written = 0;
2942 mpd.retval = 0;
2943 ret = write_cache_pages(mapping, wbc, __mpage_da_writepage,
2944 &mpd);
2946 * If we have a contigous extent of pages and we
2947 * haven't done the I/O yet, map the blocks and submit
2948 * them for I/O.
2950 if (!mpd.io_done && mpd.next_page != mpd.first_page) {
2951 if (mpage_da_map_blocks(&mpd) == 0)
2952 mpage_da_submit_io(&mpd);
2953 mpd.io_done = 1;
2954 ret = MPAGE_DA_EXTENT_TAIL;
2956 wbc->nr_to_write -= mpd.pages_written;
2958 ext4_journal_stop(handle);
2960 if ((mpd.retval == -ENOSPC) && sbi->s_journal) {
2961 /* commit the transaction which would
2962 * free blocks released in the transaction
2963 * and try again
2965 jbd2_journal_force_commit_nested(sbi->s_journal);
2966 wbc->pages_skipped = pages_skipped;
2967 ret = 0;
2968 } else if (ret == MPAGE_DA_EXTENT_TAIL) {
2970 * got one extent now try with
2971 * rest of the pages
2973 pages_written += mpd.pages_written;
2974 wbc->pages_skipped = pages_skipped;
2975 ret = 0;
2976 io_done = 1;
2977 } else if (wbc->nr_to_write)
2979 * There is no more writeout needed
2980 * or we requested for a noblocking writeout
2981 * and we found the device congested
2983 break;
2985 if (!io_done && !cycled) {
2986 cycled = 1;
2987 index = 0;
2988 wbc->range_start = index << PAGE_CACHE_SHIFT;
2989 wbc->range_end = mapping->writeback_index - 1;
2990 goto retry;
2992 if (pages_skipped != wbc->pages_skipped)
2993 printk(KERN_EMERG "This should not happen leaving %s "
2994 "with nr_to_write = %ld ret = %d\n",
2995 __func__, wbc->nr_to_write, ret);
2997 /* Update index */
2998 index += pages_written;
2999 wbc->range_cyclic = range_cyclic;
3000 if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
3002 * set the writeback_index so that range_cyclic
3003 * mode will write it back later
3005 mapping->writeback_index = index;
3007 out_writepages:
3008 if (!no_nrwrite_index_update)
3009 wbc->no_nrwrite_index_update = 0;
3010 if (wbc->nr_to_write > nr_to_writebump)
3011 wbc->nr_to_write -= nr_to_writebump;
3012 wbc->range_start = range_start;
3013 trace_ext4_da_writepages_result(inode, wbc, ret, pages_written);
3014 return ret;
3017 #define FALL_BACK_TO_NONDELALLOC 1
3018 static int ext4_nonda_switch(struct super_block *sb)
3020 s64 free_blocks, dirty_blocks;
3021 struct ext4_sb_info *sbi = EXT4_SB(sb);
3024 * switch to non delalloc mode if we are running low
3025 * on free block. The free block accounting via percpu
3026 * counters can get slightly wrong with percpu_counter_batch getting
3027 * accumulated on each CPU without updating global counters
3028 * Delalloc need an accurate free block accounting. So switch
3029 * to non delalloc when we are near to error range.
3031 free_blocks = percpu_counter_read_positive(&sbi->s_freeblocks_counter);
3032 dirty_blocks = percpu_counter_read_positive(&sbi->s_dirtyblocks_counter);
3033 if (2 * free_blocks < 3 * dirty_blocks ||
3034 free_blocks < (dirty_blocks + EXT4_FREEBLOCKS_WATERMARK)) {
3036 * free block count is less that 150% of dirty blocks
3037 * or free blocks is less that watermark
3039 return 1;
3041 return 0;
3044 static int ext4_da_write_begin(struct file *file, struct address_space *mapping,
3045 loff_t pos, unsigned len, unsigned flags,
3046 struct page **pagep, void **fsdata)
3048 int ret, retries = 0;
3049 struct page *page;
3050 pgoff_t index;
3051 unsigned from, to;
3052 struct inode *inode = mapping->host;
3053 handle_t *handle;
3055 index = pos >> PAGE_CACHE_SHIFT;
3056 from = pos & (PAGE_CACHE_SIZE - 1);
3057 to = from + len;
3059 if (ext4_nonda_switch(inode->i_sb)) {
3060 *fsdata = (void *)FALL_BACK_TO_NONDELALLOC;
3061 return ext4_write_begin(file, mapping, pos,
3062 len, flags, pagep, fsdata);
3064 *fsdata = (void *)0;
3065 trace_ext4_da_write_begin(inode, pos, len, flags);
3066 retry:
3068 * With delayed allocation, we don't log the i_disksize update
3069 * if there is delayed block allocation. But we still need
3070 * to journalling the i_disksize update if writes to the end
3071 * of file which has an already mapped buffer.
3073 handle = ext4_journal_start(inode, 1);
3074 if (IS_ERR(handle)) {
3075 ret = PTR_ERR(handle);
3076 goto out;
3078 /* We cannot recurse into the filesystem as the transaction is already
3079 * started */
3080 flags |= AOP_FLAG_NOFS;
3082 page = grab_cache_page_write_begin(mapping, index, flags);
3083 if (!page) {
3084 ext4_journal_stop(handle);
3085 ret = -ENOMEM;
3086 goto out;
3088 *pagep = page;
3090 ret = block_write_begin(file, mapping, pos, len, flags, pagep, fsdata,
3091 ext4_da_get_block_prep);
3092 if (ret < 0) {
3093 unlock_page(page);
3094 ext4_journal_stop(handle);
3095 page_cache_release(page);
3097 * block_write_begin may have instantiated a few blocks
3098 * outside i_size. Trim these off again. Don't need
3099 * i_size_read because we hold i_mutex.
3101 if (pos + len > inode->i_size)
3102 ext4_truncate_failed_write(inode);
3105 if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
3106 goto retry;
3107 out:
3108 return ret;
3112 * Check if we should update i_disksize
3113 * when write to the end of file but not require block allocation
3115 static int ext4_da_should_update_i_disksize(struct page *page,
3116 unsigned long offset)
3118 struct buffer_head *bh;
3119 struct inode *inode = page->mapping->host;
3120 unsigned int idx;
3121 int i;
3123 bh = page_buffers(page);
3124 idx = offset >> inode->i_blkbits;
3126 for (i = 0; i < idx; i++)
3127 bh = bh->b_this_page;
3129 if (!buffer_mapped(bh) || (buffer_delay(bh)) || buffer_unwritten(bh))
3130 return 0;
3131 return 1;
3134 static int ext4_da_write_end(struct file *file,
3135 struct address_space *mapping,
3136 loff_t pos, unsigned len, unsigned copied,
3137 struct page *page, void *fsdata)
3139 struct inode *inode = mapping->host;
3140 int ret = 0, ret2;
3141 handle_t *handle = ext4_journal_current_handle();
3142 loff_t new_i_size;
3143 unsigned long start, end;
3144 int write_mode = (int)(unsigned long)fsdata;
3146 if (write_mode == FALL_BACK_TO_NONDELALLOC) {
3147 if (ext4_should_order_data(inode)) {
3148 return ext4_ordered_write_end(file, mapping, pos,
3149 len, copied, page, fsdata);
3150 } else if (ext4_should_writeback_data(inode)) {
3151 return ext4_writeback_write_end(file, mapping, pos,
3152 len, copied, page, fsdata);
3153 } else {
3154 BUG();
3158 trace_ext4_da_write_end(inode, pos, len, copied);
3159 start = pos & (PAGE_CACHE_SIZE - 1);
3160 end = start + copied - 1;
3163 * generic_write_end() will run mark_inode_dirty() if i_size
3164 * changes. So let's piggyback the i_disksize mark_inode_dirty
3165 * into that.
3168 new_i_size = pos + copied;
3169 if (new_i_size > EXT4_I(inode)->i_disksize) {
3170 if (ext4_da_should_update_i_disksize(page, end)) {
3171 down_write(&EXT4_I(inode)->i_data_sem);
3172 if (new_i_size > EXT4_I(inode)->i_disksize) {
3174 * Updating i_disksize when extending file
3175 * without needing block allocation
3177 if (ext4_should_order_data(inode))
3178 ret = ext4_jbd2_file_inode(handle,
3179 inode);
3181 EXT4_I(inode)->i_disksize = new_i_size;
3183 up_write(&EXT4_I(inode)->i_data_sem);
3184 /* We need to mark inode dirty even if
3185 * new_i_size is less that inode->i_size
3186 * bu greater than i_disksize.(hint delalloc)
3188 ext4_mark_inode_dirty(handle, inode);
3191 ret2 = generic_write_end(file, mapping, pos, len, copied,
3192 page, fsdata);
3193 copied = ret2;
3194 if (ret2 < 0)
3195 ret = ret2;
3196 ret2 = ext4_journal_stop(handle);
3197 if (!ret)
3198 ret = ret2;
3200 return ret ? ret : copied;
3203 static void ext4_da_invalidatepage(struct page *page, unsigned long offset)
3206 * Drop reserved blocks
3208 BUG_ON(!PageLocked(page));
3209 if (!page_has_buffers(page))
3210 goto out;
3212 ext4_da_page_release_reservation(page, offset);
3214 out:
3215 ext4_invalidatepage(page, offset);
3217 return;
3221 * Force all delayed allocation blocks to be allocated for a given inode.
3223 int ext4_alloc_da_blocks(struct inode *inode)
3225 if (!EXT4_I(inode)->i_reserved_data_blocks &&
3226 !EXT4_I(inode)->i_reserved_meta_blocks)
3227 return 0;
3230 * We do something simple for now. The filemap_flush() will
3231 * also start triggering a write of the data blocks, which is
3232 * not strictly speaking necessary (and for users of
3233 * laptop_mode, not even desirable). However, to do otherwise
3234 * would require replicating code paths in:
3236 * ext4_da_writepages() ->
3237 * write_cache_pages() ---> (via passed in callback function)
3238 * __mpage_da_writepage() -->
3239 * mpage_add_bh_to_extent()
3240 * mpage_da_map_blocks()
3242 * The problem is that write_cache_pages(), located in
3243 * mm/page-writeback.c, marks pages clean in preparation for
3244 * doing I/O, which is not desirable if we're not planning on
3245 * doing I/O at all.
3247 * We could call write_cache_pages(), and then redirty all of
3248 * the pages by calling redirty_page_for_writeback() but that
3249 * would be ugly in the extreme. So instead we would need to
3250 * replicate parts of the code in the above functions,
3251 * simplifying them becuase we wouldn't actually intend to
3252 * write out the pages, but rather only collect contiguous
3253 * logical block extents, call the multi-block allocator, and
3254 * then update the buffer heads with the block allocations.
3256 * For now, though, we'll cheat by calling filemap_flush(),
3257 * which will map the blocks, and start the I/O, but not
3258 * actually wait for the I/O to complete.
3260 return filemap_flush(inode->i_mapping);
3264 * bmap() is special. It gets used by applications such as lilo and by
3265 * the swapper to find the on-disk block of a specific piece of data.
3267 * Naturally, this is dangerous if the block concerned is still in the
3268 * journal. If somebody makes a swapfile on an ext4 data-journaling
3269 * filesystem and enables swap, then they may get a nasty shock when the
3270 * data getting swapped to that swapfile suddenly gets overwritten by
3271 * the original zero's written out previously to the journal and
3272 * awaiting writeback in the kernel's buffer cache.
3274 * So, if we see any bmap calls here on a modified, data-journaled file,
3275 * take extra steps to flush any blocks which might be in the cache.
3277 static sector_t ext4_bmap(struct address_space *mapping, sector_t block)
3279 struct inode *inode = mapping->host;
3280 journal_t *journal;
3281 int err;
3283 if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY) &&
3284 test_opt(inode->i_sb, DELALLOC)) {
3286 * With delalloc we want to sync the file
3287 * so that we can make sure we allocate
3288 * blocks for file
3290 filemap_write_and_wait(mapping);
3293 if (EXT4_JOURNAL(inode) && EXT4_I(inode)->i_state & EXT4_STATE_JDATA) {
3295 * This is a REALLY heavyweight approach, but the use of
3296 * bmap on dirty files is expected to be extremely rare:
3297 * only if we run lilo or swapon on a freshly made file
3298 * do we expect this to happen.
3300 * (bmap requires CAP_SYS_RAWIO so this does not
3301 * represent an unprivileged user DOS attack --- we'd be
3302 * in trouble if mortal users could trigger this path at
3303 * will.)
3305 * NB. EXT4_STATE_JDATA is not set on files other than
3306 * regular files. If somebody wants to bmap a directory
3307 * or symlink and gets confused because the buffer
3308 * hasn't yet been flushed to disk, they deserve
3309 * everything they get.
3312 EXT4_I(inode)->i_state &= ~EXT4_STATE_JDATA;
3313 journal = EXT4_JOURNAL(inode);
3314 jbd2_journal_lock_updates(journal);
3315 err = jbd2_journal_flush(journal);
3316 jbd2_journal_unlock_updates(journal);
3318 if (err)
3319 return 0;
3322 return generic_block_bmap(mapping, block, ext4_get_block);
3325 static int ext4_readpage(struct file *file, struct page *page)
3327 return mpage_readpage(page, ext4_get_block);
3330 static int
3331 ext4_readpages(struct file *file, struct address_space *mapping,
3332 struct list_head *pages, unsigned nr_pages)
3334 return mpage_readpages(mapping, pages, nr_pages, ext4_get_block);
3337 static void ext4_invalidatepage(struct page *page, unsigned long offset)
3339 journal_t *journal = EXT4_JOURNAL(page->mapping->host);
3342 * If it's a full truncate we just forget about the pending dirtying
3344 if (offset == 0)
3345 ClearPageChecked(page);
3347 if (journal)
3348 jbd2_journal_invalidatepage(journal, page, offset);
3349 else
3350 block_invalidatepage(page, offset);
3353 static int ext4_releasepage(struct page *page, gfp_t wait)
3355 journal_t *journal = EXT4_JOURNAL(page->mapping->host);
3357 WARN_ON(PageChecked(page));
3358 if (!page_has_buffers(page))
3359 return 0;
3360 if (journal)
3361 return jbd2_journal_try_to_free_buffers(journal, page, wait);
3362 else
3363 return try_to_free_buffers(page);
3367 * O_DIRECT for ext3 (or indirect map) based files
3369 * If the O_DIRECT write will extend the file then add this inode to the
3370 * orphan list. So recovery will truncate it back to the original size
3371 * if the machine crashes during the write.
3373 * If the O_DIRECT write is intantiating holes inside i_size and the machine
3374 * crashes then stale disk data _may_ be exposed inside the file. But current
3375 * VFS code falls back into buffered path in that case so we are safe.
3377 static ssize_t ext4_ind_direct_IO(int rw, struct kiocb *iocb,
3378 const struct iovec *iov, loff_t offset,
3379 unsigned long nr_segs)
3381 struct file *file = iocb->ki_filp;
3382 struct inode *inode = file->f_mapping->host;
3383 struct ext4_inode_info *ei = EXT4_I(inode);
3384 handle_t *handle;
3385 ssize_t ret;
3386 int orphan = 0;
3387 size_t count = iov_length(iov, nr_segs);
3388 int retries = 0;
3390 if (rw == WRITE) {
3391 loff_t final_size = offset + count;
3393 if (final_size > inode->i_size) {
3394 /* Credits for sb + inode write */
3395 handle = ext4_journal_start(inode, 2);
3396 if (IS_ERR(handle)) {
3397 ret = PTR_ERR(handle);
3398 goto out;
3400 ret = ext4_orphan_add(handle, inode);
3401 if (ret) {
3402 ext4_journal_stop(handle);
3403 goto out;
3405 orphan = 1;
3406 ei->i_disksize = inode->i_size;
3407 ext4_journal_stop(handle);
3411 retry:
3412 ret = blockdev_direct_IO(rw, iocb, inode, inode->i_sb->s_bdev, iov,
3413 offset, nr_segs,
3414 ext4_get_block, NULL);
3415 if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
3416 goto retry;
3418 if (orphan) {
3419 int err;
3421 /* Credits for sb + inode write */
3422 handle = ext4_journal_start(inode, 2);
3423 if (IS_ERR(handle)) {
3424 /* This is really bad luck. We've written the data
3425 * but cannot extend i_size. Bail out and pretend
3426 * the write failed... */
3427 ret = PTR_ERR(handle);
3428 goto out;
3430 if (inode->i_nlink)
3431 ext4_orphan_del(handle, inode);
3432 if (ret > 0) {
3433 loff_t end = offset + ret;
3434 if (end > inode->i_size) {
3435 ei->i_disksize = end;
3436 i_size_write(inode, end);
3438 * We're going to return a positive `ret'
3439 * here due to non-zero-length I/O, so there's
3440 * no way of reporting error returns from
3441 * ext4_mark_inode_dirty() to userspace. So
3442 * ignore it.
3444 ext4_mark_inode_dirty(handle, inode);
3447 err = ext4_journal_stop(handle);
3448 if (ret == 0)
3449 ret = err;
3451 out:
3452 return ret;
3455 static int ext4_get_block_dio_write(struct inode *inode, sector_t iblock,
3456 struct buffer_head *bh_result, int create)
3458 handle_t *handle = NULL;
3459 int ret = 0;
3460 unsigned max_blocks = bh_result->b_size >> inode->i_blkbits;
3461 int dio_credits;
3463 ext4_debug("ext4_get_block_dio_write: inode %lu, create flag %d\n",
3464 inode->i_ino, create);
3466 * DIO VFS code passes create = 0 flag for write to
3467 * the middle of file. It does this to avoid block
3468 * allocation for holes, to prevent expose stale data
3469 * out when there is parallel buffered read (which does
3470 * not hold the i_mutex lock) while direct IO write has
3471 * not completed. DIO request on holes finally falls back
3472 * to buffered IO for this reason.
3474 * For ext4 extent based file, since we support fallocate,
3475 * new allocated extent as uninitialized, for holes, we
3476 * could fallocate blocks for holes, thus parallel
3477 * buffered IO read will zero out the page when read on
3478 * a hole while parallel DIO write to the hole has not completed.
3480 * when we come here, we know it's a direct IO write to
3481 * to the middle of file (<i_size)
3482 * so it's safe to override the create flag from VFS.
3484 create = EXT4_GET_BLOCKS_DIO_CREATE_EXT;
3486 if (max_blocks > DIO_MAX_BLOCKS)
3487 max_blocks = DIO_MAX_BLOCKS;
3488 dio_credits = ext4_chunk_trans_blocks(inode, max_blocks);
3489 handle = ext4_journal_start(inode, dio_credits);
3490 if (IS_ERR(handle)) {
3491 ret = PTR_ERR(handle);
3492 goto out;
3494 ret = ext4_get_blocks(handle, inode, iblock, max_blocks, bh_result,
3495 create);
3496 if (ret > 0) {
3497 bh_result->b_size = (ret << inode->i_blkbits);
3498 ret = 0;
3500 ext4_journal_stop(handle);
3501 out:
3502 return ret;
3505 static void ext4_free_io_end(ext4_io_end_t *io)
3507 BUG_ON(!io);
3508 iput(io->inode);
3509 kfree(io);
3511 static void dump_aio_dio_list(struct inode * inode)
3513 #ifdef EXT4_DEBUG
3514 struct list_head *cur, *before, *after;
3515 ext4_io_end_t *io, *io0, *io1;
3517 if (list_empty(&EXT4_I(inode)->i_aio_dio_complete_list)){
3518 ext4_debug("inode %lu aio dio list is empty\n", inode->i_ino);
3519 return;
3522 ext4_debug("Dump inode %lu aio_dio_completed_IO list \n", inode->i_ino);
3523 list_for_each_entry(io, &EXT4_I(inode)->i_aio_dio_complete_list, list){
3524 cur = &io->list;
3525 before = cur->prev;
3526 io0 = container_of(before, ext4_io_end_t, list);
3527 after = cur->next;
3528 io1 = container_of(after, ext4_io_end_t, list);
3530 ext4_debug("io 0x%p from inode %lu,prev 0x%p,next 0x%p\n",
3531 io, inode->i_ino, io0, io1);
3533 #endif
3537 * check a range of space and convert unwritten extents to written.
3539 static int ext4_end_aio_dio_nolock(ext4_io_end_t *io)
3541 struct inode *inode = io->inode;
3542 loff_t offset = io->offset;
3543 size_t size = io->size;
3544 int ret = 0;
3546 ext4_debug("end_aio_dio_onlock: io 0x%p from inode %lu,list->next 0x%p,"
3547 "list->prev 0x%p\n",
3548 io, inode->i_ino, io->list.next, io->list.prev);
3550 if (list_empty(&io->list))
3551 return ret;
3553 if (io->flag != DIO_AIO_UNWRITTEN)
3554 return ret;
3556 if (offset + size <= i_size_read(inode))
3557 ret = ext4_convert_unwritten_extents(inode, offset, size);
3559 if (ret < 0) {
3560 printk(KERN_EMERG "%s: failed to convert unwritten"
3561 "extents to written extents, error is %d"
3562 " io is still on inode %lu aio dio list\n",
3563 __func__, ret, inode->i_ino);
3564 return ret;
3567 /* clear the DIO AIO unwritten flag */
3568 io->flag = 0;
3569 return ret;
3572 * work on completed aio dio IO, to convert unwritten extents to extents
3574 static void ext4_end_aio_dio_work(struct work_struct *work)
3576 ext4_io_end_t *io = container_of(work, ext4_io_end_t, work);
3577 struct inode *inode = io->inode;
3578 int ret = 0;
3580 mutex_lock(&inode->i_mutex);
3581 ret = ext4_end_aio_dio_nolock(io);
3582 if (ret >= 0) {
3583 if (!list_empty(&io->list))
3584 list_del_init(&io->list);
3585 ext4_free_io_end(io);
3587 mutex_unlock(&inode->i_mutex);
3590 * This function is called from ext4_sync_file().
3592 * When AIO DIO IO is completed, the work to convert unwritten
3593 * extents to written is queued on workqueue but may not get immediately
3594 * scheduled. When fsync is called, we need to ensure the
3595 * conversion is complete before fsync returns.
3596 * The inode keeps track of a list of completed AIO from DIO path
3597 * that might needs to do the conversion. This function walks through
3598 * the list and convert the related unwritten extents to written.
3600 int flush_aio_dio_completed_IO(struct inode *inode)
3602 ext4_io_end_t *io;
3603 int ret = 0;
3604 int ret2 = 0;
3606 if (list_empty(&EXT4_I(inode)->i_aio_dio_complete_list))
3607 return ret;
3609 dump_aio_dio_list(inode);
3610 while (!list_empty(&EXT4_I(inode)->i_aio_dio_complete_list)){
3611 io = list_entry(EXT4_I(inode)->i_aio_dio_complete_list.next,
3612 ext4_io_end_t, list);
3614 * Calling ext4_end_aio_dio_nolock() to convert completed
3615 * IO to written.
3617 * When ext4_sync_file() is called, run_queue() may already
3618 * about to flush the work corresponding to this io structure.
3619 * It will be upset if it founds the io structure related
3620 * to the work-to-be schedule is freed.
3622 * Thus we need to keep the io structure still valid here after
3623 * convertion finished. The io structure has a flag to
3624 * avoid double converting from both fsync and background work
3625 * queue work.
3627 ret = ext4_end_aio_dio_nolock(io);
3628 if (ret < 0)
3629 ret2 = ret;
3630 else
3631 list_del_init(&io->list);
3633 return (ret2 < 0) ? ret2 : 0;
3636 static ext4_io_end_t *ext4_init_io_end (struct inode *inode)
3638 ext4_io_end_t *io = NULL;
3640 io = kmalloc(sizeof(*io), GFP_NOFS);
3642 if (io) {
3643 igrab(inode);
3644 io->inode = inode;
3645 io->flag = 0;
3646 io->offset = 0;
3647 io->size = 0;
3648 io->error = 0;
3649 INIT_WORK(&io->work, ext4_end_aio_dio_work);
3650 INIT_LIST_HEAD(&io->list);
3653 return io;
3656 static void ext4_end_io_dio(struct kiocb *iocb, loff_t offset,
3657 ssize_t size, void *private)
3659 ext4_io_end_t *io_end = iocb->private;
3660 struct workqueue_struct *wq;
3662 /* if not async direct IO or dio with 0 bytes write, just return */
3663 if (!io_end || !size)
3664 return;
3666 ext_debug("ext4_end_io_dio(): io_end 0x%p"
3667 "for inode %lu, iocb 0x%p, offset %llu, size %llu\n",
3668 iocb->private, io_end->inode->i_ino, iocb, offset,
3669 size);
3671 /* if not aio dio with unwritten extents, just free io and return */
3672 if (io_end->flag != DIO_AIO_UNWRITTEN){
3673 ext4_free_io_end(io_end);
3674 iocb->private = NULL;
3675 return;
3678 io_end->offset = offset;
3679 io_end->size = size;
3680 wq = EXT4_SB(io_end->inode->i_sb)->dio_unwritten_wq;
3682 /* queue the work to convert unwritten extents to written */
3683 queue_work(wq, &io_end->work);
3685 /* Add the io_end to per-inode completed aio dio list*/
3686 list_add_tail(&io_end->list,
3687 &EXT4_I(io_end->inode)->i_aio_dio_complete_list);
3688 iocb->private = NULL;
3691 * For ext4 extent files, ext4 will do direct-io write to holes,
3692 * preallocated extents, and those write extend the file, no need to
3693 * fall back to buffered IO.
3695 * For holes, we fallocate those blocks, mark them as unintialized
3696 * If those blocks were preallocated, we mark sure they are splited, but
3697 * still keep the range to write as unintialized.
3699 * The unwrritten extents will be converted to written when DIO is completed.
3700 * For async direct IO, since the IO may still pending when return, we
3701 * set up an end_io call back function, which will do the convertion
3702 * when async direct IO completed.
3704 * If the O_DIRECT write will extend the file then add this inode to the
3705 * orphan list. So recovery will truncate it back to the original size
3706 * if the machine crashes during the write.
3709 static ssize_t ext4_ext_direct_IO(int rw, struct kiocb *iocb,
3710 const struct iovec *iov, loff_t offset,
3711 unsigned long nr_segs)
3713 struct file *file = iocb->ki_filp;
3714 struct inode *inode = file->f_mapping->host;
3715 ssize_t ret;
3716 size_t count = iov_length(iov, nr_segs);
3718 loff_t final_size = offset + count;
3719 if (rw == WRITE && final_size <= inode->i_size) {
3721 * We could direct write to holes and fallocate.
3723 * Allocated blocks to fill the hole are marked as uninitialized
3724 * to prevent paralel buffered read to expose the stale data
3725 * before DIO complete the data IO.
3727 * As to previously fallocated extents, ext4 get_block
3728 * will just simply mark the buffer mapped but still
3729 * keep the extents uninitialized.
3731 * for non AIO case, we will convert those unwritten extents
3732 * to written after return back from blockdev_direct_IO.
3734 * for async DIO, the conversion needs to be defered when
3735 * the IO is completed. The ext4 end_io callback function
3736 * will be called to take care of the conversion work.
3737 * Here for async case, we allocate an io_end structure to
3738 * hook to the iocb.
3740 iocb->private = NULL;
3741 EXT4_I(inode)->cur_aio_dio = NULL;
3742 if (!is_sync_kiocb(iocb)) {
3743 iocb->private = ext4_init_io_end(inode);
3744 if (!iocb->private)
3745 return -ENOMEM;
3747 * we save the io structure for current async
3748 * direct IO, so that later ext4_get_blocks()
3749 * could flag the io structure whether there
3750 * is a unwritten extents needs to be converted
3751 * when IO is completed.
3753 EXT4_I(inode)->cur_aio_dio = iocb->private;
3756 ret = blockdev_direct_IO(rw, iocb, inode,
3757 inode->i_sb->s_bdev, iov,
3758 offset, nr_segs,
3759 ext4_get_block_dio_write,
3760 ext4_end_io_dio);
3761 if (iocb->private)
3762 EXT4_I(inode)->cur_aio_dio = NULL;
3764 * The io_end structure takes a reference to the inode,
3765 * that structure needs to be destroyed and the
3766 * reference to the inode need to be dropped, when IO is
3767 * complete, even with 0 byte write, or failed.
3769 * In the successful AIO DIO case, the io_end structure will be
3770 * desctroyed and the reference to the inode will be dropped
3771 * after the end_io call back function is called.
3773 * In the case there is 0 byte write, or error case, since
3774 * VFS direct IO won't invoke the end_io call back function,
3775 * we need to free the end_io structure here.
3777 if (ret != -EIOCBQUEUED && ret <= 0 && iocb->private) {
3778 ext4_free_io_end(iocb->private);
3779 iocb->private = NULL;
3780 } else if (ret > 0 && (EXT4_I(inode)->i_state &
3781 EXT4_STATE_DIO_UNWRITTEN)) {
3782 int err;
3784 * for non AIO case, since the IO is already
3785 * completed, we could do the convertion right here
3787 err = ext4_convert_unwritten_extents(inode,
3788 offset, ret);
3789 if (err < 0)
3790 ret = err;
3791 EXT4_I(inode)->i_state &= ~EXT4_STATE_DIO_UNWRITTEN;
3793 return ret;
3796 /* for write the the end of file case, we fall back to old way */
3797 return ext4_ind_direct_IO(rw, iocb, iov, offset, nr_segs);
3800 static ssize_t ext4_direct_IO(int rw, struct kiocb *iocb,
3801 const struct iovec *iov, loff_t offset,
3802 unsigned long nr_segs)
3804 struct file *file = iocb->ki_filp;
3805 struct inode *inode = file->f_mapping->host;
3807 if (EXT4_I(inode)->i_flags & EXT4_EXTENTS_FL)
3808 return ext4_ext_direct_IO(rw, iocb, iov, offset, nr_segs);
3810 return ext4_ind_direct_IO(rw, iocb, iov, offset, nr_segs);
3814 * Pages can be marked dirty completely asynchronously from ext4's journalling
3815 * activity. By filemap_sync_pte(), try_to_unmap_one(), etc. We cannot do
3816 * much here because ->set_page_dirty is called under VFS locks. The page is
3817 * not necessarily locked.
3819 * We cannot just dirty the page and leave attached buffers clean, because the
3820 * buffers' dirty state is "definitive". We cannot just set the buffers dirty
3821 * or jbddirty because all the journalling code will explode.
3823 * So what we do is to mark the page "pending dirty" and next time writepage
3824 * is called, propagate that into the buffers appropriately.
3826 static int ext4_journalled_set_page_dirty(struct page *page)
3828 SetPageChecked(page);
3829 return __set_page_dirty_nobuffers(page);
3832 static const struct address_space_operations ext4_ordered_aops = {
3833 .readpage = ext4_readpage,
3834 .readpages = ext4_readpages,
3835 .writepage = ext4_writepage,
3836 .sync_page = block_sync_page,
3837 .write_begin = ext4_write_begin,
3838 .write_end = ext4_ordered_write_end,
3839 .bmap = ext4_bmap,
3840 .invalidatepage = ext4_invalidatepage,
3841 .releasepage = ext4_releasepage,
3842 .direct_IO = ext4_direct_IO,
3843 .migratepage = buffer_migrate_page,
3844 .is_partially_uptodate = block_is_partially_uptodate,
3847 static const struct address_space_operations ext4_writeback_aops = {
3848 .readpage = ext4_readpage,
3849 .readpages = ext4_readpages,
3850 .writepage = ext4_writepage,
3851 .sync_page = block_sync_page,
3852 .write_begin = ext4_write_begin,
3853 .write_end = ext4_writeback_write_end,
3854 .bmap = ext4_bmap,
3855 .invalidatepage = ext4_invalidatepage,
3856 .releasepage = ext4_releasepage,
3857 .direct_IO = ext4_direct_IO,
3858 .migratepage = buffer_migrate_page,
3859 .is_partially_uptodate = block_is_partially_uptodate,
3862 static const struct address_space_operations ext4_journalled_aops = {
3863 .readpage = ext4_readpage,
3864 .readpages = ext4_readpages,
3865 .writepage = ext4_writepage,
3866 .sync_page = block_sync_page,
3867 .write_begin = ext4_write_begin,
3868 .write_end = ext4_journalled_write_end,
3869 .set_page_dirty = ext4_journalled_set_page_dirty,
3870 .bmap = ext4_bmap,
3871 .invalidatepage = ext4_invalidatepage,
3872 .releasepage = ext4_releasepage,
3873 .is_partially_uptodate = block_is_partially_uptodate,
3876 static const struct address_space_operations ext4_da_aops = {
3877 .readpage = ext4_readpage,
3878 .readpages = ext4_readpages,
3879 .writepage = ext4_writepage,
3880 .writepages = ext4_da_writepages,
3881 .sync_page = block_sync_page,
3882 .write_begin = ext4_da_write_begin,
3883 .write_end = ext4_da_write_end,
3884 .bmap = ext4_bmap,
3885 .invalidatepage = ext4_da_invalidatepage,
3886 .releasepage = ext4_releasepage,
3887 .direct_IO = ext4_direct_IO,
3888 .migratepage = buffer_migrate_page,
3889 .is_partially_uptodate = block_is_partially_uptodate,
3892 void ext4_set_aops(struct inode *inode)
3894 if (ext4_should_order_data(inode) &&
3895 test_opt(inode->i_sb, DELALLOC))
3896 inode->i_mapping->a_ops = &ext4_da_aops;
3897 else if (ext4_should_order_data(inode))
3898 inode->i_mapping->a_ops = &ext4_ordered_aops;
3899 else if (ext4_should_writeback_data(inode) &&
3900 test_opt(inode->i_sb, DELALLOC))
3901 inode->i_mapping->a_ops = &ext4_da_aops;
3902 else if (ext4_should_writeback_data(inode))
3903 inode->i_mapping->a_ops = &ext4_writeback_aops;
3904 else
3905 inode->i_mapping->a_ops = &ext4_journalled_aops;
3909 * ext4_block_truncate_page() zeroes out a mapping from file offset `from'
3910 * up to the end of the block which corresponds to `from'.
3911 * This required during truncate. We need to physically zero the tail end
3912 * of that block so it doesn't yield old data if the file is later grown.
3914 int ext4_block_truncate_page(handle_t *handle,
3915 struct address_space *mapping, loff_t from)
3917 ext4_fsblk_t index = from >> PAGE_CACHE_SHIFT;
3918 unsigned offset = from & (PAGE_CACHE_SIZE-1);
3919 unsigned blocksize, length, pos;
3920 ext4_lblk_t iblock;
3921 struct inode *inode = mapping->host;
3922 struct buffer_head *bh;
3923 struct page *page;
3924 int err = 0;
3926 page = find_or_create_page(mapping, from >> PAGE_CACHE_SHIFT,
3927 mapping_gfp_mask(mapping) & ~__GFP_FS);
3928 if (!page)
3929 return -EINVAL;
3931 blocksize = inode->i_sb->s_blocksize;
3932 length = blocksize - (offset & (blocksize - 1));
3933 iblock = index << (PAGE_CACHE_SHIFT - inode->i_sb->s_blocksize_bits);
3936 * For "nobh" option, we can only work if we don't need to
3937 * read-in the page - otherwise we create buffers to do the IO.
3939 if (!page_has_buffers(page) && test_opt(inode->i_sb, NOBH) &&
3940 ext4_should_writeback_data(inode) && PageUptodate(page)) {
3941 zero_user(page, offset, length);
3942 set_page_dirty(page);
3943 goto unlock;
3946 if (!page_has_buffers(page))
3947 create_empty_buffers(page, blocksize, 0);
3949 /* Find the buffer that contains "offset" */
3950 bh = page_buffers(page);
3951 pos = blocksize;
3952 while (offset >= pos) {
3953 bh = bh->b_this_page;
3954 iblock++;
3955 pos += blocksize;
3958 err = 0;
3959 if (buffer_freed(bh)) {
3960 BUFFER_TRACE(bh, "freed: skip");
3961 goto unlock;
3964 if (!buffer_mapped(bh)) {
3965 BUFFER_TRACE(bh, "unmapped");
3966 ext4_get_block(inode, iblock, bh, 0);
3967 /* unmapped? It's a hole - nothing to do */
3968 if (!buffer_mapped(bh)) {
3969 BUFFER_TRACE(bh, "still unmapped");
3970 goto unlock;
3974 /* Ok, it's mapped. Make sure it's up-to-date */
3975 if (PageUptodate(page))
3976 set_buffer_uptodate(bh);
3978 if (!buffer_uptodate(bh)) {
3979 err = -EIO;
3980 ll_rw_block(READ, 1, &bh);
3981 wait_on_buffer(bh);
3982 /* Uhhuh. Read error. Complain and punt. */
3983 if (!buffer_uptodate(bh))
3984 goto unlock;
3987 if (ext4_should_journal_data(inode)) {
3988 BUFFER_TRACE(bh, "get write access");
3989 err = ext4_journal_get_write_access(handle, bh);
3990 if (err)
3991 goto unlock;
3994 zero_user(page, offset, length);
3996 BUFFER_TRACE(bh, "zeroed end of block");
3998 err = 0;
3999 if (ext4_should_journal_data(inode)) {
4000 err = ext4_handle_dirty_metadata(handle, inode, bh);
4001 } else {
4002 if (ext4_should_order_data(inode))
4003 err = ext4_jbd2_file_inode(handle, inode);
4004 mark_buffer_dirty(bh);
4007 unlock:
4008 unlock_page(page);
4009 page_cache_release(page);
4010 return err;
4014 * Probably it should be a library function... search for first non-zero word
4015 * or memcmp with zero_page, whatever is better for particular architecture.
4016 * Linus?
4018 static inline int all_zeroes(__le32 *p, __le32 *q)
4020 while (p < q)
4021 if (*p++)
4022 return 0;
4023 return 1;
4027 * ext4_find_shared - find the indirect blocks for partial truncation.
4028 * @inode: inode in question
4029 * @depth: depth of the affected branch
4030 * @offsets: offsets of pointers in that branch (see ext4_block_to_path)
4031 * @chain: place to store the pointers to partial indirect blocks
4032 * @top: place to the (detached) top of branch
4034 * This is a helper function used by ext4_truncate().
4036 * When we do truncate() we may have to clean the ends of several
4037 * indirect blocks but leave the blocks themselves alive. Block is
4038 * partially truncated if some data below the new i_size is refered
4039 * from it (and it is on the path to the first completely truncated
4040 * data block, indeed). We have to free the top of that path along
4041 * with everything to the right of the path. Since no allocation
4042 * past the truncation point is possible until ext4_truncate()
4043 * finishes, we may safely do the latter, but top of branch may
4044 * require special attention - pageout below the truncation point
4045 * might try to populate it.
4047 * We atomically detach the top of branch from the tree, store the
4048 * block number of its root in *@top, pointers to buffer_heads of
4049 * partially truncated blocks - in @chain[].bh and pointers to
4050 * their last elements that should not be removed - in
4051 * @chain[].p. Return value is the pointer to last filled element
4052 * of @chain.
4054 * The work left to caller to do the actual freeing of subtrees:
4055 * a) free the subtree starting from *@top
4056 * b) free the subtrees whose roots are stored in
4057 * (@chain[i].p+1 .. end of @chain[i].bh->b_data)
4058 * c) free the subtrees growing from the inode past the @chain[0].
4059 * (no partially truncated stuff there). */
4061 static Indirect *ext4_find_shared(struct inode *inode, int depth,
4062 ext4_lblk_t offsets[4], Indirect chain[4],
4063 __le32 *top)
4065 Indirect *partial, *p;
4066 int k, err;
4068 *top = 0;
4069 /* Make k index the deepest non-null offest + 1 */
4070 for (k = depth; k > 1 && !offsets[k-1]; k--)
4072 partial = ext4_get_branch(inode, k, offsets, chain, &err);
4073 /* Writer: pointers */
4074 if (!partial)
4075 partial = chain + k-1;
4077 * If the branch acquired continuation since we've looked at it -
4078 * fine, it should all survive and (new) top doesn't belong to us.
4080 if (!partial->key && *partial->p)
4081 /* Writer: end */
4082 goto no_top;
4083 for (p = partial; (p > chain) && all_zeroes((__le32 *) p->bh->b_data, p->p); p--)
4086 * OK, we've found the last block that must survive. The rest of our
4087 * branch should be detached before unlocking. However, if that rest
4088 * of branch is all ours and does not grow immediately from the inode
4089 * it's easier to cheat and just decrement partial->p.
4091 if (p == chain + k - 1 && p > chain) {
4092 p->p--;
4093 } else {
4094 *top = *p->p;
4095 /* Nope, don't do this in ext4. Must leave the tree intact */
4096 #if 0
4097 *p->p = 0;
4098 #endif
4100 /* Writer: end */
4102 while (partial > p) {
4103 brelse(partial->bh);
4104 partial--;
4106 no_top:
4107 return partial;
4111 * Zero a number of block pointers in either an inode or an indirect block.
4112 * If we restart the transaction we must again get write access to the
4113 * indirect block for further modification.
4115 * We release `count' blocks on disk, but (last - first) may be greater
4116 * than `count' because there can be holes in there.
4118 static void ext4_clear_blocks(handle_t *handle, struct inode *inode,
4119 struct buffer_head *bh,
4120 ext4_fsblk_t block_to_free,
4121 unsigned long count, __le32 *first,
4122 __le32 *last)
4124 __le32 *p;
4125 int is_metadata = S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode);
4127 if (try_to_extend_transaction(handle, inode)) {
4128 if (bh) {
4129 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
4130 ext4_handle_dirty_metadata(handle, inode, bh);
4132 ext4_mark_inode_dirty(handle, inode);
4133 ext4_truncate_restart_trans(handle, inode,
4134 blocks_for_truncate(inode));
4135 if (bh) {
4136 BUFFER_TRACE(bh, "retaking write access");
4137 ext4_journal_get_write_access(handle, bh);
4142 * Any buffers which are on the journal will be in memory. We
4143 * find them on the hash table so jbd2_journal_revoke() will
4144 * run jbd2_journal_forget() on them. We've already detached
4145 * each block from the file, so bforget() in
4146 * jbd2_journal_forget() should be safe.
4148 * AKPM: turn on bforget in jbd2_journal_forget()!!!
4150 for (p = first; p < last; p++) {
4151 u32 nr = le32_to_cpu(*p);
4152 if (nr) {
4153 struct buffer_head *tbh;
4155 *p = 0;
4156 tbh = sb_find_get_block(inode->i_sb, nr);
4157 ext4_forget(handle, is_metadata, inode, tbh, nr);
4161 ext4_free_blocks(handle, inode, block_to_free, count, is_metadata);
4165 * ext4_free_data - free a list of data blocks
4166 * @handle: handle for this transaction
4167 * @inode: inode we are dealing with
4168 * @this_bh: indirect buffer_head which contains *@first and *@last
4169 * @first: array of block numbers
4170 * @last: points immediately past the end of array
4172 * We are freeing all blocks refered from that array (numbers are stored as
4173 * little-endian 32-bit) and updating @inode->i_blocks appropriately.
4175 * We accumulate contiguous runs of blocks to free. Conveniently, if these
4176 * blocks are contiguous then releasing them at one time will only affect one
4177 * or two bitmap blocks (+ group descriptor(s) and superblock) and we won't
4178 * actually use a lot of journal space.
4180 * @this_bh will be %NULL if @first and @last point into the inode's direct
4181 * block pointers.
4183 static void ext4_free_data(handle_t *handle, struct inode *inode,
4184 struct buffer_head *this_bh,
4185 __le32 *first, __le32 *last)
4187 ext4_fsblk_t block_to_free = 0; /* Starting block # of a run */
4188 unsigned long count = 0; /* Number of blocks in the run */
4189 __le32 *block_to_free_p = NULL; /* Pointer into inode/ind
4190 corresponding to
4191 block_to_free */
4192 ext4_fsblk_t nr; /* Current block # */
4193 __le32 *p; /* Pointer into inode/ind
4194 for current block */
4195 int err;
4197 if (this_bh) { /* For indirect block */
4198 BUFFER_TRACE(this_bh, "get_write_access");
4199 err = ext4_journal_get_write_access(handle, this_bh);
4200 /* Important: if we can't update the indirect pointers
4201 * to the blocks, we can't free them. */
4202 if (err)
4203 return;
4206 for (p = first; p < last; p++) {
4207 nr = le32_to_cpu(*p);
4208 if (nr) {
4209 /* accumulate blocks to free if they're contiguous */
4210 if (count == 0) {
4211 block_to_free = nr;
4212 block_to_free_p = p;
4213 count = 1;
4214 } else if (nr == block_to_free + count) {
4215 count++;
4216 } else {
4217 ext4_clear_blocks(handle, inode, this_bh,
4218 block_to_free,
4219 count, block_to_free_p, p);
4220 block_to_free = nr;
4221 block_to_free_p = p;
4222 count = 1;
4227 if (count > 0)
4228 ext4_clear_blocks(handle, inode, this_bh, block_to_free,
4229 count, block_to_free_p, p);
4231 if (this_bh) {
4232 BUFFER_TRACE(this_bh, "call ext4_handle_dirty_metadata");
4235 * The buffer head should have an attached journal head at this
4236 * point. However, if the data is corrupted and an indirect
4237 * block pointed to itself, it would have been detached when
4238 * the block was cleared. Check for this instead of OOPSing.
4240 if ((EXT4_JOURNAL(inode) == NULL) || bh2jh(this_bh))
4241 ext4_handle_dirty_metadata(handle, inode, this_bh);
4242 else
4243 ext4_error(inode->i_sb, __func__,
4244 "circular indirect block detected, "
4245 "inode=%lu, block=%llu",
4246 inode->i_ino,
4247 (unsigned long long) this_bh->b_blocknr);
4252 * ext4_free_branches - free an array of branches
4253 * @handle: JBD handle for this transaction
4254 * @inode: inode we are dealing with
4255 * @parent_bh: the buffer_head which contains *@first and *@last
4256 * @first: array of block numbers
4257 * @last: pointer immediately past the end of array
4258 * @depth: depth of the branches to free
4260 * We are freeing all blocks refered from these branches (numbers are
4261 * stored as little-endian 32-bit) and updating @inode->i_blocks
4262 * appropriately.
4264 static void ext4_free_branches(handle_t *handle, struct inode *inode,
4265 struct buffer_head *parent_bh,
4266 __le32 *first, __le32 *last, int depth)
4268 ext4_fsblk_t nr;
4269 __le32 *p;
4271 if (ext4_handle_is_aborted(handle))
4272 return;
4274 if (depth--) {
4275 struct buffer_head *bh;
4276 int addr_per_block = EXT4_ADDR_PER_BLOCK(inode->i_sb);
4277 p = last;
4278 while (--p >= first) {
4279 nr = le32_to_cpu(*p);
4280 if (!nr)
4281 continue; /* A hole */
4283 /* Go read the buffer for the next level down */
4284 bh = sb_bread(inode->i_sb, nr);
4287 * A read failure? Report error and clear slot
4288 * (should be rare).
4290 if (!bh) {
4291 ext4_error(inode->i_sb, "ext4_free_branches",
4292 "Read failure, inode=%lu, block=%llu",
4293 inode->i_ino, nr);
4294 continue;
4297 /* This zaps the entire block. Bottom up. */
4298 BUFFER_TRACE(bh, "free child branches");
4299 ext4_free_branches(handle, inode, bh,
4300 (__le32 *) bh->b_data,
4301 (__le32 *) bh->b_data + addr_per_block,
4302 depth);
4305 * We've probably journalled the indirect block several
4306 * times during the truncate. But it's no longer
4307 * needed and we now drop it from the transaction via
4308 * jbd2_journal_revoke().
4310 * That's easy if it's exclusively part of this
4311 * transaction. But if it's part of the committing
4312 * transaction then jbd2_journal_forget() will simply
4313 * brelse() it. That means that if the underlying
4314 * block is reallocated in ext4_get_block(),
4315 * unmap_underlying_metadata() will find this block
4316 * and will try to get rid of it. damn, damn.
4318 * If this block has already been committed to the
4319 * journal, a revoke record will be written. And
4320 * revoke records must be emitted *before* clearing
4321 * this block's bit in the bitmaps.
4323 ext4_forget(handle, 1, inode, bh, bh->b_blocknr);
4326 * Everything below this this pointer has been
4327 * released. Now let this top-of-subtree go.
4329 * We want the freeing of this indirect block to be
4330 * atomic in the journal with the updating of the
4331 * bitmap block which owns it. So make some room in
4332 * the journal.
4334 * We zero the parent pointer *after* freeing its
4335 * pointee in the bitmaps, so if extend_transaction()
4336 * for some reason fails to put the bitmap changes and
4337 * the release into the same transaction, recovery
4338 * will merely complain about releasing a free block,
4339 * rather than leaking blocks.
4341 if (ext4_handle_is_aborted(handle))
4342 return;
4343 if (try_to_extend_transaction(handle, inode)) {
4344 ext4_mark_inode_dirty(handle, inode);
4345 ext4_truncate_restart_trans(handle, inode,
4346 blocks_for_truncate(inode));
4349 ext4_free_blocks(handle, inode, nr, 1, 1);
4351 if (parent_bh) {
4353 * The block which we have just freed is
4354 * pointed to by an indirect block: journal it
4356 BUFFER_TRACE(parent_bh, "get_write_access");
4357 if (!ext4_journal_get_write_access(handle,
4358 parent_bh)){
4359 *p = 0;
4360 BUFFER_TRACE(parent_bh,
4361 "call ext4_handle_dirty_metadata");
4362 ext4_handle_dirty_metadata(handle,
4363 inode,
4364 parent_bh);
4368 } else {
4369 /* We have reached the bottom of the tree. */
4370 BUFFER_TRACE(parent_bh, "free data blocks");
4371 ext4_free_data(handle, inode, parent_bh, first, last);
4375 int ext4_can_truncate(struct inode *inode)
4377 if (IS_APPEND(inode) || IS_IMMUTABLE(inode))
4378 return 0;
4379 if (S_ISREG(inode->i_mode))
4380 return 1;
4381 if (S_ISDIR(inode->i_mode))
4382 return 1;
4383 if (S_ISLNK(inode->i_mode))
4384 return !ext4_inode_is_fast_symlink(inode);
4385 return 0;
4389 * ext4_truncate()
4391 * We block out ext4_get_block() block instantiations across the entire
4392 * transaction, and VFS/VM ensures that ext4_truncate() cannot run
4393 * simultaneously on behalf of the same inode.
4395 * As we work through the truncate and commmit bits of it to the journal there
4396 * is one core, guiding principle: the file's tree must always be consistent on
4397 * disk. We must be able to restart the truncate after a crash.
4399 * The file's tree may be transiently inconsistent in memory (although it
4400 * probably isn't), but whenever we close off and commit a journal transaction,
4401 * the contents of (the filesystem + the journal) must be consistent and
4402 * restartable. It's pretty simple, really: bottom up, right to left (although
4403 * left-to-right works OK too).
4405 * Note that at recovery time, journal replay occurs *before* the restart of
4406 * truncate against the orphan inode list.
4408 * The committed inode has the new, desired i_size (which is the same as
4409 * i_disksize in this case). After a crash, ext4_orphan_cleanup() will see
4410 * that this inode's truncate did not complete and it will again call
4411 * ext4_truncate() to have another go. So there will be instantiated blocks
4412 * to the right of the truncation point in a crashed ext4 filesystem. But
4413 * that's fine - as long as they are linked from the inode, the post-crash
4414 * ext4_truncate() run will find them and release them.
4416 void ext4_truncate(struct inode *inode)
4418 handle_t *handle;
4419 struct ext4_inode_info *ei = EXT4_I(inode);
4420 __le32 *i_data = ei->i_data;
4421 int addr_per_block = EXT4_ADDR_PER_BLOCK(inode->i_sb);
4422 struct address_space *mapping = inode->i_mapping;
4423 ext4_lblk_t offsets[4];
4424 Indirect chain[4];
4425 Indirect *partial;
4426 __le32 nr = 0;
4427 int n;
4428 ext4_lblk_t last_block;
4429 unsigned blocksize = inode->i_sb->s_blocksize;
4431 if (!ext4_can_truncate(inode))
4432 return;
4434 if (inode->i_size == 0 && !test_opt(inode->i_sb, NO_AUTO_DA_ALLOC))
4435 ei->i_state |= EXT4_STATE_DA_ALLOC_CLOSE;
4437 if (EXT4_I(inode)->i_flags & EXT4_EXTENTS_FL) {
4438 ext4_ext_truncate(inode);
4439 return;
4442 handle = start_transaction(inode);
4443 if (IS_ERR(handle))
4444 return; /* AKPM: return what? */
4446 last_block = (inode->i_size + blocksize-1)
4447 >> EXT4_BLOCK_SIZE_BITS(inode->i_sb);
4449 if (inode->i_size & (blocksize - 1))
4450 if (ext4_block_truncate_page(handle, mapping, inode->i_size))
4451 goto out_stop;
4453 n = ext4_block_to_path(inode, last_block, offsets, NULL);
4454 if (n == 0)
4455 goto out_stop; /* error */
4458 * OK. This truncate is going to happen. We add the inode to the
4459 * orphan list, so that if this truncate spans multiple transactions,
4460 * and we crash, we will resume the truncate when the filesystem
4461 * recovers. It also marks the inode dirty, to catch the new size.
4463 * Implication: the file must always be in a sane, consistent
4464 * truncatable state while each transaction commits.
4466 if (ext4_orphan_add(handle, inode))
4467 goto out_stop;
4470 * From here we block out all ext4_get_block() callers who want to
4471 * modify the block allocation tree.
4473 down_write(&ei->i_data_sem);
4475 ext4_discard_preallocations(inode);
4478 * The orphan list entry will now protect us from any crash which
4479 * occurs before the truncate completes, so it is now safe to propagate
4480 * the new, shorter inode size (held for now in i_size) into the
4481 * on-disk inode. We do this via i_disksize, which is the value which
4482 * ext4 *really* writes onto the disk inode.
4484 ei->i_disksize = inode->i_size;
4486 if (n == 1) { /* direct blocks */
4487 ext4_free_data(handle, inode, NULL, i_data+offsets[0],
4488 i_data + EXT4_NDIR_BLOCKS);
4489 goto do_indirects;
4492 partial = ext4_find_shared(inode, n, offsets, chain, &nr);
4493 /* Kill the top of shared branch (not detached) */
4494 if (nr) {
4495 if (partial == chain) {
4496 /* Shared branch grows from the inode */
4497 ext4_free_branches(handle, inode, NULL,
4498 &nr, &nr+1, (chain+n-1) - partial);
4499 *partial->p = 0;
4501 * We mark the inode dirty prior to restart,
4502 * and prior to stop. No need for it here.
4504 } else {
4505 /* Shared branch grows from an indirect block */
4506 BUFFER_TRACE(partial->bh, "get_write_access");
4507 ext4_free_branches(handle, inode, partial->bh,
4508 partial->p,
4509 partial->p+1, (chain+n-1) - partial);
4512 /* Clear the ends of indirect blocks on the shared branch */
4513 while (partial > chain) {
4514 ext4_free_branches(handle, inode, partial->bh, partial->p + 1,
4515 (__le32*)partial->bh->b_data+addr_per_block,
4516 (chain+n-1) - partial);
4517 BUFFER_TRACE(partial->bh, "call brelse");
4518 brelse(partial->bh);
4519 partial--;
4521 do_indirects:
4522 /* Kill the remaining (whole) subtrees */
4523 switch (offsets[0]) {
4524 default:
4525 nr = i_data[EXT4_IND_BLOCK];
4526 if (nr) {
4527 ext4_free_branches(handle, inode, NULL, &nr, &nr+1, 1);
4528 i_data[EXT4_IND_BLOCK] = 0;
4530 case EXT4_IND_BLOCK:
4531 nr = i_data[EXT4_DIND_BLOCK];
4532 if (nr) {
4533 ext4_free_branches(handle, inode, NULL, &nr, &nr+1, 2);
4534 i_data[EXT4_DIND_BLOCK] = 0;
4536 case EXT4_DIND_BLOCK:
4537 nr = i_data[EXT4_TIND_BLOCK];
4538 if (nr) {
4539 ext4_free_branches(handle, inode, NULL, &nr, &nr+1, 3);
4540 i_data[EXT4_TIND_BLOCK] = 0;
4542 case EXT4_TIND_BLOCK:
4546 up_write(&ei->i_data_sem);
4547 inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
4548 ext4_mark_inode_dirty(handle, inode);
4551 * In a multi-transaction truncate, we only make the final transaction
4552 * synchronous
4554 if (IS_SYNC(inode))
4555 ext4_handle_sync(handle);
4556 out_stop:
4558 * If this was a simple ftruncate(), and the file will remain alive
4559 * then we need to clear up the orphan record which we created above.
4560 * However, if this was a real unlink then we were called by
4561 * ext4_delete_inode(), and we allow that function to clean up the
4562 * orphan info for us.
4564 if (inode->i_nlink)
4565 ext4_orphan_del(handle, inode);
4567 ext4_journal_stop(handle);
4571 * ext4_get_inode_loc returns with an extra refcount against the inode's
4572 * underlying buffer_head on success. If 'in_mem' is true, we have all
4573 * data in memory that is needed to recreate the on-disk version of this
4574 * inode.
4576 static int __ext4_get_inode_loc(struct inode *inode,
4577 struct ext4_iloc *iloc, int in_mem)
4579 struct ext4_group_desc *gdp;
4580 struct buffer_head *bh;
4581 struct super_block *sb = inode->i_sb;
4582 ext4_fsblk_t block;
4583 int inodes_per_block, inode_offset;
4585 iloc->bh = NULL;
4586 if (!ext4_valid_inum(sb, inode->i_ino))
4587 return -EIO;
4589 iloc->block_group = (inode->i_ino - 1) / EXT4_INODES_PER_GROUP(sb);
4590 gdp = ext4_get_group_desc(sb, iloc->block_group, NULL);
4591 if (!gdp)
4592 return -EIO;
4595 * Figure out the offset within the block group inode table
4597 inodes_per_block = (EXT4_BLOCK_SIZE(sb) / EXT4_INODE_SIZE(sb));
4598 inode_offset = ((inode->i_ino - 1) %
4599 EXT4_INODES_PER_GROUP(sb));
4600 block = ext4_inode_table(sb, gdp) + (inode_offset / inodes_per_block);
4601 iloc->offset = (inode_offset % inodes_per_block) * EXT4_INODE_SIZE(sb);
4603 bh = sb_getblk(sb, block);
4604 if (!bh) {
4605 ext4_error(sb, "ext4_get_inode_loc", "unable to read "
4606 "inode block - inode=%lu, block=%llu",
4607 inode->i_ino, block);
4608 return -EIO;
4610 if (!buffer_uptodate(bh)) {
4611 lock_buffer(bh);
4614 * If the buffer has the write error flag, we have failed
4615 * to write out another inode in the same block. In this
4616 * case, we don't have to read the block because we may
4617 * read the old inode data successfully.
4619 if (buffer_write_io_error(bh) && !buffer_uptodate(bh))
4620 set_buffer_uptodate(bh);
4622 if (buffer_uptodate(bh)) {
4623 /* someone brought it uptodate while we waited */
4624 unlock_buffer(bh);
4625 goto has_buffer;
4629 * If we have all information of the inode in memory and this
4630 * is the only valid inode in the block, we need not read the
4631 * block.
4633 if (in_mem) {
4634 struct buffer_head *bitmap_bh;
4635 int i, start;
4637 start = inode_offset & ~(inodes_per_block - 1);
4639 /* Is the inode bitmap in cache? */
4640 bitmap_bh = sb_getblk(sb, ext4_inode_bitmap(sb, gdp));
4641 if (!bitmap_bh)
4642 goto make_io;
4645 * If the inode bitmap isn't in cache then the
4646 * optimisation may end up performing two reads instead
4647 * of one, so skip it.
4649 if (!buffer_uptodate(bitmap_bh)) {
4650 brelse(bitmap_bh);
4651 goto make_io;
4653 for (i = start; i < start + inodes_per_block; i++) {
4654 if (i == inode_offset)
4655 continue;
4656 if (ext4_test_bit(i, bitmap_bh->b_data))
4657 break;
4659 brelse(bitmap_bh);
4660 if (i == start + inodes_per_block) {
4661 /* all other inodes are free, so skip I/O */
4662 memset(bh->b_data, 0, bh->b_size);
4663 set_buffer_uptodate(bh);
4664 unlock_buffer(bh);
4665 goto has_buffer;
4669 make_io:
4671 * If we need to do any I/O, try to pre-readahead extra
4672 * blocks from the inode table.
4674 if (EXT4_SB(sb)->s_inode_readahead_blks) {
4675 ext4_fsblk_t b, end, table;
4676 unsigned num;
4678 table = ext4_inode_table(sb, gdp);
4679 /* s_inode_readahead_blks is always a power of 2 */
4680 b = block & ~(EXT4_SB(sb)->s_inode_readahead_blks-1);
4681 if (table > b)
4682 b = table;
4683 end = b + EXT4_SB(sb)->s_inode_readahead_blks;
4684 num = EXT4_INODES_PER_GROUP(sb);
4685 if (EXT4_HAS_RO_COMPAT_FEATURE(sb,
4686 EXT4_FEATURE_RO_COMPAT_GDT_CSUM))
4687 num -= ext4_itable_unused_count(sb, gdp);
4688 table += num / inodes_per_block;
4689 if (end > table)
4690 end = table;
4691 while (b <= end)
4692 sb_breadahead(sb, b++);
4696 * There are other valid inodes in the buffer, this inode
4697 * has in-inode xattrs, or we don't have this inode in memory.
4698 * Read the block from disk.
4700 get_bh(bh);
4701 bh->b_end_io = end_buffer_read_sync;
4702 submit_bh(READ_META, bh);
4703 wait_on_buffer(bh);
4704 if (!buffer_uptodate(bh)) {
4705 ext4_error(sb, __func__,
4706 "unable to read inode block - inode=%lu, "
4707 "block=%llu", inode->i_ino, block);
4708 brelse(bh);
4709 return -EIO;
4712 has_buffer:
4713 iloc->bh = bh;
4714 return 0;
4717 int ext4_get_inode_loc(struct inode *inode, struct ext4_iloc *iloc)
4719 /* We have all inode data except xattrs in memory here. */
4720 return __ext4_get_inode_loc(inode, iloc,
4721 !(EXT4_I(inode)->i_state & EXT4_STATE_XATTR));
4724 void ext4_set_inode_flags(struct inode *inode)
4726 unsigned int flags = EXT4_I(inode)->i_flags;
4728 inode->i_flags &= ~(S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME|S_DIRSYNC);
4729 if (flags & EXT4_SYNC_FL)
4730 inode->i_flags |= S_SYNC;
4731 if (flags & EXT4_APPEND_FL)
4732 inode->i_flags |= S_APPEND;
4733 if (flags & EXT4_IMMUTABLE_FL)
4734 inode->i_flags |= S_IMMUTABLE;
4735 if (flags & EXT4_NOATIME_FL)
4736 inode->i_flags |= S_NOATIME;
4737 if (flags & EXT4_DIRSYNC_FL)
4738 inode->i_flags |= S_DIRSYNC;
4741 /* Propagate flags from i_flags to EXT4_I(inode)->i_flags */
4742 void ext4_get_inode_flags(struct ext4_inode_info *ei)
4744 unsigned int flags = ei->vfs_inode.i_flags;
4746 ei->i_flags &= ~(EXT4_SYNC_FL|EXT4_APPEND_FL|
4747 EXT4_IMMUTABLE_FL|EXT4_NOATIME_FL|EXT4_DIRSYNC_FL);
4748 if (flags & S_SYNC)
4749 ei->i_flags |= EXT4_SYNC_FL;
4750 if (flags & S_APPEND)
4751 ei->i_flags |= EXT4_APPEND_FL;
4752 if (flags & S_IMMUTABLE)
4753 ei->i_flags |= EXT4_IMMUTABLE_FL;
4754 if (flags & S_NOATIME)
4755 ei->i_flags |= EXT4_NOATIME_FL;
4756 if (flags & S_DIRSYNC)
4757 ei->i_flags |= EXT4_DIRSYNC_FL;
4760 static blkcnt_t ext4_inode_blocks(struct ext4_inode *raw_inode,
4761 struct ext4_inode_info *ei)
4763 blkcnt_t i_blocks ;
4764 struct inode *inode = &(ei->vfs_inode);
4765 struct super_block *sb = inode->i_sb;
4767 if (EXT4_HAS_RO_COMPAT_FEATURE(sb,
4768 EXT4_FEATURE_RO_COMPAT_HUGE_FILE)) {
4769 /* we are using combined 48 bit field */
4770 i_blocks = ((u64)le16_to_cpu(raw_inode->i_blocks_high)) << 32 |
4771 le32_to_cpu(raw_inode->i_blocks_lo);
4772 if (ei->i_flags & EXT4_HUGE_FILE_FL) {
4773 /* i_blocks represent file system block size */
4774 return i_blocks << (inode->i_blkbits - 9);
4775 } else {
4776 return i_blocks;
4778 } else {
4779 return le32_to_cpu(raw_inode->i_blocks_lo);
4783 struct inode *ext4_iget(struct super_block *sb, unsigned long ino)
4785 struct ext4_iloc iloc;
4786 struct ext4_inode *raw_inode;
4787 struct ext4_inode_info *ei;
4788 struct inode *inode;
4789 journal_t *journal = EXT4_SB(sb)->s_journal;
4790 long ret;
4791 int block;
4793 inode = iget_locked(sb, ino);
4794 if (!inode)
4795 return ERR_PTR(-ENOMEM);
4796 if (!(inode->i_state & I_NEW))
4797 return inode;
4799 ei = EXT4_I(inode);
4800 iloc.bh = 0;
4802 ret = __ext4_get_inode_loc(inode, &iloc, 0);
4803 if (ret < 0)
4804 goto bad_inode;
4805 raw_inode = ext4_raw_inode(&iloc);
4806 inode->i_mode = le16_to_cpu(raw_inode->i_mode);
4807 inode->i_uid = (uid_t)le16_to_cpu(raw_inode->i_uid_low);
4808 inode->i_gid = (gid_t)le16_to_cpu(raw_inode->i_gid_low);
4809 if (!(test_opt(inode->i_sb, NO_UID32))) {
4810 inode->i_uid |= le16_to_cpu(raw_inode->i_uid_high) << 16;
4811 inode->i_gid |= le16_to_cpu(raw_inode->i_gid_high) << 16;
4813 inode->i_nlink = le16_to_cpu(raw_inode->i_links_count);
4815 ei->i_state = 0;
4816 ei->i_dir_start_lookup = 0;
4817 ei->i_dtime = le32_to_cpu(raw_inode->i_dtime);
4818 /* We now have enough fields to check if the inode was active or not.
4819 * This is needed because nfsd might try to access dead inodes
4820 * the test is that same one that e2fsck uses
4821 * NeilBrown 1999oct15
4823 if (inode->i_nlink == 0) {
4824 if (inode->i_mode == 0 ||
4825 !(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_ORPHAN_FS)) {
4826 /* this inode is deleted */
4827 ret = -ESTALE;
4828 goto bad_inode;
4830 /* The only unlinked inodes we let through here have
4831 * valid i_mode and are being read by the orphan
4832 * recovery code: that's fine, we're about to complete
4833 * the process of deleting those. */
4835 ei->i_flags = le32_to_cpu(raw_inode->i_flags);
4836 inode->i_blocks = ext4_inode_blocks(raw_inode, ei);
4837 ei->i_file_acl = le32_to_cpu(raw_inode->i_file_acl_lo);
4838 if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_64BIT))
4839 ei->i_file_acl |=
4840 ((__u64)le16_to_cpu(raw_inode->i_file_acl_high)) << 32;
4841 inode->i_size = ext4_isize(raw_inode);
4842 ei->i_disksize = inode->i_size;
4843 inode->i_generation = le32_to_cpu(raw_inode->i_generation);
4844 ei->i_block_group = iloc.block_group;
4845 ei->i_last_alloc_group = ~0;
4847 * NOTE! The in-memory inode i_data array is in little-endian order
4848 * even on big-endian machines: we do NOT byteswap the block numbers!
4850 for (block = 0; block < EXT4_N_BLOCKS; block++)
4851 ei->i_data[block] = raw_inode->i_block[block];
4852 INIT_LIST_HEAD(&ei->i_orphan);
4855 * Set transaction id's of transactions that have to be committed
4856 * to finish f[data]sync. We set them to currently running transaction
4857 * as we cannot be sure that the inode or some of its metadata isn't
4858 * part of the transaction - the inode could have been reclaimed and
4859 * now it is reread from disk.
4861 if (journal) {
4862 transaction_t *transaction;
4863 tid_t tid;
4865 spin_lock(&journal->j_state_lock);
4866 if (journal->j_running_transaction)
4867 transaction = journal->j_running_transaction;
4868 else
4869 transaction = journal->j_committing_transaction;
4870 if (transaction)
4871 tid = transaction->t_tid;
4872 else
4873 tid = journal->j_commit_sequence;
4874 spin_unlock(&journal->j_state_lock);
4875 ei->i_sync_tid = tid;
4876 ei->i_datasync_tid = tid;
4879 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4880 ei->i_extra_isize = le16_to_cpu(raw_inode->i_extra_isize);
4881 if (EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize >
4882 EXT4_INODE_SIZE(inode->i_sb)) {
4883 ret = -EIO;
4884 goto bad_inode;
4886 if (ei->i_extra_isize == 0) {
4887 /* The extra space is currently unused. Use it. */
4888 ei->i_extra_isize = sizeof(struct ext4_inode) -
4889 EXT4_GOOD_OLD_INODE_SIZE;
4890 } else {
4891 __le32 *magic = (void *)raw_inode +
4892 EXT4_GOOD_OLD_INODE_SIZE +
4893 ei->i_extra_isize;
4894 if (*magic == cpu_to_le32(EXT4_XATTR_MAGIC))
4895 ei->i_state |= EXT4_STATE_XATTR;
4897 } else
4898 ei->i_extra_isize = 0;
4900 EXT4_INODE_GET_XTIME(i_ctime, inode, raw_inode);
4901 EXT4_INODE_GET_XTIME(i_mtime, inode, raw_inode);
4902 EXT4_INODE_GET_XTIME(i_atime, inode, raw_inode);
4903 EXT4_EINODE_GET_XTIME(i_crtime, ei, raw_inode);
4905 inode->i_version = le32_to_cpu(raw_inode->i_disk_version);
4906 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4907 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
4908 inode->i_version |=
4909 (__u64)(le32_to_cpu(raw_inode->i_version_hi)) << 32;
4912 ret = 0;
4913 if (ei->i_file_acl &&
4914 !ext4_data_block_valid(EXT4_SB(sb), ei->i_file_acl, 1)) {
4915 ext4_error(sb, __func__,
4916 "bad extended attribute block %llu in inode #%lu",
4917 ei->i_file_acl, inode->i_ino);
4918 ret = -EIO;
4919 goto bad_inode;
4920 } else if (ei->i_flags & EXT4_EXTENTS_FL) {
4921 if (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
4922 (S_ISLNK(inode->i_mode) &&
4923 !ext4_inode_is_fast_symlink(inode)))
4924 /* Validate extent which is part of inode */
4925 ret = ext4_ext_check_inode(inode);
4926 } else if (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
4927 (S_ISLNK(inode->i_mode) &&
4928 !ext4_inode_is_fast_symlink(inode))) {
4929 /* Validate block references which are part of inode */
4930 ret = ext4_check_inode_blockref(inode);
4932 if (ret)
4933 goto bad_inode;
4935 if (S_ISREG(inode->i_mode)) {
4936 inode->i_op = &ext4_file_inode_operations;
4937 inode->i_fop = &ext4_file_operations;
4938 ext4_set_aops(inode);
4939 } else if (S_ISDIR(inode->i_mode)) {
4940 inode->i_op = &ext4_dir_inode_operations;
4941 inode->i_fop = &ext4_dir_operations;
4942 } else if (S_ISLNK(inode->i_mode)) {
4943 if (ext4_inode_is_fast_symlink(inode)) {
4944 inode->i_op = &ext4_fast_symlink_inode_operations;
4945 nd_terminate_link(ei->i_data, inode->i_size,
4946 sizeof(ei->i_data) - 1);
4947 } else {
4948 inode->i_op = &ext4_symlink_inode_operations;
4949 ext4_set_aops(inode);
4951 } else if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode) ||
4952 S_ISFIFO(inode->i_mode) || S_ISSOCK(inode->i_mode)) {
4953 inode->i_op = &ext4_special_inode_operations;
4954 if (raw_inode->i_block[0])
4955 init_special_inode(inode, inode->i_mode,
4956 old_decode_dev(le32_to_cpu(raw_inode->i_block[0])));
4957 else
4958 init_special_inode(inode, inode->i_mode,
4959 new_decode_dev(le32_to_cpu(raw_inode->i_block[1])));
4960 } else {
4961 ret = -EIO;
4962 ext4_error(inode->i_sb, __func__,
4963 "bogus i_mode (%o) for inode=%lu",
4964 inode->i_mode, inode->i_ino);
4965 goto bad_inode;
4967 brelse(iloc.bh);
4968 ext4_set_inode_flags(inode);
4969 unlock_new_inode(inode);
4970 return inode;
4972 bad_inode:
4973 brelse(iloc.bh);
4974 iget_failed(inode);
4975 return ERR_PTR(ret);
4978 static int ext4_inode_blocks_set(handle_t *handle,
4979 struct ext4_inode *raw_inode,
4980 struct ext4_inode_info *ei)
4982 struct inode *inode = &(ei->vfs_inode);
4983 u64 i_blocks = inode->i_blocks;
4984 struct super_block *sb = inode->i_sb;
4986 if (i_blocks <= ~0U) {
4988 * i_blocks can be represnted in a 32 bit variable
4989 * as multiple of 512 bytes
4991 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
4992 raw_inode->i_blocks_high = 0;
4993 ei->i_flags &= ~EXT4_HUGE_FILE_FL;
4994 return 0;
4996 if (!EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_HUGE_FILE))
4997 return -EFBIG;
4999 if (i_blocks <= 0xffffffffffffULL) {
5001 * i_blocks can be represented in a 48 bit variable
5002 * as multiple of 512 bytes
5004 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
5005 raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
5006 ei->i_flags &= ~EXT4_HUGE_FILE_FL;
5007 } else {
5008 ei->i_flags |= EXT4_HUGE_FILE_FL;
5009 /* i_block is stored in file system block size */
5010 i_blocks = i_blocks >> (inode->i_blkbits - 9);
5011 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
5012 raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
5014 return 0;
5018 * Post the struct inode info into an on-disk inode location in the
5019 * buffer-cache. This gobbles the caller's reference to the
5020 * buffer_head in the inode location struct.
5022 * The caller must have write access to iloc->bh.
5024 static int ext4_do_update_inode(handle_t *handle,
5025 struct inode *inode,
5026 struct ext4_iloc *iloc)
5028 struct ext4_inode *raw_inode = ext4_raw_inode(iloc);
5029 struct ext4_inode_info *ei = EXT4_I(inode);
5030 struct buffer_head *bh = iloc->bh;
5031 int err = 0, rc, block;
5033 /* For fields not not tracking in the in-memory inode,
5034 * initialise them to zero for new inodes. */
5035 if (ei->i_state & EXT4_STATE_NEW)
5036 memset(raw_inode, 0, EXT4_SB(inode->i_sb)->s_inode_size);
5038 ext4_get_inode_flags(ei);
5039 raw_inode->i_mode = cpu_to_le16(inode->i_mode);
5040 if (!(test_opt(inode->i_sb, NO_UID32))) {
5041 raw_inode->i_uid_low = cpu_to_le16(low_16_bits(inode->i_uid));
5042 raw_inode->i_gid_low = cpu_to_le16(low_16_bits(inode->i_gid));
5044 * Fix up interoperability with old kernels. Otherwise, old inodes get
5045 * re-used with the upper 16 bits of the uid/gid intact
5047 if (!ei->i_dtime) {
5048 raw_inode->i_uid_high =
5049 cpu_to_le16(high_16_bits(inode->i_uid));
5050 raw_inode->i_gid_high =
5051 cpu_to_le16(high_16_bits(inode->i_gid));
5052 } else {
5053 raw_inode->i_uid_high = 0;
5054 raw_inode->i_gid_high = 0;
5056 } else {
5057 raw_inode->i_uid_low =
5058 cpu_to_le16(fs_high2lowuid(inode->i_uid));
5059 raw_inode->i_gid_low =
5060 cpu_to_le16(fs_high2lowgid(inode->i_gid));
5061 raw_inode->i_uid_high = 0;
5062 raw_inode->i_gid_high = 0;
5064 raw_inode->i_links_count = cpu_to_le16(inode->i_nlink);
5066 EXT4_INODE_SET_XTIME(i_ctime, inode, raw_inode);
5067 EXT4_INODE_SET_XTIME(i_mtime, inode, raw_inode);
5068 EXT4_INODE_SET_XTIME(i_atime, inode, raw_inode);
5069 EXT4_EINODE_SET_XTIME(i_crtime, ei, raw_inode);
5071 if (ext4_inode_blocks_set(handle, raw_inode, ei))
5072 goto out_brelse;
5073 raw_inode->i_dtime = cpu_to_le32(ei->i_dtime);
5074 raw_inode->i_flags = cpu_to_le32(ei->i_flags);
5075 if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
5076 cpu_to_le32(EXT4_OS_HURD))
5077 raw_inode->i_file_acl_high =
5078 cpu_to_le16(ei->i_file_acl >> 32);
5079 raw_inode->i_file_acl_lo = cpu_to_le32(ei->i_file_acl);
5080 ext4_isize_set(raw_inode, ei->i_disksize);
5081 if (ei->i_disksize > 0x7fffffffULL) {
5082 struct super_block *sb = inode->i_sb;
5083 if (!EXT4_HAS_RO_COMPAT_FEATURE(sb,
5084 EXT4_FEATURE_RO_COMPAT_LARGE_FILE) ||
5085 EXT4_SB(sb)->s_es->s_rev_level ==
5086 cpu_to_le32(EXT4_GOOD_OLD_REV)) {
5087 /* If this is the first large file
5088 * created, add a flag to the superblock.
5090 err = ext4_journal_get_write_access(handle,
5091 EXT4_SB(sb)->s_sbh);
5092 if (err)
5093 goto out_brelse;
5094 ext4_update_dynamic_rev(sb);
5095 EXT4_SET_RO_COMPAT_FEATURE(sb,
5096 EXT4_FEATURE_RO_COMPAT_LARGE_FILE);
5097 sb->s_dirt = 1;
5098 ext4_handle_sync(handle);
5099 err = ext4_handle_dirty_metadata(handle, inode,
5100 EXT4_SB(sb)->s_sbh);
5103 raw_inode->i_generation = cpu_to_le32(inode->i_generation);
5104 if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) {
5105 if (old_valid_dev(inode->i_rdev)) {
5106 raw_inode->i_block[0] =
5107 cpu_to_le32(old_encode_dev(inode->i_rdev));
5108 raw_inode->i_block[1] = 0;
5109 } else {
5110 raw_inode->i_block[0] = 0;
5111 raw_inode->i_block[1] =
5112 cpu_to_le32(new_encode_dev(inode->i_rdev));
5113 raw_inode->i_block[2] = 0;
5115 } else
5116 for (block = 0; block < EXT4_N_BLOCKS; block++)
5117 raw_inode->i_block[block] = ei->i_data[block];
5119 raw_inode->i_disk_version = cpu_to_le32(inode->i_version);
5120 if (ei->i_extra_isize) {
5121 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
5122 raw_inode->i_version_hi =
5123 cpu_to_le32(inode->i_version >> 32);
5124 raw_inode->i_extra_isize = cpu_to_le16(ei->i_extra_isize);
5127 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
5128 rc = ext4_handle_dirty_metadata(handle, inode, bh);
5129 if (!err)
5130 err = rc;
5131 ei->i_state &= ~EXT4_STATE_NEW;
5133 ext4_update_inode_fsync_trans(handle, inode, 0);
5134 out_brelse:
5135 brelse(bh);
5136 ext4_std_error(inode->i_sb, err);
5137 return err;
5141 * ext4_write_inode()
5143 * We are called from a few places:
5145 * - Within generic_file_write() for O_SYNC files.
5146 * Here, there will be no transaction running. We wait for any running
5147 * trasnaction to commit.
5149 * - Within sys_sync(), kupdate and such.
5150 * We wait on commit, if tol to.
5152 * - Within prune_icache() (PF_MEMALLOC == true)
5153 * Here we simply return. We can't afford to block kswapd on the
5154 * journal commit.
5156 * In all cases it is actually safe for us to return without doing anything,
5157 * because the inode has been copied into a raw inode buffer in
5158 * ext4_mark_inode_dirty(). This is a correctness thing for O_SYNC and for
5159 * knfsd.
5161 * Note that we are absolutely dependent upon all inode dirtiers doing the
5162 * right thing: they *must* call mark_inode_dirty() after dirtying info in
5163 * which we are interested.
5165 * It would be a bug for them to not do this. The code:
5167 * mark_inode_dirty(inode)
5168 * stuff();
5169 * inode->i_size = expr;
5171 * is in error because a kswapd-driven write_inode() could occur while
5172 * `stuff()' is running, and the new i_size will be lost. Plus the inode
5173 * will no longer be on the superblock's dirty inode list.
5175 int ext4_write_inode(struct inode *inode, int wait)
5177 int err;
5179 if (current->flags & PF_MEMALLOC)
5180 return 0;
5182 if (EXT4_SB(inode->i_sb)->s_journal) {
5183 if (ext4_journal_current_handle()) {
5184 jbd_debug(1, "called recursively, non-PF_MEMALLOC!\n");
5185 dump_stack();
5186 return -EIO;
5189 if (!wait)
5190 return 0;
5192 err = ext4_force_commit(inode->i_sb);
5193 } else {
5194 struct ext4_iloc iloc;
5196 err = ext4_get_inode_loc(inode, &iloc);
5197 if (err)
5198 return err;
5199 if (wait)
5200 sync_dirty_buffer(iloc.bh);
5201 if (buffer_req(iloc.bh) && !buffer_uptodate(iloc.bh)) {
5202 ext4_error(inode->i_sb, __func__,
5203 "IO error syncing inode, "
5204 "inode=%lu, block=%llu",
5205 inode->i_ino,
5206 (unsigned long long)iloc.bh->b_blocknr);
5207 err = -EIO;
5210 return err;
5214 * ext4_setattr()
5216 * Called from notify_change.
5218 * We want to trap VFS attempts to truncate the file as soon as
5219 * possible. In particular, we want to make sure that when the VFS
5220 * shrinks i_size, we put the inode on the orphan list and modify
5221 * i_disksize immediately, so that during the subsequent flushing of
5222 * dirty pages and freeing of disk blocks, we can guarantee that any
5223 * commit will leave the blocks being flushed in an unused state on
5224 * disk. (On recovery, the inode will get truncated and the blocks will
5225 * be freed, so we have a strong guarantee that no future commit will
5226 * leave these blocks visible to the user.)
5228 * Another thing we have to assure is that if we are in ordered mode
5229 * and inode is still attached to the committing transaction, we must
5230 * we start writeout of all the dirty pages which are being truncated.
5231 * This way we are sure that all the data written in the previous
5232 * transaction are already on disk (truncate waits for pages under
5233 * writeback).
5235 * Called with inode->i_mutex down.
5237 int ext4_setattr(struct dentry *dentry, struct iattr *attr)
5239 struct inode *inode = dentry->d_inode;
5240 int error, rc = 0;
5241 const unsigned int ia_valid = attr->ia_valid;
5243 error = inode_change_ok(inode, attr);
5244 if (error)
5245 return error;
5247 if ((ia_valid & ATTR_UID && attr->ia_uid != inode->i_uid) ||
5248 (ia_valid & ATTR_GID && attr->ia_gid != inode->i_gid)) {
5249 handle_t *handle;
5251 /* (user+group)*(old+new) structure, inode write (sb,
5252 * inode block, ? - but truncate inode update has it) */
5253 handle = ext4_journal_start(inode, (EXT4_MAXQUOTAS_INIT_BLOCKS(inode->i_sb)+
5254 EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb))+3);
5255 if (IS_ERR(handle)) {
5256 error = PTR_ERR(handle);
5257 goto err_out;
5259 error = vfs_dq_transfer(inode, attr) ? -EDQUOT : 0;
5260 if (error) {
5261 ext4_journal_stop(handle);
5262 return error;
5264 /* Update corresponding info in inode so that everything is in
5265 * one transaction */
5266 if (attr->ia_valid & ATTR_UID)
5267 inode->i_uid = attr->ia_uid;
5268 if (attr->ia_valid & ATTR_GID)
5269 inode->i_gid = attr->ia_gid;
5270 error = ext4_mark_inode_dirty(handle, inode);
5271 ext4_journal_stop(handle);
5274 if (attr->ia_valid & ATTR_SIZE) {
5275 if (!(EXT4_I(inode)->i_flags & EXT4_EXTENTS_FL)) {
5276 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
5278 if (attr->ia_size > sbi->s_bitmap_maxbytes) {
5279 error = -EFBIG;
5280 goto err_out;
5285 if (S_ISREG(inode->i_mode) &&
5286 attr->ia_valid & ATTR_SIZE && attr->ia_size < inode->i_size) {
5287 handle_t *handle;
5289 handle = ext4_journal_start(inode, 3);
5290 if (IS_ERR(handle)) {
5291 error = PTR_ERR(handle);
5292 goto err_out;
5295 error = ext4_orphan_add(handle, inode);
5296 EXT4_I(inode)->i_disksize = attr->ia_size;
5297 rc = ext4_mark_inode_dirty(handle, inode);
5298 if (!error)
5299 error = rc;
5300 ext4_journal_stop(handle);
5302 if (ext4_should_order_data(inode)) {
5303 error = ext4_begin_ordered_truncate(inode,
5304 attr->ia_size);
5305 if (error) {
5306 /* Do as much error cleanup as possible */
5307 handle = ext4_journal_start(inode, 3);
5308 if (IS_ERR(handle)) {
5309 ext4_orphan_del(NULL, inode);
5310 goto err_out;
5312 ext4_orphan_del(handle, inode);
5313 ext4_journal_stop(handle);
5314 goto err_out;
5319 rc = inode_setattr(inode, attr);
5321 /* If inode_setattr's call to ext4_truncate failed to get a
5322 * transaction handle at all, we need to clean up the in-core
5323 * orphan list manually. */
5324 if (inode->i_nlink)
5325 ext4_orphan_del(NULL, inode);
5327 if (!rc && (ia_valid & ATTR_MODE))
5328 rc = ext4_acl_chmod(inode);
5330 err_out:
5331 ext4_std_error(inode->i_sb, error);
5332 if (!error)
5333 error = rc;
5334 return error;
5337 int ext4_getattr(struct vfsmount *mnt, struct dentry *dentry,
5338 struct kstat *stat)
5340 struct inode *inode;
5341 unsigned long delalloc_blocks;
5343 inode = dentry->d_inode;
5344 generic_fillattr(inode, stat);
5347 * We can't update i_blocks if the block allocation is delayed
5348 * otherwise in the case of system crash before the real block
5349 * allocation is done, we will have i_blocks inconsistent with
5350 * on-disk file blocks.
5351 * We always keep i_blocks updated together with real
5352 * allocation. But to not confuse with user, stat
5353 * will return the blocks that include the delayed allocation
5354 * blocks for this file.
5356 spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
5357 delalloc_blocks = EXT4_I(inode)->i_reserved_data_blocks;
5358 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
5360 stat->blocks += (delalloc_blocks << inode->i_sb->s_blocksize_bits)>>9;
5361 return 0;
5364 static int ext4_indirect_trans_blocks(struct inode *inode, int nrblocks,
5365 int chunk)
5367 int indirects;
5369 /* if nrblocks are contiguous */
5370 if (chunk) {
5372 * With N contiguous data blocks, it need at most
5373 * N/EXT4_ADDR_PER_BLOCK(inode->i_sb) indirect blocks
5374 * 2 dindirect blocks
5375 * 1 tindirect block
5377 indirects = nrblocks / EXT4_ADDR_PER_BLOCK(inode->i_sb);
5378 return indirects + 3;
5381 * if nrblocks are not contiguous, worse case, each block touch
5382 * a indirect block, and each indirect block touch a double indirect
5383 * block, plus a triple indirect block
5385 indirects = nrblocks * 2 + 1;
5386 return indirects;
5389 static int ext4_index_trans_blocks(struct inode *inode, int nrblocks, int chunk)
5391 if (!(EXT4_I(inode)->i_flags & EXT4_EXTENTS_FL))
5392 return ext4_indirect_trans_blocks(inode, nrblocks, chunk);
5393 return ext4_ext_index_trans_blocks(inode, nrblocks, chunk);
5397 * Account for index blocks, block groups bitmaps and block group
5398 * descriptor blocks if modify datablocks and index blocks
5399 * worse case, the indexs blocks spread over different block groups
5401 * If datablocks are discontiguous, they are possible to spread over
5402 * different block groups too. If they are contiugous, with flexbg,
5403 * they could still across block group boundary.
5405 * Also account for superblock, inode, quota and xattr blocks
5407 int ext4_meta_trans_blocks(struct inode *inode, int nrblocks, int chunk)
5409 ext4_group_t groups, ngroups = ext4_get_groups_count(inode->i_sb);
5410 int gdpblocks;
5411 int idxblocks;
5412 int ret = 0;
5415 * How many index blocks need to touch to modify nrblocks?
5416 * The "Chunk" flag indicating whether the nrblocks is
5417 * physically contiguous on disk
5419 * For Direct IO and fallocate, they calls get_block to allocate
5420 * one single extent at a time, so they could set the "Chunk" flag
5422 idxblocks = ext4_index_trans_blocks(inode, nrblocks, chunk);
5424 ret = idxblocks;
5427 * Now let's see how many group bitmaps and group descriptors need
5428 * to account
5430 groups = idxblocks;
5431 if (chunk)
5432 groups += 1;
5433 else
5434 groups += nrblocks;
5436 gdpblocks = groups;
5437 if (groups > ngroups)
5438 groups = ngroups;
5439 if (groups > EXT4_SB(inode->i_sb)->s_gdb_count)
5440 gdpblocks = EXT4_SB(inode->i_sb)->s_gdb_count;
5442 /* bitmaps and block group descriptor blocks */
5443 ret += groups + gdpblocks;
5445 /* Blocks for super block, inode, quota and xattr blocks */
5446 ret += EXT4_META_TRANS_BLOCKS(inode->i_sb);
5448 return ret;
5452 * Calulate the total number of credits to reserve to fit
5453 * the modification of a single pages into a single transaction,
5454 * which may include multiple chunks of block allocations.
5456 * This could be called via ext4_write_begin()
5458 * We need to consider the worse case, when
5459 * one new block per extent.
5461 int ext4_writepage_trans_blocks(struct inode *inode)
5463 int bpp = ext4_journal_blocks_per_page(inode);
5464 int ret;
5466 ret = ext4_meta_trans_blocks(inode, bpp, 0);
5468 /* Account for data blocks for journalled mode */
5469 if (ext4_should_journal_data(inode))
5470 ret += bpp;
5471 return ret;
5475 * Calculate the journal credits for a chunk of data modification.
5477 * This is called from DIO, fallocate or whoever calling
5478 * ext4_get_blocks() to map/allocate a chunk of contigous disk blocks.
5480 * journal buffers for data blocks are not included here, as DIO
5481 * and fallocate do no need to journal data buffers.
5483 int ext4_chunk_trans_blocks(struct inode *inode, int nrblocks)
5485 return ext4_meta_trans_blocks(inode, nrblocks, 1);
5489 * The caller must have previously called ext4_reserve_inode_write().
5490 * Give this, we know that the caller already has write access to iloc->bh.
5492 int ext4_mark_iloc_dirty(handle_t *handle,
5493 struct inode *inode, struct ext4_iloc *iloc)
5495 int err = 0;
5497 if (test_opt(inode->i_sb, I_VERSION))
5498 inode_inc_iversion(inode);
5500 /* the do_update_inode consumes one bh->b_count */
5501 get_bh(iloc->bh);
5503 /* ext4_do_update_inode() does jbd2_journal_dirty_metadata */
5504 err = ext4_do_update_inode(handle, inode, iloc);
5505 put_bh(iloc->bh);
5506 return err;
5510 * On success, We end up with an outstanding reference count against
5511 * iloc->bh. This _must_ be cleaned up later.
5515 ext4_reserve_inode_write(handle_t *handle, struct inode *inode,
5516 struct ext4_iloc *iloc)
5518 int err;
5520 err = ext4_get_inode_loc(inode, iloc);
5521 if (!err) {
5522 BUFFER_TRACE(iloc->bh, "get_write_access");
5523 err = ext4_journal_get_write_access(handle, iloc->bh);
5524 if (err) {
5525 brelse(iloc->bh);
5526 iloc->bh = NULL;
5529 ext4_std_error(inode->i_sb, err);
5530 return err;
5534 * Expand an inode by new_extra_isize bytes.
5535 * Returns 0 on success or negative error number on failure.
5537 static int ext4_expand_extra_isize(struct inode *inode,
5538 unsigned int new_extra_isize,
5539 struct ext4_iloc iloc,
5540 handle_t *handle)
5542 struct ext4_inode *raw_inode;
5543 struct ext4_xattr_ibody_header *header;
5544 struct ext4_xattr_entry *entry;
5546 if (EXT4_I(inode)->i_extra_isize >= new_extra_isize)
5547 return 0;
5549 raw_inode = ext4_raw_inode(&iloc);
5551 header = IHDR(inode, raw_inode);
5552 entry = IFIRST(header);
5554 /* No extended attributes present */
5555 if (!(EXT4_I(inode)->i_state & EXT4_STATE_XATTR) ||
5556 header->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC)) {
5557 memset((void *)raw_inode + EXT4_GOOD_OLD_INODE_SIZE, 0,
5558 new_extra_isize);
5559 EXT4_I(inode)->i_extra_isize = new_extra_isize;
5560 return 0;
5563 /* try to expand with EAs present */
5564 return ext4_expand_extra_isize_ea(inode, new_extra_isize,
5565 raw_inode, handle);
5569 * What we do here is to mark the in-core inode as clean with respect to inode
5570 * dirtiness (it may still be data-dirty).
5571 * This means that the in-core inode may be reaped by prune_icache
5572 * without having to perform any I/O. This is a very good thing,
5573 * because *any* task may call prune_icache - even ones which
5574 * have a transaction open against a different journal.
5576 * Is this cheating? Not really. Sure, we haven't written the
5577 * inode out, but prune_icache isn't a user-visible syncing function.
5578 * Whenever the user wants stuff synced (sys_sync, sys_msync, sys_fsync)
5579 * we start and wait on commits.
5581 * Is this efficient/effective? Well, we're being nice to the system
5582 * by cleaning up our inodes proactively so they can be reaped
5583 * without I/O. But we are potentially leaving up to five seconds'
5584 * worth of inodes floating about which prune_icache wants us to
5585 * write out. One way to fix that would be to get prune_icache()
5586 * to do a write_super() to free up some memory. It has the desired
5587 * effect.
5589 int ext4_mark_inode_dirty(handle_t *handle, struct inode *inode)
5591 struct ext4_iloc iloc;
5592 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
5593 static unsigned int mnt_count;
5594 int err, ret;
5596 might_sleep();
5597 err = ext4_reserve_inode_write(handle, inode, &iloc);
5598 if (ext4_handle_valid(handle) &&
5599 EXT4_I(inode)->i_extra_isize < sbi->s_want_extra_isize &&
5600 !(EXT4_I(inode)->i_state & EXT4_STATE_NO_EXPAND)) {
5602 * We need extra buffer credits since we may write into EA block
5603 * with this same handle. If journal_extend fails, then it will
5604 * only result in a minor loss of functionality for that inode.
5605 * If this is felt to be critical, then e2fsck should be run to
5606 * force a large enough s_min_extra_isize.
5608 if ((jbd2_journal_extend(handle,
5609 EXT4_DATA_TRANS_BLOCKS(inode->i_sb))) == 0) {
5610 ret = ext4_expand_extra_isize(inode,
5611 sbi->s_want_extra_isize,
5612 iloc, handle);
5613 if (ret) {
5614 EXT4_I(inode)->i_state |= EXT4_STATE_NO_EXPAND;
5615 if (mnt_count !=
5616 le16_to_cpu(sbi->s_es->s_mnt_count)) {
5617 ext4_warning(inode->i_sb, __func__,
5618 "Unable to expand inode %lu. Delete"
5619 " some EAs or run e2fsck.",
5620 inode->i_ino);
5621 mnt_count =
5622 le16_to_cpu(sbi->s_es->s_mnt_count);
5627 if (!err)
5628 err = ext4_mark_iloc_dirty(handle, inode, &iloc);
5629 return err;
5633 * ext4_dirty_inode() is called from __mark_inode_dirty()
5635 * We're really interested in the case where a file is being extended.
5636 * i_size has been changed by generic_commit_write() and we thus need
5637 * to include the updated inode in the current transaction.
5639 * Also, vfs_dq_alloc_block() will always dirty the inode when blocks
5640 * are allocated to the file.
5642 * If the inode is marked synchronous, we don't honour that here - doing
5643 * so would cause a commit on atime updates, which we don't bother doing.
5644 * We handle synchronous inodes at the highest possible level.
5646 void ext4_dirty_inode(struct inode *inode)
5648 handle_t *current_handle = ext4_journal_current_handle();
5649 handle_t *handle;
5651 handle = ext4_journal_start(inode, 2);
5652 if (IS_ERR(handle))
5653 goto out;
5655 jbd_debug(5, "marking dirty. outer handle=%p\n", current_handle);
5656 ext4_mark_inode_dirty(handle, inode);
5658 ext4_journal_stop(handle);
5659 out:
5660 return;
5663 #if 0
5665 * Bind an inode's backing buffer_head into this transaction, to prevent
5666 * it from being flushed to disk early. Unlike
5667 * ext4_reserve_inode_write, this leaves behind no bh reference and
5668 * returns no iloc structure, so the caller needs to repeat the iloc
5669 * lookup to mark the inode dirty later.
5671 static int ext4_pin_inode(handle_t *handle, struct inode *inode)
5673 struct ext4_iloc iloc;
5675 int err = 0;
5676 if (handle) {
5677 err = ext4_get_inode_loc(inode, &iloc);
5678 if (!err) {
5679 BUFFER_TRACE(iloc.bh, "get_write_access");
5680 err = jbd2_journal_get_write_access(handle, iloc.bh);
5681 if (!err)
5682 err = ext4_handle_dirty_metadata(handle,
5683 inode,
5684 iloc.bh);
5685 brelse(iloc.bh);
5688 ext4_std_error(inode->i_sb, err);
5689 return err;
5691 #endif
5693 int ext4_change_inode_journal_flag(struct inode *inode, int val)
5695 journal_t *journal;
5696 handle_t *handle;
5697 int err;
5700 * We have to be very careful here: changing a data block's
5701 * journaling status dynamically is dangerous. If we write a
5702 * data block to the journal, change the status and then delete
5703 * that block, we risk forgetting to revoke the old log record
5704 * from the journal and so a subsequent replay can corrupt data.
5705 * So, first we make sure that the journal is empty and that
5706 * nobody is changing anything.
5709 journal = EXT4_JOURNAL(inode);
5710 if (!journal)
5711 return 0;
5712 if (is_journal_aborted(journal))
5713 return -EROFS;
5715 jbd2_journal_lock_updates(journal);
5716 jbd2_journal_flush(journal);
5719 * OK, there are no updates running now, and all cached data is
5720 * synced to disk. We are now in a completely consistent state
5721 * which doesn't have anything in the journal, and we know that
5722 * no filesystem updates are running, so it is safe to modify
5723 * the inode's in-core data-journaling state flag now.
5726 if (val)
5727 EXT4_I(inode)->i_flags |= EXT4_JOURNAL_DATA_FL;
5728 else
5729 EXT4_I(inode)->i_flags &= ~EXT4_JOURNAL_DATA_FL;
5730 ext4_set_aops(inode);
5732 jbd2_journal_unlock_updates(journal);
5734 /* Finally we can mark the inode as dirty. */
5736 handle = ext4_journal_start(inode, 1);
5737 if (IS_ERR(handle))
5738 return PTR_ERR(handle);
5740 err = ext4_mark_inode_dirty(handle, inode);
5741 ext4_handle_sync(handle);
5742 ext4_journal_stop(handle);
5743 ext4_std_error(inode->i_sb, err);
5745 return err;
5748 static int ext4_bh_unmapped(handle_t *handle, struct buffer_head *bh)
5750 return !buffer_mapped(bh);
5753 int ext4_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
5755 struct page *page = vmf->page;
5756 loff_t size;
5757 unsigned long len;
5758 int ret = -EINVAL;
5759 void *fsdata;
5760 struct file *file = vma->vm_file;
5761 struct inode *inode = file->f_path.dentry->d_inode;
5762 struct address_space *mapping = inode->i_mapping;
5765 * Get i_alloc_sem to stop truncates messing with the inode. We cannot
5766 * get i_mutex because we are already holding mmap_sem.
5768 down_read(&inode->i_alloc_sem);
5769 size = i_size_read(inode);
5770 if (page->mapping != mapping || size <= page_offset(page)
5771 || !PageUptodate(page)) {
5772 /* page got truncated from under us? */
5773 goto out_unlock;
5775 ret = 0;
5776 if (PageMappedToDisk(page))
5777 goto out_unlock;
5779 if (page->index == size >> PAGE_CACHE_SHIFT)
5780 len = size & ~PAGE_CACHE_MASK;
5781 else
5782 len = PAGE_CACHE_SIZE;
5784 lock_page(page);
5786 * return if we have all the buffers mapped. This avoid
5787 * the need to call write_begin/write_end which does a
5788 * journal_start/journal_stop which can block and take
5789 * long time
5791 if (page_has_buffers(page)) {
5792 if (!walk_page_buffers(NULL, page_buffers(page), 0, len, NULL,
5793 ext4_bh_unmapped)) {
5794 unlock_page(page);
5795 goto out_unlock;
5798 unlock_page(page);
5800 * OK, we need to fill the hole... Do write_begin write_end
5801 * to do block allocation/reservation.We are not holding
5802 * inode.i__mutex here. That allow * parallel write_begin,
5803 * write_end call. lock_page prevent this from happening
5804 * on the same page though
5806 ret = mapping->a_ops->write_begin(file, mapping, page_offset(page),
5807 len, AOP_FLAG_UNINTERRUPTIBLE, &page, &fsdata);
5808 if (ret < 0)
5809 goto out_unlock;
5810 ret = mapping->a_ops->write_end(file, mapping, page_offset(page),
5811 len, len, page, fsdata);
5812 if (ret < 0)
5813 goto out_unlock;
5814 ret = 0;
5815 out_unlock:
5816 if (ret)
5817 ret = VM_FAULT_SIGBUS;
5818 up_read(&inode->i_alloc_sem);
5819 return ret;