ext4: Fix discard of inode prealloc space with delayed allocation.
[linux-2.6/mini2440.git] / fs / ext4 / inode.c
blob9abf8c12c67ddb2a24583be9dc027a7b059c06c2
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 "ext4_jbd2.h"
41 #include "xattr.h"
42 #include "acl.h"
43 #include "ext4_extents.h"
45 #define MPAGE_DA_EXTENT_TAIL 0x01
47 static inline int ext4_begin_ordered_truncate(struct inode *inode,
48 loff_t new_size)
50 return jbd2_journal_begin_ordered_truncate(
51 EXT4_SB(inode->i_sb)->s_journal,
52 &EXT4_I(inode)->jinode,
53 new_size);
56 static void ext4_invalidatepage(struct page *page, unsigned long offset);
59 * Test whether an inode is a fast symlink.
61 static int ext4_inode_is_fast_symlink(struct inode *inode)
63 int ea_blocks = EXT4_I(inode)->i_file_acl ?
64 (inode->i_sb->s_blocksize >> 9) : 0;
66 return (S_ISLNK(inode->i_mode) && inode->i_blocks - ea_blocks == 0);
70 * The ext4 forget function must perform a revoke if we are freeing data
71 * which has been journaled. Metadata (eg. indirect blocks) must be
72 * revoked in all cases.
74 * "bh" may be NULL: a metadata block may have been freed from memory
75 * but there may still be a record of it in the journal, and that record
76 * still needs to be revoked.
78 * If the handle isn't valid we're not journaling so there's nothing to do.
80 int ext4_forget(handle_t *handle, int is_metadata, struct inode *inode,
81 struct buffer_head *bh, ext4_fsblk_t blocknr)
83 int err;
85 if (!ext4_handle_valid(handle))
86 return 0;
88 might_sleep();
90 BUFFER_TRACE(bh, "enter");
92 jbd_debug(4, "forgetting bh %p: is_metadata = %d, mode %o, "
93 "data mode %lx\n",
94 bh, is_metadata, inode->i_mode,
95 test_opt(inode->i_sb, DATA_FLAGS));
97 /* Never use the revoke function if we are doing full data
98 * journaling: there is no need to, and a V1 superblock won't
99 * support it. Otherwise, only skip the revoke on un-journaled
100 * data blocks. */
102 if (test_opt(inode->i_sb, DATA_FLAGS) == EXT4_MOUNT_JOURNAL_DATA ||
103 (!is_metadata && !ext4_should_journal_data(inode))) {
104 if (bh) {
105 BUFFER_TRACE(bh, "call jbd2_journal_forget");
106 return ext4_journal_forget(handle, bh);
108 return 0;
112 * data!=journal && (is_metadata || should_journal_data(inode))
114 BUFFER_TRACE(bh, "call ext4_journal_revoke");
115 err = ext4_journal_revoke(handle, blocknr, bh);
116 if (err)
117 ext4_abort(inode->i_sb, __func__,
118 "error %d when attempting revoke", err);
119 BUFFER_TRACE(bh, "exit");
120 return err;
124 * Work out how many blocks we need to proceed with the next chunk of a
125 * truncate transaction.
127 static unsigned long blocks_for_truncate(struct inode *inode)
129 ext4_lblk_t needed;
131 needed = inode->i_blocks >> (inode->i_sb->s_blocksize_bits - 9);
133 /* Give ourselves just enough room to cope with inodes in which
134 * i_blocks is corrupt: we've seen disk corruptions in the past
135 * which resulted in random data in an inode which looked enough
136 * like a regular file for ext4 to try to delete it. Things
137 * will go a bit crazy if that happens, but at least we should
138 * try not to panic the whole kernel. */
139 if (needed < 2)
140 needed = 2;
142 /* But we need to bound the transaction so we don't overflow the
143 * journal. */
144 if (needed > EXT4_MAX_TRANS_DATA)
145 needed = EXT4_MAX_TRANS_DATA;
147 return EXT4_DATA_TRANS_BLOCKS(inode->i_sb) + needed;
151 * Truncate transactions can be complex and absolutely huge. So we need to
152 * be able to restart the transaction at a conventient checkpoint to make
153 * sure we don't overflow the journal.
155 * start_transaction gets us a new handle for a truncate transaction,
156 * and extend_transaction tries to extend the existing one a bit. If
157 * extend fails, we need to propagate the failure up and restart the
158 * transaction in the top-level truncate loop. --sct
160 static handle_t *start_transaction(struct inode *inode)
162 handle_t *result;
164 result = ext4_journal_start(inode, blocks_for_truncate(inode));
165 if (!IS_ERR(result))
166 return result;
168 ext4_std_error(inode->i_sb, PTR_ERR(result));
169 return result;
173 * Try to extend this transaction for the purposes of truncation.
175 * Returns 0 if we managed to create more room. If we can't create more
176 * room, and the transaction must be restarted we return 1.
178 static int try_to_extend_transaction(handle_t *handle, struct inode *inode)
180 if (!ext4_handle_valid(handle))
181 return 0;
182 if (ext4_handle_has_enough_credits(handle, EXT4_RESERVE_TRANS_BLOCKS+1))
183 return 0;
184 if (!ext4_journal_extend(handle, blocks_for_truncate(inode)))
185 return 0;
186 return 1;
190 * Restart the transaction associated with *handle. This does a commit,
191 * so before we call here everything must be consistently dirtied against
192 * this transaction.
194 static int ext4_journal_test_restart(handle_t *handle, struct inode *inode)
196 BUG_ON(EXT4_JOURNAL(inode) == NULL);
197 jbd_debug(2, "restarting handle %p\n", handle);
198 return ext4_journal_restart(handle, blocks_for_truncate(inode));
202 * Called at the last iput() if i_nlink is zero.
204 void ext4_delete_inode(struct inode *inode)
206 handle_t *handle;
207 int err;
209 if (ext4_should_order_data(inode))
210 ext4_begin_ordered_truncate(inode, 0);
211 truncate_inode_pages(&inode->i_data, 0);
213 if (is_bad_inode(inode))
214 goto no_delete;
216 handle = ext4_journal_start(inode, blocks_for_truncate(inode)+3);
217 if (IS_ERR(handle)) {
218 ext4_std_error(inode->i_sb, PTR_ERR(handle));
220 * If we're going to skip the normal cleanup, we still need to
221 * make sure that the in-core orphan linked list is properly
222 * cleaned up.
224 ext4_orphan_del(NULL, inode);
225 goto no_delete;
228 if (IS_SYNC(inode))
229 ext4_handle_sync(handle);
230 inode->i_size = 0;
231 err = ext4_mark_inode_dirty(handle, inode);
232 if (err) {
233 ext4_warning(inode->i_sb, __func__,
234 "couldn't mark inode dirty (err %d)", err);
235 goto stop_handle;
237 if (inode->i_blocks)
238 ext4_truncate(inode);
241 * ext4_ext_truncate() doesn't reserve any slop when it
242 * restarts journal transactions; therefore there may not be
243 * enough credits left in the handle to remove the inode from
244 * the orphan list and set the dtime field.
246 if (!ext4_handle_has_enough_credits(handle, 3)) {
247 err = ext4_journal_extend(handle, 3);
248 if (err > 0)
249 err = ext4_journal_restart(handle, 3);
250 if (err != 0) {
251 ext4_warning(inode->i_sb, __func__,
252 "couldn't extend journal (err %d)", err);
253 stop_handle:
254 ext4_journal_stop(handle);
255 goto no_delete;
260 * Kill off the orphan record which ext4_truncate created.
261 * AKPM: I think this can be inside the above `if'.
262 * Note that ext4_orphan_del() has to be able to cope with the
263 * deletion of a non-existent orphan - this is because we don't
264 * know if ext4_truncate() actually created an orphan record.
265 * (Well, we could do this if we need to, but heck - it works)
267 ext4_orphan_del(handle, inode);
268 EXT4_I(inode)->i_dtime = get_seconds();
271 * One subtle ordering requirement: if anything has gone wrong
272 * (transaction abort, IO errors, whatever), then we can still
273 * do these next steps (the fs will already have been marked as
274 * having errors), but we can't free the inode if the mark_dirty
275 * fails.
277 if (ext4_mark_inode_dirty(handle, inode))
278 /* If that failed, just do the required in-core inode clear. */
279 clear_inode(inode);
280 else
281 ext4_free_inode(handle, inode);
282 ext4_journal_stop(handle);
283 return;
284 no_delete:
285 clear_inode(inode); /* We must guarantee clearing of inode... */
288 typedef struct {
289 __le32 *p;
290 __le32 key;
291 struct buffer_head *bh;
292 } Indirect;
294 static inline void add_chain(Indirect *p, struct buffer_head *bh, __le32 *v)
296 p->key = *(p->p = v);
297 p->bh = bh;
301 * ext4_block_to_path - parse the block number into array of offsets
302 * @inode: inode in question (we are only interested in its superblock)
303 * @i_block: block number to be parsed
304 * @offsets: array to store the offsets in
305 * @boundary: set this non-zero if the referred-to block is likely to be
306 * followed (on disk) by an indirect block.
308 * To store the locations of file's data ext4 uses a data structure common
309 * for UNIX filesystems - tree of pointers anchored in the inode, with
310 * data blocks at leaves and indirect blocks in intermediate nodes.
311 * This function translates the block number into path in that tree -
312 * return value is the path length and @offsets[n] is the offset of
313 * pointer to (n+1)th node in the nth one. If @block is out of range
314 * (negative or too large) warning is printed and zero returned.
316 * Note: function doesn't find node addresses, so no IO is needed. All
317 * we need to know is the capacity of indirect blocks (taken from the
318 * inode->i_sb).
322 * Portability note: the last comparison (check that we fit into triple
323 * indirect block) is spelled differently, because otherwise on an
324 * architecture with 32-bit longs and 8Kb pages we might get into trouble
325 * if our filesystem had 8Kb blocks. We might use long long, but that would
326 * kill us on x86. Oh, well, at least the sign propagation does not matter -
327 * i_block would have to be negative in the very beginning, so we would not
328 * get there at all.
331 static int ext4_block_to_path(struct inode *inode,
332 ext4_lblk_t i_block,
333 ext4_lblk_t offsets[4], int *boundary)
335 int ptrs = EXT4_ADDR_PER_BLOCK(inode->i_sb);
336 int ptrs_bits = EXT4_ADDR_PER_BLOCK_BITS(inode->i_sb);
337 const long direct_blocks = EXT4_NDIR_BLOCKS,
338 indirect_blocks = ptrs,
339 double_blocks = (1 << (ptrs_bits * 2));
340 int n = 0;
341 int final = 0;
343 if (i_block < 0) {
344 ext4_warning(inode->i_sb, "ext4_block_to_path", "block < 0");
345 } else if (i_block < direct_blocks) {
346 offsets[n++] = i_block;
347 final = direct_blocks;
348 } else if ((i_block -= direct_blocks) < indirect_blocks) {
349 offsets[n++] = EXT4_IND_BLOCK;
350 offsets[n++] = i_block;
351 final = ptrs;
352 } else if ((i_block -= indirect_blocks) < double_blocks) {
353 offsets[n++] = EXT4_DIND_BLOCK;
354 offsets[n++] = i_block >> ptrs_bits;
355 offsets[n++] = i_block & (ptrs - 1);
356 final = ptrs;
357 } else if (((i_block -= double_blocks) >> (ptrs_bits * 2)) < ptrs) {
358 offsets[n++] = EXT4_TIND_BLOCK;
359 offsets[n++] = i_block >> (ptrs_bits * 2);
360 offsets[n++] = (i_block >> ptrs_bits) & (ptrs - 1);
361 offsets[n++] = i_block & (ptrs - 1);
362 final = ptrs;
363 } else {
364 ext4_warning(inode->i_sb, "ext4_block_to_path",
365 "block %lu > max in inode %lu",
366 i_block + direct_blocks +
367 indirect_blocks + double_blocks, inode->i_ino);
369 if (boundary)
370 *boundary = final - 1 - (i_block & (ptrs - 1));
371 return n;
375 * ext4_get_branch - read the chain of indirect blocks leading to data
376 * @inode: inode in question
377 * @depth: depth of the chain (1 - direct pointer, etc.)
378 * @offsets: offsets of pointers in inode/indirect blocks
379 * @chain: place to store the result
380 * @err: here we store the error value
382 * Function fills the array of triples <key, p, bh> and returns %NULL
383 * if everything went OK or the pointer to the last filled triple
384 * (incomplete one) otherwise. Upon the return chain[i].key contains
385 * the number of (i+1)-th block in the chain (as it is stored in memory,
386 * i.e. little-endian 32-bit), chain[i].p contains the address of that
387 * number (it points into struct inode for i==0 and into the bh->b_data
388 * for i>0) and chain[i].bh points to the buffer_head of i-th indirect
389 * block for i>0 and NULL for i==0. In other words, it holds the block
390 * numbers of the chain, addresses they were taken from (and where we can
391 * verify that chain did not change) and buffer_heads hosting these
392 * numbers.
394 * Function stops when it stumbles upon zero pointer (absent block)
395 * (pointer to last triple returned, *@err == 0)
396 * or when it gets an IO error reading an indirect block
397 * (ditto, *@err == -EIO)
398 * or when it reads all @depth-1 indirect blocks successfully and finds
399 * the whole chain, all way to the data (returns %NULL, *err == 0).
401 * Need to be called with
402 * down_read(&EXT4_I(inode)->i_data_sem)
404 static Indirect *ext4_get_branch(struct inode *inode, int depth,
405 ext4_lblk_t *offsets,
406 Indirect chain[4], int *err)
408 struct super_block *sb = inode->i_sb;
409 Indirect *p = chain;
410 struct buffer_head *bh;
412 *err = 0;
413 /* i_data is not going away, no lock needed */
414 add_chain(chain, NULL, EXT4_I(inode)->i_data + *offsets);
415 if (!p->key)
416 goto no_block;
417 while (--depth) {
418 bh = sb_bread(sb, le32_to_cpu(p->key));
419 if (!bh)
420 goto failure;
421 add_chain(++p, bh, (__le32 *)bh->b_data + *++offsets);
422 /* Reader: end */
423 if (!p->key)
424 goto no_block;
426 return NULL;
428 failure:
429 *err = -EIO;
430 no_block:
431 return p;
435 * ext4_find_near - find a place for allocation with sufficient locality
436 * @inode: owner
437 * @ind: descriptor of indirect block.
439 * This function returns the preferred place for block allocation.
440 * It is used when heuristic for sequential allocation fails.
441 * Rules are:
442 * + if there is a block to the left of our position - allocate near it.
443 * + if pointer will live in indirect block - allocate near that block.
444 * + if pointer will live in inode - allocate in the same
445 * cylinder group.
447 * In the latter case we colour the starting block by the callers PID to
448 * prevent it from clashing with concurrent allocations for a different inode
449 * in the same block group. The PID is used here so that functionally related
450 * files will be close-by on-disk.
452 * Caller must make sure that @ind is valid and will stay that way.
454 static ext4_fsblk_t ext4_find_near(struct inode *inode, Indirect *ind)
456 struct ext4_inode_info *ei = EXT4_I(inode);
457 __le32 *start = ind->bh ? (__le32 *) ind->bh->b_data : ei->i_data;
458 __le32 *p;
459 ext4_fsblk_t bg_start;
460 ext4_fsblk_t last_block;
461 ext4_grpblk_t colour;
463 /* Try to find previous block */
464 for (p = ind->p - 1; p >= start; p--) {
465 if (*p)
466 return le32_to_cpu(*p);
469 /* No such thing, so let's try location of indirect block */
470 if (ind->bh)
471 return ind->bh->b_blocknr;
474 * It is going to be referred to from the inode itself? OK, just put it
475 * into the same cylinder group then.
477 bg_start = ext4_group_first_block_no(inode->i_sb, ei->i_block_group);
478 last_block = ext4_blocks_count(EXT4_SB(inode->i_sb)->s_es) - 1;
480 if (bg_start + EXT4_BLOCKS_PER_GROUP(inode->i_sb) <= last_block)
481 colour = (current->pid % 16) *
482 (EXT4_BLOCKS_PER_GROUP(inode->i_sb) / 16);
483 else
484 colour = (current->pid % 16) * ((last_block - bg_start) / 16);
485 return bg_start + colour;
489 * ext4_find_goal - find a preferred place for allocation.
490 * @inode: owner
491 * @block: block we want
492 * @partial: pointer to the last triple within a chain
494 * Normally this function find the preferred place for block allocation,
495 * returns it.
497 static ext4_fsblk_t ext4_find_goal(struct inode *inode, ext4_lblk_t block,
498 Indirect *partial)
501 * XXX need to get goal block from mballoc's data structures
504 return ext4_find_near(inode, partial);
508 * ext4_blks_to_allocate: Look up the block map and count the number
509 * of direct blocks need to be allocated for the given branch.
511 * @branch: chain of indirect blocks
512 * @k: number of blocks need for indirect blocks
513 * @blks: number of data blocks to be mapped.
514 * @blocks_to_boundary: the offset in the indirect block
516 * return the total number of blocks to be allocate, including the
517 * direct and indirect blocks.
519 static int ext4_blks_to_allocate(Indirect *branch, int k, unsigned int blks,
520 int blocks_to_boundary)
522 unsigned int count = 0;
525 * Simple case, [t,d]Indirect block(s) has not allocated yet
526 * then it's clear blocks on that path have not allocated
528 if (k > 0) {
529 /* right now we don't handle cross boundary allocation */
530 if (blks < blocks_to_boundary + 1)
531 count += blks;
532 else
533 count += blocks_to_boundary + 1;
534 return count;
537 count++;
538 while (count < blks && count <= blocks_to_boundary &&
539 le32_to_cpu(*(branch[0].p + count)) == 0) {
540 count++;
542 return count;
546 * ext4_alloc_blocks: multiple allocate blocks needed for a branch
547 * @indirect_blks: the number of blocks need to allocate for indirect
548 * blocks
550 * @new_blocks: on return it will store the new block numbers for
551 * the indirect blocks(if needed) and the first direct block,
552 * @blks: on return it will store the total number of allocated
553 * direct blocks
555 static int ext4_alloc_blocks(handle_t *handle, struct inode *inode,
556 ext4_lblk_t iblock, ext4_fsblk_t goal,
557 int indirect_blks, int blks,
558 ext4_fsblk_t new_blocks[4], int *err)
560 struct ext4_allocation_request ar;
561 int target, i;
562 unsigned long count = 0, blk_allocated = 0;
563 int index = 0;
564 ext4_fsblk_t current_block = 0;
565 int ret = 0;
568 * Here we try to allocate the requested multiple blocks at once,
569 * on a best-effort basis.
570 * To build a branch, we should allocate blocks for
571 * the indirect blocks(if not allocated yet), and at least
572 * the first direct block of this branch. That's the
573 * minimum number of blocks need to allocate(required)
575 /* first we try to allocate the indirect blocks */
576 target = indirect_blks;
577 while (target > 0) {
578 count = target;
579 /* allocating blocks for indirect blocks and direct blocks */
580 current_block = ext4_new_meta_blocks(handle, inode,
581 goal, &count, err);
582 if (*err)
583 goto failed_out;
585 target -= count;
586 /* allocate blocks for indirect blocks */
587 while (index < indirect_blks && count) {
588 new_blocks[index++] = current_block++;
589 count--;
591 if (count > 0) {
593 * save the new block number
594 * for the first direct block
596 new_blocks[index] = current_block;
597 printk(KERN_INFO "%s returned more blocks than "
598 "requested\n", __func__);
599 WARN_ON(1);
600 break;
604 target = blks - count ;
605 blk_allocated = count;
606 if (!target)
607 goto allocated;
608 /* Now allocate data blocks */
609 memset(&ar, 0, sizeof(ar));
610 ar.inode = inode;
611 ar.goal = goal;
612 ar.len = target;
613 ar.logical = iblock;
614 if (S_ISREG(inode->i_mode))
615 /* enable in-core preallocation only for regular files */
616 ar.flags = EXT4_MB_HINT_DATA;
618 current_block = ext4_mb_new_blocks(handle, &ar, err);
620 if (*err && (target == blks)) {
622 * if the allocation failed and we didn't allocate
623 * any blocks before
625 goto failed_out;
627 if (!*err) {
628 if (target == blks) {
630 * save the new block number
631 * for the first direct block
633 new_blocks[index] = current_block;
635 blk_allocated += ar.len;
637 allocated:
638 /* total number of blocks allocated for direct blocks */
639 ret = blk_allocated;
640 *err = 0;
641 return ret;
642 failed_out:
643 for (i = 0; i < index; i++)
644 ext4_free_blocks(handle, inode, new_blocks[i], 1, 0);
645 return ret;
649 * ext4_alloc_branch - allocate and set up a chain of blocks.
650 * @inode: owner
651 * @indirect_blks: number of allocated indirect blocks
652 * @blks: number of allocated direct blocks
653 * @offsets: offsets (in the blocks) to store the pointers to next.
654 * @branch: place to store the chain in.
656 * This function allocates blocks, zeroes out all but the last one,
657 * links them into chain and (if we are synchronous) writes them to disk.
658 * In other words, it prepares a branch that can be spliced onto the
659 * inode. It stores the information about that chain in the branch[], in
660 * the same format as ext4_get_branch() would do. We are calling it after
661 * we had read the existing part of chain and partial points to the last
662 * triple of that (one with zero ->key). Upon the exit we have the same
663 * picture as after the successful ext4_get_block(), except that in one
664 * place chain is disconnected - *branch->p is still zero (we did not
665 * set the last link), but branch->key contains the number that should
666 * be placed into *branch->p to fill that gap.
668 * If allocation fails we free all blocks we've allocated (and forget
669 * their buffer_heads) and return the error value the from failed
670 * ext4_alloc_block() (normally -ENOSPC). Otherwise we set the chain
671 * as described above and return 0.
673 static int ext4_alloc_branch(handle_t *handle, struct inode *inode,
674 ext4_lblk_t iblock, int indirect_blks,
675 int *blks, ext4_fsblk_t goal,
676 ext4_lblk_t *offsets, Indirect *branch)
678 int blocksize = inode->i_sb->s_blocksize;
679 int i, n = 0;
680 int err = 0;
681 struct buffer_head *bh;
682 int num;
683 ext4_fsblk_t new_blocks[4];
684 ext4_fsblk_t current_block;
686 num = ext4_alloc_blocks(handle, inode, iblock, goal, indirect_blks,
687 *blks, new_blocks, &err);
688 if (err)
689 return err;
691 branch[0].key = cpu_to_le32(new_blocks[0]);
693 * metadata blocks and data blocks are allocated.
695 for (n = 1; n <= indirect_blks; n++) {
697 * Get buffer_head for parent block, zero it out
698 * and set the pointer to new one, then send
699 * parent to disk.
701 bh = sb_getblk(inode->i_sb, new_blocks[n-1]);
702 branch[n].bh = bh;
703 lock_buffer(bh);
704 BUFFER_TRACE(bh, "call get_create_access");
705 err = ext4_journal_get_create_access(handle, bh);
706 if (err) {
707 unlock_buffer(bh);
708 brelse(bh);
709 goto failed;
712 memset(bh->b_data, 0, blocksize);
713 branch[n].p = (__le32 *) bh->b_data + offsets[n];
714 branch[n].key = cpu_to_le32(new_blocks[n]);
715 *branch[n].p = branch[n].key;
716 if (n == indirect_blks) {
717 current_block = new_blocks[n];
719 * End of chain, update the last new metablock of
720 * the chain to point to the new allocated
721 * data blocks numbers
723 for (i=1; i < num; i++)
724 *(branch[n].p + i) = cpu_to_le32(++current_block);
726 BUFFER_TRACE(bh, "marking uptodate");
727 set_buffer_uptodate(bh);
728 unlock_buffer(bh);
730 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
731 err = ext4_handle_dirty_metadata(handle, inode, bh);
732 if (err)
733 goto failed;
735 *blks = num;
736 return err;
737 failed:
738 /* Allocation failed, free what we already allocated */
739 for (i = 1; i <= n ; i++) {
740 BUFFER_TRACE(branch[i].bh, "call jbd2_journal_forget");
741 ext4_journal_forget(handle, branch[i].bh);
743 for (i = 0; i < indirect_blks; i++)
744 ext4_free_blocks(handle, inode, new_blocks[i], 1, 0);
746 ext4_free_blocks(handle, inode, new_blocks[i], num, 0);
748 return err;
752 * ext4_splice_branch - splice the allocated branch onto inode.
753 * @inode: owner
754 * @block: (logical) number of block we are adding
755 * @chain: chain of indirect blocks (with a missing link - see
756 * ext4_alloc_branch)
757 * @where: location of missing link
758 * @num: number of indirect blocks we are adding
759 * @blks: number of direct blocks we are adding
761 * This function fills the missing link and does all housekeeping needed in
762 * inode (->i_blocks, etc.). In case of success we end up with the full
763 * chain to new block and return 0.
765 static int ext4_splice_branch(handle_t *handle, struct inode *inode,
766 ext4_lblk_t block, Indirect *where, int num, int blks)
768 int i;
769 int err = 0;
770 ext4_fsblk_t current_block;
773 * If we're splicing into a [td]indirect block (as opposed to the
774 * inode) then we need to get write access to the [td]indirect block
775 * before the splice.
777 if (where->bh) {
778 BUFFER_TRACE(where->bh, "get_write_access");
779 err = ext4_journal_get_write_access(handle, where->bh);
780 if (err)
781 goto err_out;
783 /* That's it */
785 *where->p = where->key;
788 * Update the host buffer_head or inode to point to more just allocated
789 * direct blocks blocks
791 if (num == 0 && blks > 1) {
792 current_block = le32_to_cpu(where->key) + 1;
793 for (i = 1; i < blks; i++)
794 *(where->p + i) = cpu_to_le32(current_block++);
797 /* We are done with atomic stuff, now do the rest of housekeeping */
799 inode->i_ctime = ext4_current_time(inode);
800 ext4_mark_inode_dirty(handle, inode);
802 /* had we spliced it onto indirect block? */
803 if (where->bh) {
805 * If we spliced it onto an indirect block, we haven't
806 * altered the inode. Note however that if it is being spliced
807 * onto an indirect block at the very end of the file (the
808 * file is growing) then we *will* alter the inode to reflect
809 * the new i_size. But that is not done here - it is done in
810 * generic_commit_write->__mark_inode_dirty->ext4_dirty_inode.
812 jbd_debug(5, "splicing indirect only\n");
813 BUFFER_TRACE(where->bh, "call ext4_handle_dirty_metadata");
814 err = ext4_handle_dirty_metadata(handle, inode, where->bh);
815 if (err)
816 goto err_out;
817 } else {
819 * OK, we spliced it into the inode itself on a direct block.
820 * Inode was dirtied above.
822 jbd_debug(5, "splicing direct\n");
824 return err;
826 err_out:
827 for (i = 1; i <= num; i++) {
828 BUFFER_TRACE(where[i].bh, "call jbd2_journal_forget");
829 ext4_journal_forget(handle, where[i].bh);
830 ext4_free_blocks(handle, inode,
831 le32_to_cpu(where[i-1].key), 1, 0);
833 ext4_free_blocks(handle, inode, le32_to_cpu(where[num].key), blks, 0);
835 return err;
839 * Allocation strategy is simple: if we have to allocate something, we will
840 * have to go the whole way to leaf. So let's do it before attaching anything
841 * to tree, set linkage between the newborn blocks, write them if sync is
842 * required, recheck the path, free and repeat if check fails, otherwise
843 * set the last missing link (that will protect us from any truncate-generated
844 * removals - all blocks on the path are immune now) and possibly force the
845 * write on the parent block.
846 * That has a nice additional property: no special recovery from the failed
847 * allocations is needed - we simply release blocks and do not touch anything
848 * reachable from inode.
850 * `handle' can be NULL if create == 0.
852 * return > 0, # of blocks mapped or allocated.
853 * return = 0, if plain lookup failed.
854 * return < 0, error case.
857 * Need to be called with
858 * down_read(&EXT4_I(inode)->i_data_sem) if not allocating file system block
859 * (ie, create is zero). Otherwise down_write(&EXT4_I(inode)->i_data_sem)
861 static int ext4_get_blocks_handle(handle_t *handle, struct inode *inode,
862 ext4_lblk_t iblock, unsigned int maxblocks,
863 struct buffer_head *bh_result,
864 int create, int extend_disksize)
866 int err = -EIO;
867 ext4_lblk_t offsets[4];
868 Indirect chain[4];
869 Indirect *partial;
870 ext4_fsblk_t goal;
871 int indirect_blks;
872 int blocks_to_boundary = 0;
873 int depth;
874 struct ext4_inode_info *ei = EXT4_I(inode);
875 int count = 0;
876 ext4_fsblk_t first_block = 0;
877 loff_t disksize;
880 J_ASSERT(!(EXT4_I(inode)->i_flags & EXT4_EXTENTS_FL));
881 J_ASSERT(handle != NULL || create == 0);
882 depth = ext4_block_to_path(inode, iblock, offsets,
883 &blocks_to_boundary);
885 if (depth == 0)
886 goto out;
888 partial = ext4_get_branch(inode, depth, offsets, chain, &err);
890 /* Simplest case - block found, no allocation needed */
891 if (!partial) {
892 first_block = le32_to_cpu(chain[depth - 1].key);
893 clear_buffer_new(bh_result);
894 count++;
895 /*map more blocks*/
896 while (count < maxblocks && count <= blocks_to_boundary) {
897 ext4_fsblk_t blk;
899 blk = le32_to_cpu(*(chain[depth-1].p + count));
901 if (blk == first_block + count)
902 count++;
903 else
904 break;
906 goto got_it;
909 /* Next simple case - plain lookup or failed read of indirect block */
910 if (!create || err == -EIO)
911 goto cleanup;
914 * Okay, we need to do block allocation.
916 goal = ext4_find_goal(inode, iblock, partial);
918 /* the number of blocks need to allocate for [d,t]indirect blocks */
919 indirect_blks = (chain + depth) - partial - 1;
922 * Next look up the indirect map to count the totoal number of
923 * direct blocks to allocate for this branch.
925 count = ext4_blks_to_allocate(partial, indirect_blks,
926 maxblocks, blocks_to_boundary);
928 * Block out ext4_truncate while we alter the tree
930 err = ext4_alloc_branch(handle, inode, iblock, indirect_blks,
931 &count, goal,
932 offsets + (partial - chain), partial);
935 * The ext4_splice_branch call will free and forget any buffers
936 * on the new chain if there is a failure, but that risks using
937 * up transaction credits, especially for bitmaps where the
938 * credits cannot be returned. Can we handle this somehow? We
939 * may need to return -EAGAIN upwards in the worst case. --sct
941 if (!err)
942 err = ext4_splice_branch(handle, inode, iblock,
943 partial, indirect_blks, count);
945 * i_disksize growing is protected by i_data_sem. Don't forget to
946 * protect it if you're about to implement concurrent
947 * ext4_get_block() -bzzz
949 if (!err && extend_disksize) {
950 disksize = ((loff_t) iblock + count) << inode->i_blkbits;
951 if (disksize > i_size_read(inode))
952 disksize = i_size_read(inode);
953 if (disksize > ei->i_disksize)
954 ei->i_disksize = disksize;
956 if (err)
957 goto cleanup;
959 set_buffer_new(bh_result);
960 got_it:
961 map_bh(bh_result, inode->i_sb, le32_to_cpu(chain[depth-1].key));
962 if (count > blocks_to_boundary)
963 set_buffer_boundary(bh_result);
964 err = count;
965 /* Clean up and exit */
966 partial = chain + depth - 1; /* the whole chain */
967 cleanup:
968 while (partial > chain) {
969 BUFFER_TRACE(partial->bh, "call brelse");
970 brelse(partial->bh);
971 partial--;
973 BUFFER_TRACE(bh_result, "returned");
974 out:
975 return err;
979 * Calculate the number of metadata blocks need to reserve
980 * to allocate @blocks for non extent file based file
982 static int ext4_indirect_calc_metadata_amount(struct inode *inode, int blocks)
984 int icap = EXT4_ADDR_PER_BLOCK(inode->i_sb);
985 int ind_blks, dind_blks, tind_blks;
987 /* number of new indirect blocks needed */
988 ind_blks = (blocks + icap - 1) / icap;
990 dind_blks = (ind_blks + icap - 1) / icap;
992 tind_blks = 1;
994 return ind_blks + dind_blks + tind_blks;
998 * Calculate the number of metadata blocks need to reserve
999 * to allocate given number of blocks
1001 static int ext4_calc_metadata_amount(struct inode *inode, int blocks)
1003 if (!blocks)
1004 return 0;
1006 if (EXT4_I(inode)->i_flags & EXT4_EXTENTS_FL)
1007 return ext4_ext_calc_metadata_amount(inode, blocks);
1009 return ext4_indirect_calc_metadata_amount(inode, blocks);
1012 static void ext4_da_update_reserve_space(struct inode *inode, int used)
1014 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1015 int total, mdb, mdb_free;
1017 spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
1018 /* recalculate the number of metablocks still need to be reserved */
1019 total = EXT4_I(inode)->i_reserved_data_blocks - used;
1020 mdb = ext4_calc_metadata_amount(inode, total);
1022 /* figure out how many metablocks to release */
1023 BUG_ON(mdb > EXT4_I(inode)->i_reserved_meta_blocks);
1024 mdb_free = EXT4_I(inode)->i_reserved_meta_blocks - mdb;
1026 if (mdb_free) {
1027 /* Account for allocated meta_blocks */
1028 mdb_free -= EXT4_I(inode)->i_allocated_meta_blocks;
1030 /* update fs dirty blocks counter */
1031 percpu_counter_sub(&sbi->s_dirtyblocks_counter, mdb_free);
1032 EXT4_I(inode)->i_allocated_meta_blocks = 0;
1033 EXT4_I(inode)->i_reserved_meta_blocks = mdb;
1036 /* update per-inode reservations */
1037 BUG_ON(used > EXT4_I(inode)->i_reserved_data_blocks);
1038 EXT4_I(inode)->i_reserved_data_blocks -= used;
1039 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
1042 * If we have done all the pending block allocations and if
1043 * there aren't any writers on the inode, we can discard the
1044 * inode's preallocations.
1046 if (!total && (atomic_read(&inode->i_writecount) == 0))
1047 ext4_discard_preallocations(inode);
1051 * The ext4_get_blocks_wrap() function try to look up the requested blocks,
1052 * and returns if the blocks are already mapped.
1054 * Otherwise it takes the write lock of the i_data_sem and allocate blocks
1055 * and store the allocated blocks in the result buffer head and mark it
1056 * mapped.
1058 * If file type is extents based, it will call ext4_ext_get_blocks(),
1059 * Otherwise, call with ext4_get_blocks_handle() to handle indirect mapping
1060 * based files
1062 * On success, it returns the number of blocks being mapped or allocate.
1063 * if create==0 and the blocks are pre-allocated and uninitialized block,
1064 * the result buffer head is unmapped. If the create ==1, it will make sure
1065 * the buffer head is mapped.
1067 * It returns 0 if plain look up failed (blocks have not been allocated), in
1068 * that casem, buffer head is unmapped
1070 * It returns the error in case of allocation failure.
1072 int ext4_get_blocks_wrap(handle_t *handle, struct inode *inode, sector_t block,
1073 unsigned int max_blocks, struct buffer_head *bh,
1074 int create, int extend_disksize, int flag)
1076 int retval;
1078 clear_buffer_mapped(bh);
1081 * Try to see if we can get the block without requesting
1082 * for new file system block.
1084 down_read((&EXT4_I(inode)->i_data_sem));
1085 if (EXT4_I(inode)->i_flags & EXT4_EXTENTS_FL) {
1086 retval = ext4_ext_get_blocks(handle, inode, block, max_blocks,
1087 bh, 0, 0);
1088 } else {
1089 retval = ext4_get_blocks_handle(handle,
1090 inode, block, max_blocks, bh, 0, 0);
1092 up_read((&EXT4_I(inode)->i_data_sem));
1094 /* If it is only a block(s) look up */
1095 if (!create)
1096 return retval;
1099 * Returns if the blocks have already allocated
1101 * Note that if blocks have been preallocated
1102 * ext4_ext_get_block() returns th create = 0
1103 * with buffer head unmapped.
1105 if (retval > 0 && buffer_mapped(bh))
1106 return retval;
1109 * New blocks allocate and/or writing to uninitialized extent
1110 * will possibly result in updating i_data, so we take
1111 * the write lock of i_data_sem, and call get_blocks()
1112 * with create == 1 flag.
1114 down_write((&EXT4_I(inode)->i_data_sem));
1117 * if the caller is from delayed allocation writeout path
1118 * we have already reserved fs blocks for allocation
1119 * let the underlying get_block() function know to
1120 * avoid double accounting
1122 if (flag)
1123 EXT4_I(inode)->i_delalloc_reserved_flag = 1;
1125 * We need to check for EXT4 here because migrate
1126 * could have changed the inode type in between
1128 if (EXT4_I(inode)->i_flags & EXT4_EXTENTS_FL) {
1129 retval = ext4_ext_get_blocks(handle, inode, block, max_blocks,
1130 bh, create, extend_disksize);
1131 } else {
1132 retval = ext4_get_blocks_handle(handle, inode, block,
1133 max_blocks, bh, create, extend_disksize);
1135 if (retval > 0 && buffer_new(bh)) {
1137 * We allocated new blocks which will result in
1138 * i_data's format changing. Force the migrate
1139 * to fail by clearing migrate flags
1141 EXT4_I(inode)->i_flags = EXT4_I(inode)->i_flags &
1142 ~EXT4_EXT_MIGRATE;
1146 if (flag) {
1147 EXT4_I(inode)->i_delalloc_reserved_flag = 0;
1149 * Update reserved blocks/metadata blocks
1150 * after successful block allocation
1151 * which were deferred till now
1153 if ((retval > 0) && buffer_delay(bh))
1154 ext4_da_update_reserve_space(inode, retval);
1157 up_write((&EXT4_I(inode)->i_data_sem));
1158 return retval;
1161 /* Maximum number of blocks we map for direct IO at once. */
1162 #define DIO_MAX_BLOCKS 4096
1164 int ext4_get_block(struct inode *inode, sector_t iblock,
1165 struct buffer_head *bh_result, int create)
1167 handle_t *handle = ext4_journal_current_handle();
1168 int ret = 0, started = 0;
1169 unsigned max_blocks = bh_result->b_size >> inode->i_blkbits;
1170 int dio_credits;
1172 if (create && !handle) {
1173 /* Direct IO write... */
1174 if (max_blocks > DIO_MAX_BLOCKS)
1175 max_blocks = DIO_MAX_BLOCKS;
1176 dio_credits = ext4_chunk_trans_blocks(inode, max_blocks);
1177 handle = ext4_journal_start(inode, dio_credits);
1178 if (IS_ERR(handle)) {
1179 ret = PTR_ERR(handle);
1180 goto out;
1182 started = 1;
1185 ret = ext4_get_blocks_wrap(handle, inode, iblock,
1186 max_blocks, bh_result, create, 0, 0);
1187 if (ret > 0) {
1188 bh_result->b_size = (ret << inode->i_blkbits);
1189 ret = 0;
1191 if (started)
1192 ext4_journal_stop(handle);
1193 out:
1194 return ret;
1198 * `handle' can be NULL if create is zero
1200 struct buffer_head *ext4_getblk(handle_t *handle, struct inode *inode,
1201 ext4_lblk_t block, int create, int *errp)
1203 struct buffer_head dummy;
1204 int fatal = 0, err;
1206 J_ASSERT(handle != NULL || create == 0);
1208 dummy.b_state = 0;
1209 dummy.b_blocknr = -1000;
1210 buffer_trace_init(&dummy.b_history);
1211 err = ext4_get_blocks_wrap(handle, inode, block, 1,
1212 &dummy, create, 1, 0);
1214 * ext4_get_blocks_handle() returns number of blocks
1215 * mapped. 0 in case of a HOLE.
1217 if (err > 0) {
1218 if (err > 1)
1219 WARN_ON(1);
1220 err = 0;
1222 *errp = err;
1223 if (!err && buffer_mapped(&dummy)) {
1224 struct buffer_head *bh;
1225 bh = sb_getblk(inode->i_sb, dummy.b_blocknr);
1226 if (!bh) {
1227 *errp = -EIO;
1228 goto err;
1230 if (buffer_new(&dummy)) {
1231 J_ASSERT(create != 0);
1232 J_ASSERT(handle != NULL);
1235 * Now that we do not always journal data, we should
1236 * keep in mind whether this should always journal the
1237 * new buffer as metadata. For now, regular file
1238 * writes use ext4_get_block instead, so it's not a
1239 * problem.
1241 lock_buffer(bh);
1242 BUFFER_TRACE(bh, "call get_create_access");
1243 fatal = ext4_journal_get_create_access(handle, bh);
1244 if (!fatal && !buffer_uptodate(bh)) {
1245 memset(bh->b_data, 0, inode->i_sb->s_blocksize);
1246 set_buffer_uptodate(bh);
1248 unlock_buffer(bh);
1249 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
1250 err = ext4_handle_dirty_metadata(handle, inode, bh);
1251 if (!fatal)
1252 fatal = err;
1253 } else {
1254 BUFFER_TRACE(bh, "not a new buffer");
1256 if (fatal) {
1257 *errp = fatal;
1258 brelse(bh);
1259 bh = NULL;
1261 return bh;
1263 err:
1264 return NULL;
1267 struct buffer_head *ext4_bread(handle_t *handle, struct inode *inode,
1268 ext4_lblk_t block, int create, int *err)
1270 struct buffer_head *bh;
1272 bh = ext4_getblk(handle, inode, block, create, err);
1273 if (!bh)
1274 return bh;
1275 if (buffer_uptodate(bh))
1276 return bh;
1277 ll_rw_block(READ_META, 1, &bh);
1278 wait_on_buffer(bh);
1279 if (buffer_uptodate(bh))
1280 return bh;
1281 put_bh(bh);
1282 *err = -EIO;
1283 return NULL;
1286 static int walk_page_buffers(handle_t *handle,
1287 struct buffer_head *head,
1288 unsigned from,
1289 unsigned to,
1290 int *partial,
1291 int (*fn)(handle_t *handle,
1292 struct buffer_head *bh))
1294 struct buffer_head *bh;
1295 unsigned block_start, block_end;
1296 unsigned blocksize = head->b_size;
1297 int err, ret = 0;
1298 struct buffer_head *next;
1300 for (bh = head, block_start = 0;
1301 ret == 0 && (bh != head || !block_start);
1302 block_start = block_end, bh = next)
1304 next = bh->b_this_page;
1305 block_end = block_start + blocksize;
1306 if (block_end <= from || block_start >= to) {
1307 if (partial && !buffer_uptodate(bh))
1308 *partial = 1;
1309 continue;
1311 err = (*fn)(handle, bh);
1312 if (!ret)
1313 ret = err;
1315 return ret;
1319 * To preserve ordering, it is essential that the hole instantiation and
1320 * the data write be encapsulated in a single transaction. We cannot
1321 * close off a transaction and start a new one between the ext4_get_block()
1322 * and the commit_write(). So doing the jbd2_journal_start at the start of
1323 * prepare_write() is the right place.
1325 * Also, this function can nest inside ext4_writepage() ->
1326 * block_write_full_page(). In that case, we *know* that ext4_writepage()
1327 * has generated enough buffer credits to do the whole page. So we won't
1328 * block on the journal in that case, which is good, because the caller may
1329 * be PF_MEMALLOC.
1331 * By accident, ext4 can be reentered when a transaction is open via
1332 * quota file writes. If we were to commit the transaction while thus
1333 * reentered, there can be a deadlock - we would be holding a quota
1334 * lock, and the commit would never complete if another thread had a
1335 * transaction open and was blocking on the quota lock - a ranking
1336 * violation.
1338 * So what we do is to rely on the fact that jbd2_journal_stop/journal_start
1339 * will _not_ run commit under these circumstances because handle->h_ref
1340 * is elevated. We'll still have enough credits for the tiny quotafile
1341 * write.
1343 static int do_journal_get_write_access(handle_t *handle,
1344 struct buffer_head *bh)
1346 if (!buffer_mapped(bh) || buffer_freed(bh))
1347 return 0;
1348 return ext4_journal_get_write_access(handle, bh);
1351 static int ext4_write_begin(struct file *file, struct address_space *mapping,
1352 loff_t pos, unsigned len, unsigned flags,
1353 struct page **pagep, void **fsdata)
1355 struct inode *inode = mapping->host;
1356 int ret, needed_blocks = ext4_writepage_trans_blocks(inode);
1357 handle_t *handle;
1358 int retries = 0;
1359 struct page *page;
1360 pgoff_t index;
1361 unsigned from, to;
1363 trace_mark(ext4_write_begin,
1364 "dev %s ino %lu pos %llu len %u flags %u",
1365 inode->i_sb->s_id, inode->i_ino,
1366 (unsigned long long) pos, len, flags);
1367 index = pos >> PAGE_CACHE_SHIFT;
1368 from = pos & (PAGE_CACHE_SIZE - 1);
1369 to = from + len;
1371 retry:
1372 handle = ext4_journal_start(inode, needed_blocks);
1373 if (IS_ERR(handle)) {
1374 ret = PTR_ERR(handle);
1375 goto out;
1378 /* We cannot recurse into the filesystem as the transaction is already
1379 * started */
1380 flags |= AOP_FLAG_NOFS;
1382 page = grab_cache_page_write_begin(mapping, index, flags);
1383 if (!page) {
1384 ext4_journal_stop(handle);
1385 ret = -ENOMEM;
1386 goto out;
1388 *pagep = page;
1390 ret = block_write_begin(file, mapping, pos, len, flags, pagep, fsdata,
1391 ext4_get_block);
1393 if (!ret && ext4_should_journal_data(inode)) {
1394 ret = walk_page_buffers(handle, page_buffers(page),
1395 from, to, NULL, do_journal_get_write_access);
1398 if (ret) {
1399 unlock_page(page);
1400 ext4_journal_stop(handle);
1401 page_cache_release(page);
1403 * block_write_begin may have instantiated a few blocks
1404 * outside i_size. Trim these off again. Don't need
1405 * i_size_read because we hold i_mutex.
1407 if (pos + len > inode->i_size)
1408 vmtruncate(inode, inode->i_size);
1411 if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
1412 goto retry;
1413 out:
1414 return ret;
1417 /* For write_end() in data=journal mode */
1418 static int write_end_fn(handle_t *handle, struct buffer_head *bh)
1420 if (!buffer_mapped(bh) || buffer_freed(bh))
1421 return 0;
1422 set_buffer_uptodate(bh);
1423 return ext4_handle_dirty_metadata(handle, NULL, bh);
1427 * We need to pick up the new inode size which generic_commit_write gave us
1428 * `file' can be NULL - eg, when called from page_symlink().
1430 * ext4 never places buffers on inode->i_mapping->private_list. metadata
1431 * buffers are managed internally.
1433 static int ext4_ordered_write_end(struct file *file,
1434 struct address_space *mapping,
1435 loff_t pos, unsigned len, unsigned copied,
1436 struct page *page, void *fsdata)
1438 handle_t *handle = ext4_journal_current_handle();
1439 struct inode *inode = mapping->host;
1440 int ret = 0, ret2;
1442 trace_mark(ext4_ordered_write_end,
1443 "dev %s ino %lu pos %llu len %u copied %u",
1444 inode->i_sb->s_id, inode->i_ino,
1445 (unsigned long long) pos, len, copied);
1446 ret = ext4_jbd2_file_inode(handle, inode);
1448 if (ret == 0) {
1449 loff_t new_i_size;
1451 new_i_size = pos + copied;
1452 if (new_i_size > EXT4_I(inode)->i_disksize) {
1453 ext4_update_i_disksize(inode, new_i_size);
1454 /* We need to mark inode dirty even if
1455 * new_i_size is less that inode->i_size
1456 * bu greater than i_disksize.(hint delalloc)
1458 ext4_mark_inode_dirty(handle, inode);
1461 ret2 = generic_write_end(file, mapping, pos, len, copied,
1462 page, fsdata);
1463 copied = ret2;
1464 if (ret2 < 0)
1465 ret = ret2;
1467 ret2 = ext4_journal_stop(handle);
1468 if (!ret)
1469 ret = ret2;
1471 return ret ? ret : copied;
1474 static int ext4_writeback_write_end(struct file *file,
1475 struct address_space *mapping,
1476 loff_t pos, unsigned len, unsigned copied,
1477 struct page *page, void *fsdata)
1479 handle_t *handle = ext4_journal_current_handle();
1480 struct inode *inode = mapping->host;
1481 int ret = 0, ret2;
1482 loff_t new_i_size;
1484 trace_mark(ext4_writeback_write_end,
1485 "dev %s ino %lu pos %llu len %u copied %u",
1486 inode->i_sb->s_id, inode->i_ino,
1487 (unsigned long long) pos, len, copied);
1488 new_i_size = pos + copied;
1489 if (new_i_size > EXT4_I(inode)->i_disksize) {
1490 ext4_update_i_disksize(inode, new_i_size);
1491 /* We need to mark inode dirty even if
1492 * new_i_size is less that inode->i_size
1493 * bu greater than i_disksize.(hint delalloc)
1495 ext4_mark_inode_dirty(handle, inode);
1498 ret2 = generic_write_end(file, mapping, pos, len, copied,
1499 page, fsdata);
1500 copied = ret2;
1501 if (ret2 < 0)
1502 ret = ret2;
1504 ret2 = ext4_journal_stop(handle);
1505 if (!ret)
1506 ret = ret2;
1508 return ret ? ret : copied;
1511 static int ext4_journalled_write_end(struct file *file,
1512 struct address_space *mapping,
1513 loff_t pos, unsigned len, unsigned copied,
1514 struct page *page, void *fsdata)
1516 handle_t *handle = ext4_journal_current_handle();
1517 struct inode *inode = mapping->host;
1518 int ret = 0, ret2;
1519 int partial = 0;
1520 unsigned from, to;
1521 loff_t new_i_size;
1523 trace_mark(ext4_journalled_write_end,
1524 "dev %s ino %lu pos %llu len %u copied %u",
1525 inode->i_sb->s_id, inode->i_ino,
1526 (unsigned long long) pos, len, copied);
1527 from = pos & (PAGE_CACHE_SIZE - 1);
1528 to = from + len;
1530 if (copied < len) {
1531 if (!PageUptodate(page))
1532 copied = 0;
1533 page_zero_new_buffers(page, from+copied, to);
1536 ret = walk_page_buffers(handle, page_buffers(page), from,
1537 to, &partial, write_end_fn);
1538 if (!partial)
1539 SetPageUptodate(page);
1540 new_i_size = pos + copied;
1541 if (new_i_size > inode->i_size)
1542 i_size_write(inode, pos+copied);
1543 EXT4_I(inode)->i_state |= EXT4_STATE_JDATA;
1544 if (new_i_size > EXT4_I(inode)->i_disksize) {
1545 ext4_update_i_disksize(inode, new_i_size);
1546 ret2 = ext4_mark_inode_dirty(handle, inode);
1547 if (!ret)
1548 ret = ret2;
1551 unlock_page(page);
1552 ret2 = ext4_journal_stop(handle);
1553 if (!ret)
1554 ret = ret2;
1555 page_cache_release(page);
1557 return ret ? ret : copied;
1560 static int ext4_da_reserve_space(struct inode *inode, int nrblocks)
1562 int retries = 0;
1563 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1564 unsigned long md_needed, mdblocks, total = 0;
1567 * recalculate the amount of metadata blocks to reserve
1568 * in order to allocate nrblocks
1569 * worse case is one extent per block
1571 repeat:
1572 spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
1573 total = EXT4_I(inode)->i_reserved_data_blocks + nrblocks;
1574 mdblocks = ext4_calc_metadata_amount(inode, total);
1575 BUG_ON(mdblocks < EXT4_I(inode)->i_reserved_meta_blocks);
1577 md_needed = mdblocks - EXT4_I(inode)->i_reserved_meta_blocks;
1578 total = md_needed + nrblocks;
1580 if (ext4_claim_free_blocks(sbi, total)) {
1581 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
1582 if (ext4_should_retry_alloc(inode->i_sb, &retries)) {
1583 yield();
1584 goto repeat;
1586 return -ENOSPC;
1588 EXT4_I(inode)->i_reserved_data_blocks += nrblocks;
1589 EXT4_I(inode)->i_reserved_meta_blocks = mdblocks;
1591 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
1592 return 0; /* success */
1595 static void ext4_da_release_space(struct inode *inode, int to_free)
1597 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1598 int total, mdb, mdb_free, release;
1600 if (!to_free)
1601 return; /* Nothing to release, exit */
1603 spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
1605 if (!EXT4_I(inode)->i_reserved_data_blocks) {
1607 * if there is no reserved blocks, but we try to free some
1608 * then the counter is messed up somewhere.
1609 * but since this function is called from invalidate
1610 * page, it's harmless to return without any action
1612 printk(KERN_INFO "ext4 delalloc try to release %d reserved "
1613 "blocks for inode %lu, but there is no reserved "
1614 "data blocks\n", to_free, inode->i_ino);
1615 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
1616 return;
1619 /* recalculate the number of metablocks still need to be reserved */
1620 total = EXT4_I(inode)->i_reserved_data_blocks - to_free;
1621 mdb = ext4_calc_metadata_amount(inode, total);
1623 /* figure out how many metablocks to release */
1624 BUG_ON(mdb > EXT4_I(inode)->i_reserved_meta_blocks);
1625 mdb_free = EXT4_I(inode)->i_reserved_meta_blocks - mdb;
1627 release = to_free + mdb_free;
1629 /* update fs dirty blocks counter for truncate case */
1630 percpu_counter_sub(&sbi->s_dirtyblocks_counter, release);
1632 /* update per-inode reservations */
1633 BUG_ON(to_free > EXT4_I(inode)->i_reserved_data_blocks);
1634 EXT4_I(inode)->i_reserved_data_blocks -= to_free;
1636 BUG_ON(mdb > EXT4_I(inode)->i_reserved_meta_blocks);
1637 EXT4_I(inode)->i_reserved_meta_blocks = mdb;
1638 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
1641 static void ext4_da_page_release_reservation(struct page *page,
1642 unsigned long offset)
1644 int to_release = 0;
1645 struct buffer_head *head, *bh;
1646 unsigned int curr_off = 0;
1648 head = page_buffers(page);
1649 bh = head;
1650 do {
1651 unsigned int next_off = curr_off + bh->b_size;
1653 if ((offset <= curr_off) && (buffer_delay(bh))) {
1654 to_release++;
1655 clear_buffer_delay(bh);
1657 curr_off = next_off;
1658 } while ((bh = bh->b_this_page) != head);
1659 ext4_da_release_space(page->mapping->host, to_release);
1663 * Delayed allocation stuff
1666 struct mpage_da_data {
1667 struct inode *inode;
1668 struct buffer_head lbh; /* extent of blocks */
1669 unsigned long first_page, next_page; /* extent of pages */
1670 get_block_t *get_block;
1671 struct writeback_control *wbc;
1672 int io_done;
1673 int pages_written;
1674 int retval;
1678 * mpage_da_submit_io - walks through extent of pages and try to write
1679 * them with writepage() call back
1681 * @mpd->inode: inode
1682 * @mpd->first_page: first page of the extent
1683 * @mpd->next_page: page after the last page of the extent
1684 * @mpd->get_block: the filesystem's block mapper function
1686 * By the time mpage_da_submit_io() is called we expect all blocks
1687 * to be allocated. this may be wrong if allocation failed.
1689 * As pages are already locked by write_cache_pages(), we can't use it
1691 static int mpage_da_submit_io(struct mpage_da_data *mpd)
1693 long pages_skipped;
1694 struct pagevec pvec;
1695 unsigned long index, end;
1696 int ret = 0, err, nr_pages, i;
1697 struct inode *inode = mpd->inode;
1698 struct address_space *mapping = inode->i_mapping;
1700 BUG_ON(mpd->next_page <= mpd->first_page);
1702 * We need to start from the first_page to the next_page - 1
1703 * to make sure we also write the mapped dirty buffer_heads.
1704 * If we look at mpd->lbh.b_blocknr we would only be looking
1705 * at the currently mapped buffer_heads.
1707 index = mpd->first_page;
1708 end = mpd->next_page - 1;
1710 pagevec_init(&pvec, 0);
1711 while (index <= end) {
1712 nr_pages = pagevec_lookup(&pvec, mapping, index, PAGEVEC_SIZE);
1713 if (nr_pages == 0)
1714 break;
1715 for (i = 0; i < nr_pages; i++) {
1716 struct page *page = pvec.pages[i];
1718 index = page->index;
1719 if (index > end)
1720 break;
1721 index++;
1723 BUG_ON(!PageLocked(page));
1724 BUG_ON(PageWriteback(page));
1726 pages_skipped = mpd->wbc->pages_skipped;
1727 err = mapping->a_ops->writepage(page, mpd->wbc);
1728 if (!err && (pages_skipped == mpd->wbc->pages_skipped))
1730 * have successfully written the page
1731 * without skipping the same
1733 mpd->pages_written++;
1735 * In error case, we have to continue because
1736 * remaining pages are still locked
1737 * XXX: unlock and re-dirty them?
1739 if (ret == 0)
1740 ret = err;
1742 pagevec_release(&pvec);
1744 return ret;
1748 * mpage_put_bnr_to_bhs - walk blocks and assign them actual numbers
1750 * @mpd->inode - inode to walk through
1751 * @exbh->b_blocknr - first block on a disk
1752 * @exbh->b_size - amount of space in bytes
1753 * @logical - first logical block to start assignment with
1755 * the function goes through all passed space and put actual disk
1756 * block numbers into buffer heads, dropping BH_Delay
1758 static void mpage_put_bnr_to_bhs(struct mpage_da_data *mpd, sector_t logical,
1759 struct buffer_head *exbh)
1761 struct inode *inode = mpd->inode;
1762 struct address_space *mapping = inode->i_mapping;
1763 int blocks = exbh->b_size >> inode->i_blkbits;
1764 sector_t pblock = exbh->b_blocknr, cur_logical;
1765 struct buffer_head *head, *bh;
1766 pgoff_t index, end;
1767 struct pagevec pvec;
1768 int nr_pages, i;
1770 index = logical >> (PAGE_CACHE_SHIFT - inode->i_blkbits);
1771 end = (logical + blocks - 1) >> (PAGE_CACHE_SHIFT - inode->i_blkbits);
1772 cur_logical = index << (PAGE_CACHE_SHIFT - inode->i_blkbits);
1774 pagevec_init(&pvec, 0);
1776 while (index <= end) {
1777 /* XXX: optimize tail */
1778 nr_pages = pagevec_lookup(&pvec, mapping, index, PAGEVEC_SIZE);
1779 if (nr_pages == 0)
1780 break;
1781 for (i = 0; i < nr_pages; i++) {
1782 struct page *page = pvec.pages[i];
1784 index = page->index;
1785 if (index > end)
1786 break;
1787 index++;
1789 BUG_ON(!PageLocked(page));
1790 BUG_ON(PageWriteback(page));
1791 BUG_ON(!page_has_buffers(page));
1793 bh = page_buffers(page);
1794 head = bh;
1796 /* skip blocks out of the range */
1797 do {
1798 if (cur_logical >= logical)
1799 break;
1800 cur_logical++;
1801 } while ((bh = bh->b_this_page) != head);
1803 do {
1804 if (cur_logical >= logical + blocks)
1805 break;
1806 if (buffer_delay(bh)) {
1807 bh->b_blocknr = pblock;
1808 clear_buffer_delay(bh);
1809 bh->b_bdev = inode->i_sb->s_bdev;
1810 } else if (buffer_unwritten(bh)) {
1811 bh->b_blocknr = pblock;
1812 clear_buffer_unwritten(bh);
1813 set_buffer_mapped(bh);
1814 set_buffer_new(bh);
1815 bh->b_bdev = inode->i_sb->s_bdev;
1816 } else if (buffer_mapped(bh))
1817 BUG_ON(bh->b_blocknr != pblock);
1819 cur_logical++;
1820 pblock++;
1821 } while ((bh = bh->b_this_page) != head);
1823 pagevec_release(&pvec);
1829 * __unmap_underlying_blocks - just a helper function to unmap
1830 * set of blocks described by @bh
1832 static inline void __unmap_underlying_blocks(struct inode *inode,
1833 struct buffer_head *bh)
1835 struct block_device *bdev = inode->i_sb->s_bdev;
1836 int blocks, i;
1838 blocks = bh->b_size >> inode->i_blkbits;
1839 for (i = 0; i < blocks; i++)
1840 unmap_underlying_metadata(bdev, bh->b_blocknr + i);
1843 static void ext4_da_block_invalidatepages(struct mpage_da_data *mpd,
1844 sector_t logical, long blk_cnt)
1846 int nr_pages, i;
1847 pgoff_t index, end;
1848 struct pagevec pvec;
1849 struct inode *inode = mpd->inode;
1850 struct address_space *mapping = inode->i_mapping;
1852 index = logical >> (PAGE_CACHE_SHIFT - inode->i_blkbits);
1853 end = (logical + blk_cnt - 1) >>
1854 (PAGE_CACHE_SHIFT - inode->i_blkbits);
1855 while (index <= end) {
1856 nr_pages = pagevec_lookup(&pvec, mapping, index, PAGEVEC_SIZE);
1857 if (nr_pages == 0)
1858 break;
1859 for (i = 0; i < nr_pages; i++) {
1860 struct page *page = pvec.pages[i];
1861 index = page->index;
1862 if (index > end)
1863 break;
1864 index++;
1866 BUG_ON(!PageLocked(page));
1867 BUG_ON(PageWriteback(page));
1868 block_invalidatepage(page, 0);
1869 ClearPageUptodate(page);
1870 unlock_page(page);
1873 return;
1876 static void ext4_print_free_blocks(struct inode *inode)
1878 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1879 printk(KERN_EMERG "Total free blocks count %lld\n",
1880 ext4_count_free_blocks(inode->i_sb));
1881 printk(KERN_EMERG "Free/Dirty block details\n");
1882 printk(KERN_EMERG "free_blocks=%lld\n",
1883 (long long)percpu_counter_sum(&sbi->s_freeblocks_counter));
1884 printk(KERN_EMERG "dirty_blocks=%lld\n",
1885 (long long)percpu_counter_sum(&sbi->s_dirtyblocks_counter));
1886 printk(KERN_EMERG "Block reservation details\n");
1887 printk(KERN_EMERG "i_reserved_data_blocks=%u\n",
1888 EXT4_I(inode)->i_reserved_data_blocks);
1889 printk(KERN_EMERG "i_reserved_meta_blocks=%u\n",
1890 EXT4_I(inode)->i_reserved_meta_blocks);
1891 return;
1895 * mpage_da_map_blocks - go through given space
1897 * @mpd->lbh - bh describing space
1898 * @mpd->get_block - the filesystem's block mapper function
1900 * The function skips space we know is already mapped to disk blocks.
1903 static int mpage_da_map_blocks(struct mpage_da_data *mpd)
1905 int err = 0;
1906 struct buffer_head new;
1907 struct buffer_head *lbh = &mpd->lbh;
1908 sector_t next;
1911 * We consider only non-mapped and non-allocated blocks
1913 if (buffer_mapped(lbh) && !buffer_delay(lbh))
1914 return 0;
1915 new.b_state = lbh->b_state;
1916 new.b_blocknr = 0;
1917 new.b_size = lbh->b_size;
1918 next = lbh->b_blocknr;
1920 * If we didn't accumulate anything
1921 * to write simply return
1923 if (!new.b_size)
1924 return 0;
1925 err = mpd->get_block(mpd->inode, next, &new, 1);
1926 if (err) {
1928 /* If get block returns with error
1929 * we simply return. Later writepage
1930 * will redirty the page and writepages
1931 * will find the dirty page again
1933 if (err == -EAGAIN)
1934 return 0;
1936 if (err == -ENOSPC &&
1937 ext4_count_free_blocks(mpd->inode->i_sb)) {
1938 mpd->retval = err;
1939 return 0;
1943 * get block failure will cause us
1944 * to loop in writepages. Because
1945 * a_ops->writepage won't be able to
1946 * make progress. The page will be redirtied
1947 * by writepage and writepages will again
1948 * try to write the same.
1950 printk(KERN_EMERG "%s block allocation failed for inode %lu "
1951 "at logical offset %llu with max blocks "
1952 "%zd with error %d\n",
1953 __func__, mpd->inode->i_ino,
1954 (unsigned long long)next,
1955 lbh->b_size >> mpd->inode->i_blkbits, err);
1956 printk(KERN_EMERG "This should not happen.!! "
1957 "Data will be lost\n");
1958 if (err == -ENOSPC) {
1959 ext4_print_free_blocks(mpd->inode);
1961 /* invlaidate all the pages */
1962 ext4_da_block_invalidatepages(mpd, next,
1963 lbh->b_size >> mpd->inode->i_blkbits);
1964 return err;
1966 BUG_ON(new.b_size == 0);
1968 if (buffer_new(&new))
1969 __unmap_underlying_blocks(mpd->inode, &new);
1972 * If blocks are delayed marked, we need to
1973 * put actual blocknr and drop delayed bit
1975 if (buffer_delay(lbh) || buffer_unwritten(lbh))
1976 mpage_put_bnr_to_bhs(mpd, next, &new);
1978 return 0;
1981 #define BH_FLAGS ((1 << BH_Uptodate) | (1 << BH_Mapped) | \
1982 (1 << BH_Delay) | (1 << BH_Unwritten))
1985 * mpage_add_bh_to_extent - try to add one more block to extent of blocks
1987 * @mpd->lbh - extent of blocks
1988 * @logical - logical number of the block in the file
1989 * @bh - bh of the block (used to access block's state)
1991 * the function is used to collect contig. blocks in same state
1993 static void mpage_add_bh_to_extent(struct mpage_da_data *mpd,
1994 sector_t logical, struct buffer_head *bh)
1996 sector_t next;
1997 size_t b_size = bh->b_size;
1998 struct buffer_head *lbh = &mpd->lbh;
1999 int nrblocks = lbh->b_size >> mpd->inode->i_blkbits;
2001 /* check if thereserved journal credits might overflow */
2002 if (!(EXT4_I(mpd->inode)->i_flags & EXT4_EXTENTS_FL)) {
2003 if (nrblocks >= EXT4_MAX_TRANS_DATA) {
2005 * With non-extent format we are limited by the journal
2006 * credit available. Total credit needed to insert
2007 * nrblocks contiguous blocks is dependent on the
2008 * nrblocks. So limit nrblocks.
2010 goto flush_it;
2011 } else if ((nrblocks + (b_size >> mpd->inode->i_blkbits)) >
2012 EXT4_MAX_TRANS_DATA) {
2014 * Adding the new buffer_head would make it cross the
2015 * allowed limit for which we have journal credit
2016 * reserved. So limit the new bh->b_size
2018 b_size = (EXT4_MAX_TRANS_DATA - nrblocks) <<
2019 mpd->inode->i_blkbits;
2020 /* we will do mpage_da_submit_io in the next loop */
2024 * First block in the extent
2026 if (lbh->b_size == 0) {
2027 lbh->b_blocknr = logical;
2028 lbh->b_size = b_size;
2029 lbh->b_state = bh->b_state & BH_FLAGS;
2030 return;
2033 next = lbh->b_blocknr + nrblocks;
2035 * Can we merge the block to our big extent?
2037 if (logical == next && (bh->b_state & BH_FLAGS) == lbh->b_state) {
2038 lbh->b_size += b_size;
2039 return;
2042 flush_it:
2044 * We couldn't merge the block to our extent, so we
2045 * need to flush current extent and start new one
2047 if (mpage_da_map_blocks(mpd) == 0)
2048 mpage_da_submit_io(mpd);
2049 mpd->io_done = 1;
2050 return;
2054 * __mpage_da_writepage - finds extent of pages and blocks
2056 * @page: page to consider
2057 * @wbc: not used, we just follow rules
2058 * @data: context
2060 * The function finds extents of pages and scan them for all blocks.
2062 static int __mpage_da_writepage(struct page *page,
2063 struct writeback_control *wbc, void *data)
2065 struct mpage_da_data *mpd = data;
2066 struct inode *inode = mpd->inode;
2067 struct buffer_head *bh, *head, fake;
2068 sector_t logical;
2070 if (mpd->io_done) {
2072 * Rest of the page in the page_vec
2073 * redirty then and skip then. We will
2074 * try to to write them again after
2075 * starting a new transaction
2077 redirty_page_for_writepage(wbc, page);
2078 unlock_page(page);
2079 return MPAGE_DA_EXTENT_TAIL;
2082 * Can we merge this page to current extent?
2084 if (mpd->next_page != page->index) {
2086 * Nope, we can't. So, we map non-allocated blocks
2087 * and start IO on them using writepage()
2089 if (mpd->next_page != mpd->first_page) {
2090 if (mpage_da_map_blocks(mpd) == 0)
2091 mpage_da_submit_io(mpd);
2093 * skip rest of the page in the page_vec
2095 mpd->io_done = 1;
2096 redirty_page_for_writepage(wbc, page);
2097 unlock_page(page);
2098 return MPAGE_DA_EXTENT_TAIL;
2102 * Start next extent of pages ...
2104 mpd->first_page = page->index;
2107 * ... and blocks
2109 mpd->lbh.b_size = 0;
2110 mpd->lbh.b_state = 0;
2111 mpd->lbh.b_blocknr = 0;
2114 mpd->next_page = page->index + 1;
2115 logical = (sector_t) page->index <<
2116 (PAGE_CACHE_SHIFT - inode->i_blkbits);
2118 if (!page_has_buffers(page)) {
2120 * There is no attached buffer heads yet (mmap?)
2121 * we treat the page asfull of dirty blocks
2123 bh = &fake;
2124 bh->b_size = PAGE_CACHE_SIZE;
2125 bh->b_state = 0;
2126 set_buffer_dirty(bh);
2127 set_buffer_uptodate(bh);
2128 mpage_add_bh_to_extent(mpd, logical, bh);
2129 if (mpd->io_done)
2130 return MPAGE_DA_EXTENT_TAIL;
2131 } else {
2133 * Page with regular buffer heads, just add all dirty ones
2135 head = page_buffers(page);
2136 bh = head;
2137 do {
2138 BUG_ON(buffer_locked(bh));
2140 * We need to try to allocate
2141 * unmapped blocks in the same page.
2142 * Otherwise we won't make progress
2143 * with the page in ext4_da_writepage
2145 if (buffer_dirty(bh) &&
2146 (!buffer_mapped(bh) || buffer_delay(bh))) {
2147 mpage_add_bh_to_extent(mpd, logical, bh);
2148 if (mpd->io_done)
2149 return MPAGE_DA_EXTENT_TAIL;
2150 } else if (buffer_dirty(bh) && (buffer_mapped(bh))) {
2152 * mapped dirty buffer. We need to update
2153 * the b_state because we look at
2154 * b_state in mpage_da_map_blocks. We don't
2155 * update b_size because if we find an
2156 * unmapped buffer_head later we need to
2157 * use the b_state flag of that buffer_head.
2159 if (mpd->lbh.b_size == 0)
2160 mpd->lbh.b_state =
2161 bh->b_state & BH_FLAGS;
2163 logical++;
2164 } while ((bh = bh->b_this_page) != head);
2167 return 0;
2171 * mpage_da_writepages - walk the list of dirty pages of the given
2172 * address space, allocates non-allocated blocks, maps newly-allocated
2173 * blocks to existing bhs and issue IO them
2175 * @mapping: address space structure to write
2176 * @wbc: subtract the number of written pages from *@wbc->nr_to_write
2177 * @get_block: the filesystem's block mapper function.
2179 * This is a library function, which implements the writepages()
2180 * address_space_operation.
2182 static int mpage_da_writepages(struct address_space *mapping,
2183 struct writeback_control *wbc,
2184 struct mpage_da_data *mpd)
2186 int ret;
2188 if (!mpd->get_block)
2189 return generic_writepages(mapping, wbc);
2191 mpd->lbh.b_size = 0;
2192 mpd->lbh.b_state = 0;
2193 mpd->lbh.b_blocknr = 0;
2194 mpd->first_page = 0;
2195 mpd->next_page = 0;
2196 mpd->io_done = 0;
2197 mpd->pages_written = 0;
2198 mpd->retval = 0;
2200 ret = write_cache_pages(mapping, wbc, __mpage_da_writepage, mpd);
2202 * Handle last extent of pages
2204 if (!mpd->io_done && mpd->next_page != mpd->first_page) {
2205 if (mpage_da_map_blocks(mpd) == 0)
2206 mpage_da_submit_io(mpd);
2208 mpd->io_done = 1;
2209 ret = MPAGE_DA_EXTENT_TAIL;
2211 wbc->nr_to_write -= mpd->pages_written;
2212 return ret;
2216 * this is a special callback for ->write_begin() only
2217 * it's intention is to return mapped block or reserve space
2219 static int ext4_da_get_block_prep(struct inode *inode, sector_t iblock,
2220 struct buffer_head *bh_result, int create)
2222 int ret = 0;
2224 BUG_ON(create == 0);
2225 BUG_ON(bh_result->b_size != inode->i_sb->s_blocksize);
2228 * first, we need to know whether the block is allocated already
2229 * preallocated blocks are unmapped but should treated
2230 * the same as allocated blocks.
2232 ret = ext4_get_blocks_wrap(NULL, inode, iblock, 1, bh_result, 0, 0, 0);
2233 if ((ret == 0) && !buffer_delay(bh_result)) {
2234 /* the block isn't (pre)allocated yet, let's reserve space */
2236 * XXX: __block_prepare_write() unmaps passed block,
2237 * is it OK?
2239 ret = ext4_da_reserve_space(inode, 1);
2240 if (ret)
2241 /* not enough space to reserve */
2242 return ret;
2244 map_bh(bh_result, inode->i_sb, 0);
2245 set_buffer_new(bh_result);
2246 set_buffer_delay(bh_result);
2247 } else if (ret > 0) {
2248 bh_result->b_size = (ret << inode->i_blkbits);
2249 ret = 0;
2252 return ret;
2254 #define EXT4_DELALLOC_RSVED 1
2255 static int ext4_da_get_block_write(struct inode *inode, sector_t iblock,
2256 struct buffer_head *bh_result, int create)
2258 int ret;
2259 unsigned max_blocks = bh_result->b_size >> inode->i_blkbits;
2260 loff_t disksize = EXT4_I(inode)->i_disksize;
2261 handle_t *handle = NULL;
2263 handle = ext4_journal_current_handle();
2264 BUG_ON(!handle);
2265 ret = ext4_get_blocks_wrap(handle, inode, iblock, max_blocks,
2266 bh_result, create, 0, EXT4_DELALLOC_RSVED);
2267 if (ret > 0) {
2269 bh_result->b_size = (ret << inode->i_blkbits);
2271 if (ext4_should_order_data(inode)) {
2272 int retval;
2273 retval = ext4_jbd2_file_inode(handle, inode);
2274 if (retval)
2276 * Failed to add inode for ordered
2277 * mode. Don't update file size
2279 return retval;
2283 * Update on-disk size along with block allocation
2284 * we don't use 'extend_disksize' as size may change
2285 * within already allocated block -bzzz
2287 disksize = ((loff_t) iblock + ret) << inode->i_blkbits;
2288 if (disksize > i_size_read(inode))
2289 disksize = i_size_read(inode);
2290 if (disksize > EXT4_I(inode)->i_disksize) {
2291 ext4_update_i_disksize(inode, disksize);
2292 ret = ext4_mark_inode_dirty(handle, inode);
2293 return ret;
2295 ret = 0;
2297 return ret;
2300 static int ext4_bh_unmapped_or_delay(handle_t *handle, struct buffer_head *bh)
2303 * unmapped buffer is possible for holes.
2304 * delay buffer is possible with delayed allocation
2306 return ((!buffer_mapped(bh) || buffer_delay(bh)) && buffer_dirty(bh));
2309 static int ext4_normal_get_block_write(struct inode *inode, sector_t iblock,
2310 struct buffer_head *bh_result, int create)
2312 int ret = 0;
2313 unsigned max_blocks = bh_result->b_size >> inode->i_blkbits;
2316 * we don't want to do block allocation in writepage
2317 * so call get_block_wrap with create = 0
2319 ret = ext4_get_blocks_wrap(NULL, inode, iblock, max_blocks,
2320 bh_result, 0, 0, 0);
2321 if (ret > 0) {
2322 bh_result->b_size = (ret << inode->i_blkbits);
2323 ret = 0;
2325 return ret;
2329 * get called vi ext4_da_writepages after taking page lock (have journal handle)
2330 * get called via journal_submit_inode_data_buffers (no journal handle)
2331 * get called via shrink_page_list via pdflush (no journal handle)
2332 * or grab_page_cache when doing write_begin (have journal handle)
2334 static int ext4_da_writepage(struct page *page,
2335 struct writeback_control *wbc)
2337 int ret = 0;
2338 loff_t size;
2339 unsigned int len;
2340 struct buffer_head *page_bufs;
2341 struct inode *inode = page->mapping->host;
2343 trace_mark(ext4_da_writepage,
2344 "dev %s ino %lu page_index %lu",
2345 inode->i_sb->s_id, inode->i_ino, page->index);
2346 size = i_size_read(inode);
2347 if (page->index == size >> PAGE_CACHE_SHIFT)
2348 len = size & ~PAGE_CACHE_MASK;
2349 else
2350 len = PAGE_CACHE_SIZE;
2352 if (page_has_buffers(page)) {
2353 page_bufs = page_buffers(page);
2354 if (walk_page_buffers(NULL, page_bufs, 0, len, NULL,
2355 ext4_bh_unmapped_or_delay)) {
2357 * We don't want to do block allocation
2358 * So redirty the page and return
2359 * We may reach here when we do a journal commit
2360 * via journal_submit_inode_data_buffers.
2361 * If we don't have mapping block we just ignore
2362 * them. We can also reach here via shrink_page_list
2364 redirty_page_for_writepage(wbc, page);
2365 unlock_page(page);
2366 return 0;
2368 } else {
2370 * The test for page_has_buffers() is subtle:
2371 * We know the page is dirty but it lost buffers. That means
2372 * that at some moment in time after write_begin()/write_end()
2373 * has been called all buffers have been clean and thus they
2374 * must have been written at least once. So they are all
2375 * mapped and we can happily proceed with mapping them
2376 * and writing the page.
2378 * Try to initialize the buffer_heads and check whether
2379 * all are mapped and non delay. We don't want to
2380 * do block allocation here.
2382 ret = block_prepare_write(page, 0, PAGE_CACHE_SIZE,
2383 ext4_normal_get_block_write);
2384 if (!ret) {
2385 page_bufs = page_buffers(page);
2386 /* check whether all are mapped and non delay */
2387 if (walk_page_buffers(NULL, page_bufs, 0, len, NULL,
2388 ext4_bh_unmapped_or_delay)) {
2389 redirty_page_for_writepage(wbc, page);
2390 unlock_page(page);
2391 return 0;
2393 } else {
2395 * We can't do block allocation here
2396 * so just redity the page and unlock
2397 * and return
2399 redirty_page_for_writepage(wbc, page);
2400 unlock_page(page);
2401 return 0;
2403 /* now mark the buffer_heads as dirty and uptodate */
2404 block_commit_write(page, 0, PAGE_CACHE_SIZE);
2407 if (test_opt(inode->i_sb, NOBH) && ext4_should_writeback_data(inode))
2408 ret = nobh_writepage(page, ext4_normal_get_block_write, wbc);
2409 else
2410 ret = block_write_full_page(page,
2411 ext4_normal_get_block_write,
2412 wbc);
2414 return ret;
2418 * This is called via ext4_da_writepages() to
2419 * calulate the total number of credits to reserve to fit
2420 * a single extent allocation into a single transaction,
2421 * ext4_da_writpeages() will loop calling this before
2422 * the block allocation.
2425 static int ext4_da_writepages_trans_blocks(struct inode *inode)
2427 int max_blocks = EXT4_I(inode)->i_reserved_data_blocks;
2430 * With non-extent format the journal credit needed to
2431 * insert nrblocks contiguous block is dependent on
2432 * number of contiguous block. So we will limit
2433 * number of contiguous block to a sane value
2435 if (!(inode->i_flags & EXT4_EXTENTS_FL) &&
2436 (max_blocks > EXT4_MAX_TRANS_DATA))
2437 max_blocks = EXT4_MAX_TRANS_DATA;
2439 return ext4_chunk_trans_blocks(inode, max_blocks);
2442 static int ext4_da_writepages(struct address_space *mapping,
2443 struct writeback_control *wbc)
2445 pgoff_t index;
2446 int range_whole = 0;
2447 handle_t *handle = NULL;
2448 struct mpage_da_data mpd;
2449 struct inode *inode = mapping->host;
2450 int no_nrwrite_index_update;
2451 int pages_written = 0;
2452 long pages_skipped;
2453 int range_cyclic, cycled = 1, io_done = 0;
2454 int needed_blocks, ret = 0, nr_to_writebump = 0;
2455 struct ext4_sb_info *sbi = EXT4_SB(mapping->host->i_sb);
2457 trace_mark(ext4_da_writepages,
2458 "dev %s ino %lu nr_t_write %ld "
2459 "pages_skipped %ld range_start %llu "
2460 "range_end %llu nonblocking %d "
2461 "for_kupdate %d for_reclaim %d "
2462 "for_writepages %d range_cyclic %d",
2463 inode->i_sb->s_id, inode->i_ino,
2464 wbc->nr_to_write, wbc->pages_skipped,
2465 (unsigned long long) wbc->range_start,
2466 (unsigned long long) wbc->range_end,
2467 wbc->nonblocking, wbc->for_kupdate,
2468 wbc->for_reclaim, wbc->for_writepages,
2469 wbc->range_cyclic);
2472 * No pages to write? This is mainly a kludge to avoid starting
2473 * a transaction for special inodes like journal inode on last iput()
2474 * because that could violate lock ordering on umount
2476 if (!mapping->nrpages || !mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
2477 return 0;
2480 * If the filesystem has aborted, it is read-only, so return
2481 * right away instead of dumping stack traces later on that
2482 * will obscure the real source of the problem. We test
2483 * EXT4_MOUNT_ABORT instead of sb->s_flag's MS_RDONLY because
2484 * the latter could be true if the filesystem is mounted
2485 * read-only, and in that case, ext4_da_writepages should
2486 * *never* be called, so if that ever happens, we would want
2487 * the stack trace.
2489 if (unlikely(sbi->s_mount_opt & EXT4_MOUNT_ABORT))
2490 return -EROFS;
2493 * Make sure nr_to_write is >= sbi->s_mb_stream_request
2494 * This make sure small files blocks are allocated in
2495 * single attempt. This ensure that small files
2496 * get less fragmented.
2498 if (wbc->nr_to_write < sbi->s_mb_stream_request) {
2499 nr_to_writebump = sbi->s_mb_stream_request - wbc->nr_to_write;
2500 wbc->nr_to_write = sbi->s_mb_stream_request;
2502 if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
2503 range_whole = 1;
2505 range_cyclic = wbc->range_cyclic;
2506 if (wbc->range_cyclic) {
2507 index = mapping->writeback_index;
2508 if (index)
2509 cycled = 0;
2510 wbc->range_start = index << PAGE_CACHE_SHIFT;
2511 wbc->range_end = LLONG_MAX;
2512 wbc->range_cyclic = 0;
2513 } else
2514 index = wbc->range_start >> PAGE_CACHE_SHIFT;
2516 mpd.wbc = wbc;
2517 mpd.inode = mapping->host;
2520 * we don't want write_cache_pages to update
2521 * nr_to_write and writeback_index
2523 no_nrwrite_index_update = wbc->no_nrwrite_index_update;
2524 wbc->no_nrwrite_index_update = 1;
2525 pages_skipped = wbc->pages_skipped;
2527 retry:
2528 while (!ret && wbc->nr_to_write > 0) {
2531 * we insert one extent at a time. So we need
2532 * credit needed for single extent allocation.
2533 * journalled mode is currently not supported
2534 * by delalloc
2536 BUG_ON(ext4_should_journal_data(inode));
2537 needed_blocks = ext4_da_writepages_trans_blocks(inode);
2539 /* start a new transaction*/
2540 handle = ext4_journal_start(inode, needed_blocks);
2541 if (IS_ERR(handle)) {
2542 ret = PTR_ERR(handle);
2543 printk(KERN_CRIT "%s: jbd2_start: "
2544 "%ld pages, ino %lu; err %d\n", __func__,
2545 wbc->nr_to_write, inode->i_ino, ret);
2546 dump_stack();
2547 goto out_writepages;
2549 mpd.get_block = ext4_da_get_block_write;
2550 ret = mpage_da_writepages(mapping, wbc, &mpd);
2552 ext4_journal_stop(handle);
2554 if ((mpd.retval == -ENOSPC) && sbi->s_journal) {
2555 /* commit the transaction which would
2556 * free blocks released in the transaction
2557 * and try again
2559 jbd2_journal_force_commit_nested(sbi->s_journal);
2560 wbc->pages_skipped = pages_skipped;
2561 ret = 0;
2562 } else if (ret == MPAGE_DA_EXTENT_TAIL) {
2564 * got one extent now try with
2565 * rest of the pages
2567 pages_written += mpd.pages_written;
2568 wbc->pages_skipped = pages_skipped;
2569 ret = 0;
2570 io_done = 1;
2571 } else if (wbc->nr_to_write)
2573 * There is no more writeout needed
2574 * or we requested for a noblocking writeout
2575 * and we found the device congested
2577 break;
2579 if (!io_done && !cycled) {
2580 cycled = 1;
2581 index = 0;
2582 wbc->range_start = index << PAGE_CACHE_SHIFT;
2583 wbc->range_end = mapping->writeback_index - 1;
2584 goto retry;
2586 if (pages_skipped != wbc->pages_skipped)
2587 printk(KERN_EMERG "This should not happen leaving %s "
2588 "with nr_to_write = %ld ret = %d\n",
2589 __func__, wbc->nr_to_write, ret);
2591 /* Update index */
2592 index += pages_written;
2593 wbc->range_cyclic = range_cyclic;
2594 if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
2596 * set the writeback_index so that range_cyclic
2597 * mode will write it back later
2599 mapping->writeback_index = index;
2601 out_writepages:
2602 if (!no_nrwrite_index_update)
2603 wbc->no_nrwrite_index_update = 0;
2604 wbc->nr_to_write -= nr_to_writebump;
2605 trace_mark(ext4_da_writepage_result,
2606 "dev %s ino %lu ret %d pages_written %d "
2607 "pages_skipped %ld congestion %d "
2608 "more_io %d no_nrwrite_index_update %d",
2609 inode->i_sb->s_id, inode->i_ino, ret,
2610 pages_written, wbc->pages_skipped,
2611 wbc->encountered_congestion, wbc->more_io,
2612 wbc->no_nrwrite_index_update);
2613 return ret;
2616 #define FALL_BACK_TO_NONDELALLOC 1
2617 static int ext4_nonda_switch(struct super_block *sb)
2619 s64 free_blocks, dirty_blocks;
2620 struct ext4_sb_info *sbi = EXT4_SB(sb);
2623 * switch to non delalloc mode if we are running low
2624 * on free block. The free block accounting via percpu
2625 * counters can get slightly wrong with percpu_counter_batch getting
2626 * accumulated on each CPU without updating global counters
2627 * Delalloc need an accurate free block accounting. So switch
2628 * to non delalloc when we are near to error range.
2630 free_blocks = percpu_counter_read_positive(&sbi->s_freeblocks_counter);
2631 dirty_blocks = percpu_counter_read_positive(&sbi->s_dirtyblocks_counter);
2632 if (2 * free_blocks < 3 * dirty_blocks ||
2633 free_blocks < (dirty_blocks + EXT4_FREEBLOCKS_WATERMARK)) {
2635 * free block count is less that 150% of dirty blocks
2636 * or free blocks is less that watermark
2638 return 1;
2640 return 0;
2643 static int ext4_da_write_begin(struct file *file, struct address_space *mapping,
2644 loff_t pos, unsigned len, unsigned flags,
2645 struct page **pagep, void **fsdata)
2647 int ret, retries = 0;
2648 struct page *page;
2649 pgoff_t index;
2650 unsigned from, to;
2651 struct inode *inode = mapping->host;
2652 handle_t *handle;
2654 index = pos >> PAGE_CACHE_SHIFT;
2655 from = pos & (PAGE_CACHE_SIZE - 1);
2656 to = from + len;
2658 if (ext4_nonda_switch(inode->i_sb)) {
2659 *fsdata = (void *)FALL_BACK_TO_NONDELALLOC;
2660 return ext4_write_begin(file, mapping, pos,
2661 len, flags, pagep, fsdata);
2663 *fsdata = (void *)0;
2665 trace_mark(ext4_da_write_begin,
2666 "dev %s ino %lu pos %llu len %u flags %u",
2667 inode->i_sb->s_id, inode->i_ino,
2668 (unsigned long long) pos, len, flags);
2669 retry:
2671 * With delayed allocation, we don't log the i_disksize update
2672 * if there is delayed block allocation. But we still need
2673 * to journalling the i_disksize update if writes to the end
2674 * of file which has an already mapped buffer.
2676 handle = ext4_journal_start(inode, 1);
2677 if (IS_ERR(handle)) {
2678 ret = PTR_ERR(handle);
2679 goto out;
2681 /* We cannot recurse into the filesystem as the transaction is already
2682 * started */
2683 flags |= AOP_FLAG_NOFS;
2685 page = grab_cache_page_write_begin(mapping, index, flags);
2686 if (!page) {
2687 ext4_journal_stop(handle);
2688 ret = -ENOMEM;
2689 goto out;
2691 *pagep = page;
2693 ret = block_write_begin(file, mapping, pos, len, flags, pagep, fsdata,
2694 ext4_da_get_block_prep);
2695 if (ret < 0) {
2696 unlock_page(page);
2697 ext4_journal_stop(handle);
2698 page_cache_release(page);
2700 * block_write_begin may have instantiated a few blocks
2701 * outside i_size. Trim these off again. Don't need
2702 * i_size_read because we hold i_mutex.
2704 if (pos + len > inode->i_size)
2705 vmtruncate(inode, inode->i_size);
2708 if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
2709 goto retry;
2710 out:
2711 return ret;
2715 * Check if we should update i_disksize
2716 * when write to the end of file but not require block allocation
2718 static int ext4_da_should_update_i_disksize(struct page *page,
2719 unsigned long offset)
2721 struct buffer_head *bh;
2722 struct inode *inode = page->mapping->host;
2723 unsigned int idx;
2724 int i;
2726 bh = page_buffers(page);
2727 idx = offset >> inode->i_blkbits;
2729 for (i = 0; i < idx; i++)
2730 bh = bh->b_this_page;
2732 if (!buffer_mapped(bh) || (buffer_delay(bh)))
2733 return 0;
2734 return 1;
2737 static int ext4_da_write_end(struct file *file,
2738 struct address_space *mapping,
2739 loff_t pos, unsigned len, unsigned copied,
2740 struct page *page, void *fsdata)
2742 struct inode *inode = mapping->host;
2743 int ret = 0, ret2;
2744 handle_t *handle = ext4_journal_current_handle();
2745 loff_t new_i_size;
2746 unsigned long start, end;
2747 int write_mode = (int)(unsigned long)fsdata;
2749 if (write_mode == FALL_BACK_TO_NONDELALLOC) {
2750 if (ext4_should_order_data(inode)) {
2751 return ext4_ordered_write_end(file, mapping, pos,
2752 len, copied, page, fsdata);
2753 } else if (ext4_should_writeback_data(inode)) {
2754 return ext4_writeback_write_end(file, mapping, pos,
2755 len, copied, page, fsdata);
2756 } else {
2757 BUG();
2761 trace_mark(ext4_da_write_end,
2762 "dev %s ino %lu pos %llu len %u copied %u",
2763 inode->i_sb->s_id, inode->i_ino,
2764 (unsigned long long) pos, len, copied);
2765 start = pos & (PAGE_CACHE_SIZE - 1);
2766 end = start + copied - 1;
2769 * generic_write_end() will run mark_inode_dirty() if i_size
2770 * changes. So let's piggyback the i_disksize mark_inode_dirty
2771 * into that.
2774 new_i_size = pos + copied;
2775 if (new_i_size > EXT4_I(inode)->i_disksize) {
2776 if (ext4_da_should_update_i_disksize(page, end)) {
2777 down_write(&EXT4_I(inode)->i_data_sem);
2778 if (new_i_size > EXT4_I(inode)->i_disksize) {
2780 * Updating i_disksize when extending file
2781 * without needing block allocation
2783 if (ext4_should_order_data(inode))
2784 ret = ext4_jbd2_file_inode(handle,
2785 inode);
2787 EXT4_I(inode)->i_disksize = new_i_size;
2789 up_write(&EXT4_I(inode)->i_data_sem);
2790 /* We need to mark inode dirty even if
2791 * new_i_size is less that inode->i_size
2792 * bu greater than i_disksize.(hint delalloc)
2794 ext4_mark_inode_dirty(handle, inode);
2797 ret2 = generic_write_end(file, mapping, pos, len, copied,
2798 page, fsdata);
2799 copied = ret2;
2800 if (ret2 < 0)
2801 ret = ret2;
2802 ret2 = ext4_journal_stop(handle);
2803 if (!ret)
2804 ret = ret2;
2806 return ret ? ret : copied;
2809 static void ext4_da_invalidatepage(struct page *page, unsigned long offset)
2812 * Drop reserved blocks
2814 BUG_ON(!PageLocked(page));
2815 if (!page_has_buffers(page))
2816 goto out;
2818 ext4_da_page_release_reservation(page, offset);
2820 out:
2821 ext4_invalidatepage(page, offset);
2823 return;
2827 * Force all delayed allocation blocks to be allocated for a given inode.
2829 int ext4_alloc_da_blocks(struct inode *inode)
2831 if (!EXT4_I(inode)->i_reserved_data_blocks &&
2832 !EXT4_I(inode)->i_reserved_meta_blocks)
2833 return 0;
2836 * We do something simple for now. The filemap_flush() will
2837 * also start triggering a write of the data blocks, which is
2838 * not strictly speaking necessary (and for users of
2839 * laptop_mode, not even desirable). However, to do otherwise
2840 * would require replicating code paths in:
2842 * ext4_da_writepages() ->
2843 * write_cache_pages() ---> (via passed in callback function)
2844 * __mpage_da_writepage() -->
2845 * mpage_add_bh_to_extent()
2846 * mpage_da_map_blocks()
2848 * The problem is that write_cache_pages(), located in
2849 * mm/page-writeback.c, marks pages clean in preparation for
2850 * doing I/O, which is not desirable if we're not planning on
2851 * doing I/O at all.
2853 * We could call write_cache_pages(), and then redirty all of
2854 * the pages by calling redirty_page_for_writeback() but that
2855 * would be ugly in the extreme. So instead we would need to
2856 * replicate parts of the code in the above functions,
2857 * simplifying them becuase we wouldn't actually intend to
2858 * write out the pages, but rather only collect contiguous
2859 * logical block extents, call the multi-block allocator, and
2860 * then update the buffer heads with the block allocations.
2862 * For now, though, we'll cheat by calling filemap_flush(),
2863 * which will map the blocks, and start the I/O, but not
2864 * actually wait for the I/O to complete.
2866 return filemap_flush(inode->i_mapping);
2870 * bmap() is special. It gets used by applications such as lilo and by
2871 * the swapper to find the on-disk block of a specific piece of data.
2873 * Naturally, this is dangerous if the block concerned is still in the
2874 * journal. If somebody makes a swapfile on an ext4 data-journaling
2875 * filesystem and enables swap, then they may get a nasty shock when the
2876 * data getting swapped to that swapfile suddenly gets overwritten by
2877 * the original zero's written out previously to the journal and
2878 * awaiting writeback in the kernel's buffer cache.
2880 * So, if we see any bmap calls here on a modified, data-journaled file,
2881 * take extra steps to flush any blocks which might be in the cache.
2883 static sector_t ext4_bmap(struct address_space *mapping, sector_t block)
2885 struct inode *inode = mapping->host;
2886 journal_t *journal;
2887 int err;
2889 if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY) &&
2890 test_opt(inode->i_sb, DELALLOC)) {
2892 * With delalloc we want to sync the file
2893 * so that we can make sure we allocate
2894 * blocks for file
2896 filemap_write_and_wait(mapping);
2899 if (EXT4_JOURNAL(inode) && EXT4_I(inode)->i_state & EXT4_STATE_JDATA) {
2901 * This is a REALLY heavyweight approach, but the use of
2902 * bmap on dirty files is expected to be extremely rare:
2903 * only if we run lilo or swapon on a freshly made file
2904 * do we expect this to happen.
2906 * (bmap requires CAP_SYS_RAWIO so this does not
2907 * represent an unprivileged user DOS attack --- we'd be
2908 * in trouble if mortal users could trigger this path at
2909 * will.)
2911 * NB. EXT4_STATE_JDATA is not set on files other than
2912 * regular files. If somebody wants to bmap a directory
2913 * or symlink and gets confused because the buffer
2914 * hasn't yet been flushed to disk, they deserve
2915 * everything they get.
2918 EXT4_I(inode)->i_state &= ~EXT4_STATE_JDATA;
2919 journal = EXT4_JOURNAL(inode);
2920 jbd2_journal_lock_updates(journal);
2921 err = jbd2_journal_flush(journal);
2922 jbd2_journal_unlock_updates(journal);
2924 if (err)
2925 return 0;
2928 return generic_block_bmap(mapping, block, ext4_get_block);
2931 static int bget_one(handle_t *handle, struct buffer_head *bh)
2933 get_bh(bh);
2934 return 0;
2937 static int bput_one(handle_t *handle, struct buffer_head *bh)
2939 put_bh(bh);
2940 return 0;
2944 * Note that we don't need to start a transaction unless we're journaling data
2945 * because we should have holes filled from ext4_page_mkwrite(). We even don't
2946 * need to file the inode to the transaction's list in ordered mode because if
2947 * we are writing back data added by write(), the inode is already there and if
2948 * we are writing back data modified via mmap(), noone guarantees in which
2949 * transaction the data will hit the disk. In case we are journaling data, we
2950 * cannot start transaction directly because transaction start ranks above page
2951 * lock so we have to do some magic.
2953 * In all journaling modes block_write_full_page() will start the I/O.
2955 * Problem:
2957 * ext4_writepage() -> kmalloc() -> __alloc_pages() -> page_launder() ->
2958 * ext4_writepage()
2960 * Similar for:
2962 * ext4_file_write() -> generic_file_write() -> __alloc_pages() -> ...
2964 * Same applies to ext4_get_block(). We will deadlock on various things like
2965 * lock_journal and i_data_sem
2967 * Setting PF_MEMALLOC here doesn't work - too many internal memory
2968 * allocations fail.
2970 * 16May01: If we're reentered then journal_current_handle() will be
2971 * non-zero. We simply *return*.
2973 * 1 July 2001: @@@ FIXME:
2974 * In journalled data mode, a data buffer may be metadata against the
2975 * current transaction. But the same file is part of a shared mapping
2976 * and someone does a writepage() on it.
2978 * We will move the buffer onto the async_data list, but *after* it has
2979 * been dirtied. So there's a small window where we have dirty data on
2980 * BJ_Metadata.
2982 * Note that this only applies to the last partial page in the file. The
2983 * bit which block_write_full_page() uses prepare/commit for. (That's
2984 * broken code anyway: it's wrong for msync()).
2986 * It's a rare case: affects the final partial page, for journalled data
2987 * where the file is subject to bith write() and writepage() in the same
2988 * transction. To fix it we'll need a custom block_write_full_page().
2989 * We'll probably need that anyway for journalling writepage() output.
2991 * We don't honour synchronous mounts for writepage(). That would be
2992 * disastrous. Any write() or metadata operation will sync the fs for
2993 * us.
2996 static int __ext4_normal_writepage(struct page *page,
2997 struct writeback_control *wbc)
2999 struct inode *inode = page->mapping->host;
3001 if (test_opt(inode->i_sb, NOBH))
3002 return nobh_writepage(page,
3003 ext4_normal_get_block_write, wbc);
3004 else
3005 return block_write_full_page(page,
3006 ext4_normal_get_block_write,
3007 wbc);
3010 static int ext4_normal_writepage(struct page *page,
3011 struct writeback_control *wbc)
3013 struct inode *inode = page->mapping->host;
3014 loff_t size = i_size_read(inode);
3015 loff_t len;
3017 trace_mark(ext4_normal_writepage,
3018 "dev %s ino %lu page_index %lu",
3019 inode->i_sb->s_id, inode->i_ino, page->index);
3020 J_ASSERT(PageLocked(page));
3021 if (page->index == size >> PAGE_CACHE_SHIFT)
3022 len = size & ~PAGE_CACHE_MASK;
3023 else
3024 len = PAGE_CACHE_SIZE;
3026 if (page_has_buffers(page)) {
3027 /* if page has buffers it should all be mapped
3028 * and allocated. If there are not buffers attached
3029 * to the page we know the page is dirty but it lost
3030 * buffers. That means that at some moment in time
3031 * after write_begin() / write_end() has been called
3032 * all buffers have been clean and thus they must have been
3033 * written at least once. So they are all mapped and we can
3034 * happily proceed with mapping them and writing the page.
3036 BUG_ON(walk_page_buffers(NULL, page_buffers(page), 0, len, NULL,
3037 ext4_bh_unmapped_or_delay));
3040 if (!ext4_journal_current_handle())
3041 return __ext4_normal_writepage(page, wbc);
3043 redirty_page_for_writepage(wbc, page);
3044 unlock_page(page);
3045 return 0;
3048 static int __ext4_journalled_writepage(struct page *page,
3049 struct writeback_control *wbc)
3051 struct address_space *mapping = page->mapping;
3052 struct inode *inode = mapping->host;
3053 struct buffer_head *page_bufs;
3054 handle_t *handle = NULL;
3055 int ret = 0;
3056 int err;
3058 ret = block_prepare_write(page, 0, PAGE_CACHE_SIZE,
3059 ext4_normal_get_block_write);
3060 if (ret != 0)
3061 goto out_unlock;
3063 page_bufs = page_buffers(page);
3064 walk_page_buffers(handle, page_bufs, 0, PAGE_CACHE_SIZE, NULL,
3065 bget_one);
3066 /* As soon as we unlock the page, it can go away, but we have
3067 * references to buffers so we are safe */
3068 unlock_page(page);
3070 handle = ext4_journal_start(inode, ext4_writepage_trans_blocks(inode));
3071 if (IS_ERR(handle)) {
3072 ret = PTR_ERR(handle);
3073 goto out;
3076 ret = walk_page_buffers(handle, page_bufs, 0,
3077 PAGE_CACHE_SIZE, NULL, do_journal_get_write_access);
3079 err = walk_page_buffers(handle, page_bufs, 0,
3080 PAGE_CACHE_SIZE, NULL, write_end_fn);
3081 if (ret == 0)
3082 ret = err;
3083 err = ext4_journal_stop(handle);
3084 if (!ret)
3085 ret = err;
3087 walk_page_buffers(handle, page_bufs, 0,
3088 PAGE_CACHE_SIZE, NULL, bput_one);
3089 EXT4_I(inode)->i_state |= EXT4_STATE_JDATA;
3090 goto out;
3092 out_unlock:
3093 unlock_page(page);
3094 out:
3095 return ret;
3098 static int ext4_journalled_writepage(struct page *page,
3099 struct writeback_control *wbc)
3101 struct inode *inode = page->mapping->host;
3102 loff_t size = i_size_read(inode);
3103 loff_t len;
3105 trace_mark(ext4_journalled_writepage,
3106 "dev %s ino %lu page_index %lu",
3107 inode->i_sb->s_id, inode->i_ino, page->index);
3108 J_ASSERT(PageLocked(page));
3109 if (page->index == size >> PAGE_CACHE_SHIFT)
3110 len = size & ~PAGE_CACHE_MASK;
3111 else
3112 len = PAGE_CACHE_SIZE;
3114 if (page_has_buffers(page)) {
3115 /* if page has buffers it should all be mapped
3116 * and allocated. If there are not buffers attached
3117 * to the page we know the page is dirty but it lost
3118 * buffers. That means that at some moment in time
3119 * after write_begin() / write_end() has been called
3120 * all buffers have been clean and thus they must have been
3121 * written at least once. So they are all mapped and we can
3122 * happily proceed with mapping them and writing the page.
3124 BUG_ON(walk_page_buffers(NULL, page_buffers(page), 0, len, NULL,
3125 ext4_bh_unmapped_or_delay));
3128 if (ext4_journal_current_handle())
3129 goto no_write;
3131 if (PageChecked(page)) {
3133 * It's mmapped pagecache. Add buffers and journal it. There
3134 * doesn't seem much point in redirtying the page here.
3136 ClearPageChecked(page);
3137 return __ext4_journalled_writepage(page, wbc);
3138 } else {
3140 * It may be a page full of checkpoint-mode buffers. We don't
3141 * really know unless we go poke around in the buffer_heads.
3142 * But block_write_full_page will do the right thing.
3144 return block_write_full_page(page,
3145 ext4_normal_get_block_write,
3146 wbc);
3148 no_write:
3149 redirty_page_for_writepage(wbc, page);
3150 unlock_page(page);
3151 return 0;
3154 static int ext4_readpage(struct file *file, struct page *page)
3156 return mpage_readpage(page, ext4_get_block);
3159 static int
3160 ext4_readpages(struct file *file, struct address_space *mapping,
3161 struct list_head *pages, unsigned nr_pages)
3163 return mpage_readpages(mapping, pages, nr_pages, ext4_get_block);
3166 static void ext4_invalidatepage(struct page *page, unsigned long offset)
3168 journal_t *journal = EXT4_JOURNAL(page->mapping->host);
3171 * If it's a full truncate we just forget about the pending dirtying
3173 if (offset == 0)
3174 ClearPageChecked(page);
3176 if (journal)
3177 jbd2_journal_invalidatepage(journal, page, offset);
3178 else
3179 block_invalidatepage(page, offset);
3182 static int ext4_releasepage(struct page *page, gfp_t wait)
3184 journal_t *journal = EXT4_JOURNAL(page->mapping->host);
3186 WARN_ON(PageChecked(page));
3187 if (!page_has_buffers(page))
3188 return 0;
3189 if (journal)
3190 return jbd2_journal_try_to_free_buffers(journal, page, wait);
3191 else
3192 return try_to_free_buffers(page);
3196 * If the O_DIRECT write will extend the file then add this inode to the
3197 * orphan list. So recovery will truncate it back to the original size
3198 * if the machine crashes during the write.
3200 * If the O_DIRECT write is intantiating holes inside i_size and the machine
3201 * crashes then stale disk data _may_ be exposed inside the file. But current
3202 * VFS code falls back into buffered path in that case so we are safe.
3204 static ssize_t ext4_direct_IO(int rw, struct kiocb *iocb,
3205 const struct iovec *iov, loff_t offset,
3206 unsigned long nr_segs)
3208 struct file *file = iocb->ki_filp;
3209 struct inode *inode = file->f_mapping->host;
3210 struct ext4_inode_info *ei = EXT4_I(inode);
3211 handle_t *handle;
3212 ssize_t ret;
3213 int orphan = 0;
3214 size_t count = iov_length(iov, nr_segs);
3216 if (rw == WRITE) {
3217 loff_t final_size = offset + count;
3219 if (final_size > inode->i_size) {
3220 /* Credits for sb + inode write */
3221 handle = ext4_journal_start(inode, 2);
3222 if (IS_ERR(handle)) {
3223 ret = PTR_ERR(handle);
3224 goto out;
3226 ret = ext4_orphan_add(handle, inode);
3227 if (ret) {
3228 ext4_journal_stop(handle);
3229 goto out;
3231 orphan = 1;
3232 ei->i_disksize = inode->i_size;
3233 ext4_journal_stop(handle);
3237 ret = blockdev_direct_IO(rw, iocb, inode, inode->i_sb->s_bdev, iov,
3238 offset, nr_segs,
3239 ext4_get_block, NULL);
3241 if (orphan) {
3242 int err;
3244 /* Credits for sb + inode write */
3245 handle = ext4_journal_start(inode, 2);
3246 if (IS_ERR(handle)) {
3247 /* This is really bad luck. We've written the data
3248 * but cannot extend i_size. Bail out and pretend
3249 * the write failed... */
3250 ret = PTR_ERR(handle);
3251 goto out;
3253 if (inode->i_nlink)
3254 ext4_orphan_del(handle, inode);
3255 if (ret > 0) {
3256 loff_t end = offset + ret;
3257 if (end > inode->i_size) {
3258 ei->i_disksize = end;
3259 i_size_write(inode, end);
3261 * We're going to return a positive `ret'
3262 * here due to non-zero-length I/O, so there's
3263 * no way of reporting error returns from
3264 * ext4_mark_inode_dirty() to userspace. So
3265 * ignore it.
3267 ext4_mark_inode_dirty(handle, inode);
3270 err = ext4_journal_stop(handle);
3271 if (ret == 0)
3272 ret = err;
3274 out:
3275 return ret;
3279 * Pages can be marked dirty completely asynchronously from ext4's journalling
3280 * activity. By filemap_sync_pte(), try_to_unmap_one(), etc. We cannot do
3281 * much here because ->set_page_dirty is called under VFS locks. The page is
3282 * not necessarily locked.
3284 * We cannot just dirty the page and leave attached buffers clean, because the
3285 * buffers' dirty state is "definitive". We cannot just set the buffers dirty
3286 * or jbddirty because all the journalling code will explode.
3288 * So what we do is to mark the page "pending dirty" and next time writepage
3289 * is called, propagate that into the buffers appropriately.
3291 static int ext4_journalled_set_page_dirty(struct page *page)
3293 SetPageChecked(page);
3294 return __set_page_dirty_nobuffers(page);
3297 static const struct address_space_operations ext4_ordered_aops = {
3298 .readpage = ext4_readpage,
3299 .readpages = ext4_readpages,
3300 .writepage = ext4_normal_writepage,
3301 .sync_page = block_sync_page,
3302 .write_begin = ext4_write_begin,
3303 .write_end = ext4_ordered_write_end,
3304 .bmap = ext4_bmap,
3305 .invalidatepage = ext4_invalidatepage,
3306 .releasepage = ext4_releasepage,
3307 .direct_IO = ext4_direct_IO,
3308 .migratepage = buffer_migrate_page,
3309 .is_partially_uptodate = block_is_partially_uptodate,
3312 static const struct address_space_operations ext4_writeback_aops = {
3313 .readpage = ext4_readpage,
3314 .readpages = ext4_readpages,
3315 .writepage = ext4_normal_writepage,
3316 .sync_page = block_sync_page,
3317 .write_begin = ext4_write_begin,
3318 .write_end = ext4_writeback_write_end,
3319 .bmap = ext4_bmap,
3320 .invalidatepage = ext4_invalidatepage,
3321 .releasepage = ext4_releasepage,
3322 .direct_IO = ext4_direct_IO,
3323 .migratepage = buffer_migrate_page,
3324 .is_partially_uptodate = block_is_partially_uptodate,
3327 static const struct address_space_operations ext4_journalled_aops = {
3328 .readpage = ext4_readpage,
3329 .readpages = ext4_readpages,
3330 .writepage = ext4_journalled_writepage,
3331 .sync_page = block_sync_page,
3332 .write_begin = ext4_write_begin,
3333 .write_end = ext4_journalled_write_end,
3334 .set_page_dirty = ext4_journalled_set_page_dirty,
3335 .bmap = ext4_bmap,
3336 .invalidatepage = ext4_invalidatepage,
3337 .releasepage = ext4_releasepage,
3338 .is_partially_uptodate = block_is_partially_uptodate,
3341 static const struct address_space_operations ext4_da_aops = {
3342 .readpage = ext4_readpage,
3343 .readpages = ext4_readpages,
3344 .writepage = ext4_da_writepage,
3345 .writepages = ext4_da_writepages,
3346 .sync_page = block_sync_page,
3347 .write_begin = ext4_da_write_begin,
3348 .write_end = ext4_da_write_end,
3349 .bmap = ext4_bmap,
3350 .invalidatepage = ext4_da_invalidatepage,
3351 .releasepage = ext4_releasepage,
3352 .direct_IO = ext4_direct_IO,
3353 .migratepage = buffer_migrate_page,
3354 .is_partially_uptodate = block_is_partially_uptodate,
3357 void ext4_set_aops(struct inode *inode)
3359 if (ext4_should_order_data(inode) &&
3360 test_opt(inode->i_sb, DELALLOC))
3361 inode->i_mapping->a_ops = &ext4_da_aops;
3362 else if (ext4_should_order_data(inode))
3363 inode->i_mapping->a_ops = &ext4_ordered_aops;
3364 else if (ext4_should_writeback_data(inode) &&
3365 test_opt(inode->i_sb, DELALLOC))
3366 inode->i_mapping->a_ops = &ext4_da_aops;
3367 else if (ext4_should_writeback_data(inode))
3368 inode->i_mapping->a_ops = &ext4_writeback_aops;
3369 else
3370 inode->i_mapping->a_ops = &ext4_journalled_aops;
3374 * ext4_block_truncate_page() zeroes out a mapping from file offset `from'
3375 * up to the end of the block which corresponds to `from'.
3376 * This required during truncate. We need to physically zero the tail end
3377 * of that block so it doesn't yield old data if the file is later grown.
3379 int ext4_block_truncate_page(handle_t *handle,
3380 struct address_space *mapping, loff_t from)
3382 ext4_fsblk_t index = from >> PAGE_CACHE_SHIFT;
3383 unsigned offset = from & (PAGE_CACHE_SIZE-1);
3384 unsigned blocksize, length, pos;
3385 ext4_lblk_t iblock;
3386 struct inode *inode = mapping->host;
3387 struct buffer_head *bh;
3388 struct page *page;
3389 int err = 0;
3391 page = grab_cache_page(mapping, from >> PAGE_CACHE_SHIFT);
3392 if (!page)
3393 return -EINVAL;
3395 blocksize = inode->i_sb->s_blocksize;
3396 length = blocksize - (offset & (blocksize - 1));
3397 iblock = index << (PAGE_CACHE_SHIFT - inode->i_sb->s_blocksize_bits);
3400 * For "nobh" option, we can only work if we don't need to
3401 * read-in the page - otherwise we create buffers to do the IO.
3403 if (!page_has_buffers(page) && test_opt(inode->i_sb, NOBH) &&
3404 ext4_should_writeback_data(inode) && PageUptodate(page)) {
3405 zero_user(page, offset, length);
3406 set_page_dirty(page);
3407 goto unlock;
3410 if (!page_has_buffers(page))
3411 create_empty_buffers(page, blocksize, 0);
3413 /* Find the buffer that contains "offset" */
3414 bh = page_buffers(page);
3415 pos = blocksize;
3416 while (offset >= pos) {
3417 bh = bh->b_this_page;
3418 iblock++;
3419 pos += blocksize;
3422 err = 0;
3423 if (buffer_freed(bh)) {
3424 BUFFER_TRACE(bh, "freed: skip");
3425 goto unlock;
3428 if (!buffer_mapped(bh)) {
3429 BUFFER_TRACE(bh, "unmapped");
3430 ext4_get_block(inode, iblock, bh, 0);
3431 /* unmapped? It's a hole - nothing to do */
3432 if (!buffer_mapped(bh)) {
3433 BUFFER_TRACE(bh, "still unmapped");
3434 goto unlock;
3438 /* Ok, it's mapped. Make sure it's up-to-date */
3439 if (PageUptodate(page))
3440 set_buffer_uptodate(bh);
3442 if (!buffer_uptodate(bh)) {
3443 err = -EIO;
3444 ll_rw_block(READ, 1, &bh);
3445 wait_on_buffer(bh);
3446 /* Uhhuh. Read error. Complain and punt. */
3447 if (!buffer_uptodate(bh))
3448 goto unlock;
3451 if (ext4_should_journal_data(inode)) {
3452 BUFFER_TRACE(bh, "get write access");
3453 err = ext4_journal_get_write_access(handle, bh);
3454 if (err)
3455 goto unlock;
3458 zero_user(page, offset, length);
3460 BUFFER_TRACE(bh, "zeroed end of block");
3462 err = 0;
3463 if (ext4_should_journal_data(inode)) {
3464 err = ext4_handle_dirty_metadata(handle, inode, bh);
3465 } else {
3466 if (ext4_should_order_data(inode))
3467 err = ext4_jbd2_file_inode(handle, inode);
3468 mark_buffer_dirty(bh);
3471 unlock:
3472 unlock_page(page);
3473 page_cache_release(page);
3474 return err;
3478 * Probably it should be a library function... search for first non-zero word
3479 * or memcmp with zero_page, whatever is better for particular architecture.
3480 * Linus?
3482 static inline int all_zeroes(__le32 *p, __le32 *q)
3484 while (p < q)
3485 if (*p++)
3486 return 0;
3487 return 1;
3491 * ext4_find_shared - find the indirect blocks for partial truncation.
3492 * @inode: inode in question
3493 * @depth: depth of the affected branch
3494 * @offsets: offsets of pointers in that branch (see ext4_block_to_path)
3495 * @chain: place to store the pointers to partial indirect blocks
3496 * @top: place to the (detached) top of branch
3498 * This is a helper function used by ext4_truncate().
3500 * When we do truncate() we may have to clean the ends of several
3501 * indirect blocks but leave the blocks themselves alive. Block is
3502 * partially truncated if some data below the new i_size is refered
3503 * from it (and it is on the path to the first completely truncated
3504 * data block, indeed). We have to free the top of that path along
3505 * with everything to the right of the path. Since no allocation
3506 * past the truncation point is possible until ext4_truncate()
3507 * finishes, we may safely do the latter, but top of branch may
3508 * require special attention - pageout below the truncation point
3509 * might try to populate it.
3511 * We atomically detach the top of branch from the tree, store the
3512 * block number of its root in *@top, pointers to buffer_heads of
3513 * partially truncated blocks - in @chain[].bh and pointers to
3514 * their last elements that should not be removed - in
3515 * @chain[].p. Return value is the pointer to last filled element
3516 * of @chain.
3518 * The work left to caller to do the actual freeing of subtrees:
3519 * a) free the subtree starting from *@top
3520 * b) free the subtrees whose roots are stored in
3521 * (@chain[i].p+1 .. end of @chain[i].bh->b_data)
3522 * c) free the subtrees growing from the inode past the @chain[0].
3523 * (no partially truncated stuff there). */
3525 static Indirect *ext4_find_shared(struct inode *inode, int depth,
3526 ext4_lblk_t offsets[4], Indirect chain[4], __le32 *top)
3528 Indirect *partial, *p;
3529 int k, err;
3531 *top = 0;
3532 /* Make k index the deepest non-null offest + 1 */
3533 for (k = depth; k > 1 && !offsets[k-1]; k--)
3535 partial = ext4_get_branch(inode, k, offsets, chain, &err);
3536 /* Writer: pointers */
3537 if (!partial)
3538 partial = chain + k-1;
3540 * If the branch acquired continuation since we've looked at it -
3541 * fine, it should all survive and (new) top doesn't belong to us.
3543 if (!partial->key && *partial->p)
3544 /* Writer: end */
3545 goto no_top;
3546 for (p = partial; (p > chain) && all_zeroes((__le32 *) p->bh->b_data, p->p); p--)
3549 * OK, we've found the last block that must survive. The rest of our
3550 * branch should be detached before unlocking. However, if that rest
3551 * of branch is all ours and does not grow immediately from the inode
3552 * it's easier to cheat and just decrement partial->p.
3554 if (p == chain + k - 1 && p > chain) {
3555 p->p--;
3556 } else {
3557 *top = *p->p;
3558 /* Nope, don't do this in ext4. Must leave the tree intact */
3559 #if 0
3560 *p->p = 0;
3561 #endif
3563 /* Writer: end */
3565 while (partial > p) {
3566 brelse(partial->bh);
3567 partial--;
3569 no_top:
3570 return partial;
3574 * Zero a number of block pointers in either an inode or an indirect block.
3575 * If we restart the transaction we must again get write access to the
3576 * indirect block for further modification.
3578 * We release `count' blocks on disk, but (last - first) may be greater
3579 * than `count' because there can be holes in there.
3581 static void ext4_clear_blocks(handle_t *handle, struct inode *inode,
3582 struct buffer_head *bh, ext4_fsblk_t block_to_free,
3583 unsigned long count, __le32 *first, __le32 *last)
3585 __le32 *p;
3586 if (try_to_extend_transaction(handle, inode)) {
3587 if (bh) {
3588 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
3589 ext4_handle_dirty_metadata(handle, inode, bh);
3591 ext4_mark_inode_dirty(handle, inode);
3592 ext4_journal_test_restart(handle, inode);
3593 if (bh) {
3594 BUFFER_TRACE(bh, "retaking write access");
3595 ext4_journal_get_write_access(handle, bh);
3600 * Any buffers which are on the journal will be in memory. We find
3601 * them on the hash table so jbd2_journal_revoke() will run jbd2_journal_forget()
3602 * on them. We've already detached each block from the file, so
3603 * bforget() in jbd2_journal_forget() should be safe.
3605 * AKPM: turn on bforget in jbd2_journal_forget()!!!
3607 for (p = first; p < last; p++) {
3608 u32 nr = le32_to_cpu(*p);
3609 if (nr) {
3610 struct buffer_head *tbh;
3612 *p = 0;
3613 tbh = sb_find_get_block(inode->i_sb, nr);
3614 ext4_forget(handle, 0, inode, tbh, nr);
3618 ext4_free_blocks(handle, inode, block_to_free, count, 0);
3622 * ext4_free_data - free a list of data blocks
3623 * @handle: handle for this transaction
3624 * @inode: inode we are dealing with
3625 * @this_bh: indirect buffer_head which contains *@first and *@last
3626 * @first: array of block numbers
3627 * @last: points immediately past the end of array
3629 * We are freeing all blocks refered from that array (numbers are stored as
3630 * little-endian 32-bit) and updating @inode->i_blocks appropriately.
3632 * We accumulate contiguous runs of blocks to free. Conveniently, if these
3633 * blocks are contiguous then releasing them at one time will only affect one
3634 * or two bitmap blocks (+ group descriptor(s) and superblock) and we won't
3635 * actually use a lot of journal space.
3637 * @this_bh will be %NULL if @first and @last point into the inode's direct
3638 * block pointers.
3640 static void ext4_free_data(handle_t *handle, struct inode *inode,
3641 struct buffer_head *this_bh,
3642 __le32 *first, __le32 *last)
3644 ext4_fsblk_t block_to_free = 0; /* Starting block # of a run */
3645 unsigned long count = 0; /* Number of blocks in the run */
3646 __le32 *block_to_free_p = NULL; /* Pointer into inode/ind
3647 corresponding to
3648 block_to_free */
3649 ext4_fsblk_t nr; /* Current block # */
3650 __le32 *p; /* Pointer into inode/ind
3651 for current block */
3652 int err;
3654 if (this_bh) { /* For indirect block */
3655 BUFFER_TRACE(this_bh, "get_write_access");
3656 err = ext4_journal_get_write_access(handle, this_bh);
3657 /* Important: if we can't update the indirect pointers
3658 * to the blocks, we can't free them. */
3659 if (err)
3660 return;
3663 for (p = first; p < last; p++) {
3664 nr = le32_to_cpu(*p);
3665 if (nr) {
3666 /* accumulate blocks to free if they're contiguous */
3667 if (count == 0) {
3668 block_to_free = nr;
3669 block_to_free_p = p;
3670 count = 1;
3671 } else if (nr == block_to_free + count) {
3672 count++;
3673 } else {
3674 ext4_clear_blocks(handle, inode, this_bh,
3675 block_to_free,
3676 count, block_to_free_p, p);
3677 block_to_free = nr;
3678 block_to_free_p = p;
3679 count = 1;
3684 if (count > 0)
3685 ext4_clear_blocks(handle, inode, this_bh, block_to_free,
3686 count, block_to_free_p, p);
3688 if (this_bh) {
3689 BUFFER_TRACE(this_bh, "call ext4_handle_dirty_metadata");
3692 * The buffer head should have an attached journal head at this
3693 * point. However, if the data is corrupted and an indirect
3694 * block pointed to itself, it would have been detached when
3695 * the block was cleared. Check for this instead of OOPSing.
3697 if ((EXT4_JOURNAL(inode) == NULL) || bh2jh(this_bh))
3698 ext4_handle_dirty_metadata(handle, inode, this_bh);
3699 else
3700 ext4_error(inode->i_sb, __func__,
3701 "circular indirect block detected, "
3702 "inode=%lu, block=%llu",
3703 inode->i_ino,
3704 (unsigned long long) this_bh->b_blocknr);
3709 * ext4_free_branches - free an array of branches
3710 * @handle: JBD handle for this transaction
3711 * @inode: inode we are dealing with
3712 * @parent_bh: the buffer_head which contains *@first and *@last
3713 * @first: array of block numbers
3714 * @last: pointer immediately past the end of array
3715 * @depth: depth of the branches to free
3717 * We are freeing all blocks refered from these branches (numbers are
3718 * stored as little-endian 32-bit) and updating @inode->i_blocks
3719 * appropriately.
3721 static void ext4_free_branches(handle_t *handle, struct inode *inode,
3722 struct buffer_head *parent_bh,
3723 __le32 *first, __le32 *last, int depth)
3725 ext4_fsblk_t nr;
3726 __le32 *p;
3728 if (ext4_handle_is_aborted(handle))
3729 return;
3731 if (depth--) {
3732 struct buffer_head *bh;
3733 int addr_per_block = EXT4_ADDR_PER_BLOCK(inode->i_sb);
3734 p = last;
3735 while (--p >= first) {
3736 nr = le32_to_cpu(*p);
3737 if (!nr)
3738 continue; /* A hole */
3740 /* Go read the buffer for the next level down */
3741 bh = sb_bread(inode->i_sb, nr);
3744 * A read failure? Report error and clear slot
3745 * (should be rare).
3747 if (!bh) {
3748 ext4_error(inode->i_sb, "ext4_free_branches",
3749 "Read failure, inode=%lu, block=%llu",
3750 inode->i_ino, nr);
3751 continue;
3754 /* This zaps the entire block. Bottom up. */
3755 BUFFER_TRACE(bh, "free child branches");
3756 ext4_free_branches(handle, inode, bh,
3757 (__le32 *) bh->b_data,
3758 (__le32 *) bh->b_data + addr_per_block,
3759 depth);
3762 * We've probably journalled the indirect block several
3763 * times during the truncate. But it's no longer
3764 * needed and we now drop it from the transaction via
3765 * jbd2_journal_revoke().
3767 * That's easy if it's exclusively part of this
3768 * transaction. But if it's part of the committing
3769 * transaction then jbd2_journal_forget() will simply
3770 * brelse() it. That means that if the underlying
3771 * block is reallocated in ext4_get_block(),
3772 * unmap_underlying_metadata() will find this block
3773 * and will try to get rid of it. damn, damn.
3775 * If this block has already been committed to the
3776 * journal, a revoke record will be written. And
3777 * revoke records must be emitted *before* clearing
3778 * this block's bit in the bitmaps.
3780 ext4_forget(handle, 1, inode, bh, bh->b_blocknr);
3783 * Everything below this this pointer has been
3784 * released. Now let this top-of-subtree go.
3786 * We want the freeing of this indirect block to be
3787 * atomic in the journal with the updating of the
3788 * bitmap block which owns it. So make some room in
3789 * the journal.
3791 * We zero the parent pointer *after* freeing its
3792 * pointee in the bitmaps, so if extend_transaction()
3793 * for some reason fails to put the bitmap changes and
3794 * the release into the same transaction, recovery
3795 * will merely complain about releasing a free block,
3796 * rather than leaking blocks.
3798 if (ext4_handle_is_aborted(handle))
3799 return;
3800 if (try_to_extend_transaction(handle, inode)) {
3801 ext4_mark_inode_dirty(handle, inode);
3802 ext4_journal_test_restart(handle, inode);
3805 ext4_free_blocks(handle, inode, nr, 1, 1);
3807 if (parent_bh) {
3809 * The block which we have just freed is
3810 * pointed to by an indirect block: journal it
3812 BUFFER_TRACE(parent_bh, "get_write_access");
3813 if (!ext4_journal_get_write_access(handle,
3814 parent_bh)){
3815 *p = 0;
3816 BUFFER_TRACE(parent_bh,
3817 "call ext4_handle_dirty_metadata");
3818 ext4_handle_dirty_metadata(handle,
3819 inode,
3820 parent_bh);
3824 } else {
3825 /* We have reached the bottom of the tree. */
3826 BUFFER_TRACE(parent_bh, "free data blocks");
3827 ext4_free_data(handle, inode, parent_bh, first, last);
3831 int ext4_can_truncate(struct inode *inode)
3833 if (IS_APPEND(inode) || IS_IMMUTABLE(inode))
3834 return 0;
3835 if (S_ISREG(inode->i_mode))
3836 return 1;
3837 if (S_ISDIR(inode->i_mode))
3838 return 1;
3839 if (S_ISLNK(inode->i_mode))
3840 return !ext4_inode_is_fast_symlink(inode);
3841 return 0;
3845 * ext4_truncate()
3847 * We block out ext4_get_block() block instantiations across the entire
3848 * transaction, and VFS/VM ensures that ext4_truncate() cannot run
3849 * simultaneously on behalf of the same inode.
3851 * As we work through the truncate and commmit bits of it to the journal there
3852 * is one core, guiding principle: the file's tree must always be consistent on
3853 * disk. We must be able to restart the truncate after a crash.
3855 * The file's tree may be transiently inconsistent in memory (although it
3856 * probably isn't), but whenever we close off and commit a journal transaction,
3857 * the contents of (the filesystem + the journal) must be consistent and
3858 * restartable. It's pretty simple, really: bottom up, right to left (although
3859 * left-to-right works OK too).
3861 * Note that at recovery time, journal replay occurs *before* the restart of
3862 * truncate against the orphan inode list.
3864 * The committed inode has the new, desired i_size (which is the same as
3865 * i_disksize in this case). After a crash, ext4_orphan_cleanup() will see
3866 * that this inode's truncate did not complete and it will again call
3867 * ext4_truncate() to have another go. So there will be instantiated blocks
3868 * to the right of the truncation point in a crashed ext4 filesystem. But
3869 * that's fine - as long as they are linked from the inode, the post-crash
3870 * ext4_truncate() run will find them and release them.
3872 void ext4_truncate(struct inode *inode)
3874 handle_t *handle;
3875 struct ext4_inode_info *ei = EXT4_I(inode);
3876 __le32 *i_data = ei->i_data;
3877 int addr_per_block = EXT4_ADDR_PER_BLOCK(inode->i_sb);
3878 struct address_space *mapping = inode->i_mapping;
3879 ext4_lblk_t offsets[4];
3880 Indirect chain[4];
3881 Indirect *partial;
3882 __le32 nr = 0;
3883 int n;
3884 ext4_lblk_t last_block;
3885 unsigned blocksize = inode->i_sb->s_blocksize;
3887 if (!ext4_can_truncate(inode))
3888 return;
3890 if (inode->i_size == 0)
3891 ei->i_state |= EXT4_STATE_DA_ALLOC_CLOSE;
3893 if (EXT4_I(inode)->i_flags & EXT4_EXTENTS_FL) {
3894 ext4_ext_truncate(inode);
3895 return;
3898 handle = start_transaction(inode);
3899 if (IS_ERR(handle))
3900 return; /* AKPM: return what? */
3902 last_block = (inode->i_size + blocksize-1)
3903 >> EXT4_BLOCK_SIZE_BITS(inode->i_sb);
3905 if (inode->i_size & (blocksize - 1))
3906 if (ext4_block_truncate_page(handle, mapping, inode->i_size))
3907 goto out_stop;
3909 n = ext4_block_to_path(inode, last_block, offsets, NULL);
3910 if (n == 0)
3911 goto out_stop; /* error */
3914 * OK. This truncate is going to happen. We add the inode to the
3915 * orphan list, so that if this truncate spans multiple transactions,
3916 * and we crash, we will resume the truncate when the filesystem
3917 * recovers. It also marks the inode dirty, to catch the new size.
3919 * Implication: the file must always be in a sane, consistent
3920 * truncatable state while each transaction commits.
3922 if (ext4_orphan_add(handle, inode))
3923 goto out_stop;
3926 * From here we block out all ext4_get_block() callers who want to
3927 * modify the block allocation tree.
3929 down_write(&ei->i_data_sem);
3931 ext4_discard_preallocations(inode);
3934 * The orphan list entry will now protect us from any crash which
3935 * occurs before the truncate completes, so it is now safe to propagate
3936 * the new, shorter inode size (held for now in i_size) into the
3937 * on-disk inode. We do this via i_disksize, which is the value which
3938 * ext4 *really* writes onto the disk inode.
3940 ei->i_disksize = inode->i_size;
3942 if (n == 1) { /* direct blocks */
3943 ext4_free_data(handle, inode, NULL, i_data+offsets[0],
3944 i_data + EXT4_NDIR_BLOCKS);
3945 goto do_indirects;
3948 partial = ext4_find_shared(inode, n, offsets, chain, &nr);
3949 /* Kill the top of shared branch (not detached) */
3950 if (nr) {
3951 if (partial == chain) {
3952 /* Shared branch grows from the inode */
3953 ext4_free_branches(handle, inode, NULL,
3954 &nr, &nr+1, (chain+n-1) - partial);
3955 *partial->p = 0;
3957 * We mark the inode dirty prior to restart,
3958 * and prior to stop. No need for it here.
3960 } else {
3961 /* Shared branch grows from an indirect block */
3962 BUFFER_TRACE(partial->bh, "get_write_access");
3963 ext4_free_branches(handle, inode, partial->bh,
3964 partial->p,
3965 partial->p+1, (chain+n-1) - partial);
3968 /* Clear the ends of indirect blocks on the shared branch */
3969 while (partial > chain) {
3970 ext4_free_branches(handle, inode, partial->bh, partial->p + 1,
3971 (__le32*)partial->bh->b_data+addr_per_block,
3972 (chain+n-1) - partial);
3973 BUFFER_TRACE(partial->bh, "call brelse");
3974 brelse (partial->bh);
3975 partial--;
3977 do_indirects:
3978 /* Kill the remaining (whole) subtrees */
3979 switch (offsets[0]) {
3980 default:
3981 nr = i_data[EXT4_IND_BLOCK];
3982 if (nr) {
3983 ext4_free_branches(handle, inode, NULL, &nr, &nr+1, 1);
3984 i_data[EXT4_IND_BLOCK] = 0;
3986 case EXT4_IND_BLOCK:
3987 nr = i_data[EXT4_DIND_BLOCK];
3988 if (nr) {
3989 ext4_free_branches(handle, inode, NULL, &nr, &nr+1, 2);
3990 i_data[EXT4_DIND_BLOCK] = 0;
3992 case EXT4_DIND_BLOCK:
3993 nr = i_data[EXT4_TIND_BLOCK];
3994 if (nr) {
3995 ext4_free_branches(handle, inode, NULL, &nr, &nr+1, 3);
3996 i_data[EXT4_TIND_BLOCK] = 0;
3998 case EXT4_TIND_BLOCK:
4002 up_write(&ei->i_data_sem);
4003 inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
4004 ext4_mark_inode_dirty(handle, inode);
4007 * In a multi-transaction truncate, we only make the final transaction
4008 * synchronous
4010 if (IS_SYNC(inode))
4011 ext4_handle_sync(handle);
4012 out_stop:
4014 * If this was a simple ftruncate(), and the file will remain alive
4015 * then we need to clear up the orphan record which we created above.
4016 * However, if this was a real unlink then we were called by
4017 * ext4_delete_inode(), and we allow that function to clean up the
4018 * orphan info for us.
4020 if (inode->i_nlink)
4021 ext4_orphan_del(handle, inode);
4023 ext4_journal_stop(handle);
4027 * ext4_get_inode_loc returns with an extra refcount against the inode's
4028 * underlying buffer_head on success. If 'in_mem' is true, we have all
4029 * data in memory that is needed to recreate the on-disk version of this
4030 * inode.
4032 static int __ext4_get_inode_loc(struct inode *inode,
4033 struct ext4_iloc *iloc, int in_mem)
4035 struct ext4_group_desc *gdp;
4036 struct buffer_head *bh;
4037 struct super_block *sb = inode->i_sb;
4038 ext4_fsblk_t block;
4039 int inodes_per_block, inode_offset;
4041 iloc->bh = NULL;
4042 if (!ext4_valid_inum(sb, inode->i_ino))
4043 return -EIO;
4045 iloc->block_group = (inode->i_ino - 1) / EXT4_INODES_PER_GROUP(sb);
4046 gdp = ext4_get_group_desc(sb, iloc->block_group, NULL);
4047 if (!gdp)
4048 return -EIO;
4051 * Figure out the offset within the block group inode table
4053 inodes_per_block = (EXT4_BLOCK_SIZE(sb) / EXT4_INODE_SIZE(sb));
4054 inode_offset = ((inode->i_ino - 1) %
4055 EXT4_INODES_PER_GROUP(sb));
4056 block = ext4_inode_table(sb, gdp) + (inode_offset / inodes_per_block);
4057 iloc->offset = (inode_offset % inodes_per_block) * EXT4_INODE_SIZE(sb);
4059 bh = sb_getblk(sb, block);
4060 if (!bh) {
4061 ext4_error(sb, "ext4_get_inode_loc", "unable to read "
4062 "inode block - inode=%lu, block=%llu",
4063 inode->i_ino, block);
4064 return -EIO;
4066 if (!buffer_uptodate(bh)) {
4067 lock_buffer(bh);
4070 * If the buffer has the write error flag, we have failed
4071 * to write out another inode in the same block. In this
4072 * case, we don't have to read the block because we may
4073 * read the old inode data successfully.
4075 if (buffer_write_io_error(bh) && !buffer_uptodate(bh))
4076 set_buffer_uptodate(bh);
4078 if (buffer_uptodate(bh)) {
4079 /* someone brought it uptodate while we waited */
4080 unlock_buffer(bh);
4081 goto has_buffer;
4085 * If we have all information of the inode in memory and this
4086 * is the only valid inode in the block, we need not read the
4087 * block.
4089 if (in_mem) {
4090 struct buffer_head *bitmap_bh;
4091 int i, start;
4093 start = inode_offset & ~(inodes_per_block - 1);
4095 /* Is the inode bitmap in cache? */
4096 bitmap_bh = sb_getblk(sb, ext4_inode_bitmap(sb, gdp));
4097 if (!bitmap_bh)
4098 goto make_io;
4101 * If the inode bitmap isn't in cache then the
4102 * optimisation may end up performing two reads instead
4103 * of one, so skip it.
4105 if (!buffer_uptodate(bitmap_bh)) {
4106 brelse(bitmap_bh);
4107 goto make_io;
4109 for (i = start; i < start + inodes_per_block; i++) {
4110 if (i == inode_offset)
4111 continue;
4112 if (ext4_test_bit(i, bitmap_bh->b_data))
4113 break;
4115 brelse(bitmap_bh);
4116 if (i == start + inodes_per_block) {
4117 /* all other inodes are free, so skip I/O */
4118 memset(bh->b_data, 0, bh->b_size);
4119 set_buffer_uptodate(bh);
4120 unlock_buffer(bh);
4121 goto has_buffer;
4125 make_io:
4127 * If we need to do any I/O, try to pre-readahead extra
4128 * blocks from the inode table.
4130 if (EXT4_SB(sb)->s_inode_readahead_blks) {
4131 ext4_fsblk_t b, end, table;
4132 unsigned num;
4134 table = ext4_inode_table(sb, gdp);
4135 /* Make sure s_inode_readahead_blks is a power of 2 */
4136 while (EXT4_SB(sb)->s_inode_readahead_blks &
4137 (EXT4_SB(sb)->s_inode_readahead_blks-1))
4138 EXT4_SB(sb)->s_inode_readahead_blks =
4139 (EXT4_SB(sb)->s_inode_readahead_blks &
4140 (EXT4_SB(sb)->s_inode_readahead_blks-1));
4141 b = block & ~(EXT4_SB(sb)->s_inode_readahead_blks-1);
4142 if (table > b)
4143 b = table;
4144 end = b + EXT4_SB(sb)->s_inode_readahead_blks;
4145 num = EXT4_INODES_PER_GROUP(sb);
4146 if (EXT4_HAS_RO_COMPAT_FEATURE(sb,
4147 EXT4_FEATURE_RO_COMPAT_GDT_CSUM))
4148 num -= ext4_itable_unused_count(sb, gdp);
4149 table += num / inodes_per_block;
4150 if (end > table)
4151 end = table;
4152 while (b <= end)
4153 sb_breadahead(sb, b++);
4157 * There are other valid inodes in the buffer, this inode
4158 * has in-inode xattrs, or we don't have this inode in memory.
4159 * Read the block from disk.
4161 get_bh(bh);
4162 bh->b_end_io = end_buffer_read_sync;
4163 submit_bh(READ_META, bh);
4164 wait_on_buffer(bh);
4165 if (!buffer_uptodate(bh)) {
4166 ext4_error(sb, __func__,
4167 "unable to read inode block - inode=%lu, "
4168 "block=%llu", inode->i_ino, block);
4169 brelse(bh);
4170 return -EIO;
4173 has_buffer:
4174 iloc->bh = bh;
4175 return 0;
4178 int ext4_get_inode_loc(struct inode *inode, struct ext4_iloc *iloc)
4180 /* We have all inode data except xattrs in memory here. */
4181 return __ext4_get_inode_loc(inode, iloc,
4182 !(EXT4_I(inode)->i_state & EXT4_STATE_XATTR));
4185 void ext4_set_inode_flags(struct inode *inode)
4187 unsigned int flags = EXT4_I(inode)->i_flags;
4189 inode->i_flags &= ~(S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME|S_DIRSYNC);
4190 if (flags & EXT4_SYNC_FL)
4191 inode->i_flags |= S_SYNC;
4192 if (flags & EXT4_APPEND_FL)
4193 inode->i_flags |= S_APPEND;
4194 if (flags & EXT4_IMMUTABLE_FL)
4195 inode->i_flags |= S_IMMUTABLE;
4196 if (flags & EXT4_NOATIME_FL)
4197 inode->i_flags |= S_NOATIME;
4198 if (flags & EXT4_DIRSYNC_FL)
4199 inode->i_flags |= S_DIRSYNC;
4202 /* Propagate flags from i_flags to EXT4_I(inode)->i_flags */
4203 void ext4_get_inode_flags(struct ext4_inode_info *ei)
4205 unsigned int flags = ei->vfs_inode.i_flags;
4207 ei->i_flags &= ~(EXT4_SYNC_FL|EXT4_APPEND_FL|
4208 EXT4_IMMUTABLE_FL|EXT4_NOATIME_FL|EXT4_DIRSYNC_FL);
4209 if (flags & S_SYNC)
4210 ei->i_flags |= EXT4_SYNC_FL;
4211 if (flags & S_APPEND)
4212 ei->i_flags |= EXT4_APPEND_FL;
4213 if (flags & S_IMMUTABLE)
4214 ei->i_flags |= EXT4_IMMUTABLE_FL;
4215 if (flags & S_NOATIME)
4216 ei->i_flags |= EXT4_NOATIME_FL;
4217 if (flags & S_DIRSYNC)
4218 ei->i_flags |= EXT4_DIRSYNC_FL;
4220 static blkcnt_t ext4_inode_blocks(struct ext4_inode *raw_inode,
4221 struct ext4_inode_info *ei)
4223 blkcnt_t i_blocks ;
4224 struct inode *inode = &(ei->vfs_inode);
4225 struct super_block *sb = inode->i_sb;
4227 if (EXT4_HAS_RO_COMPAT_FEATURE(sb,
4228 EXT4_FEATURE_RO_COMPAT_HUGE_FILE)) {
4229 /* we are using combined 48 bit field */
4230 i_blocks = ((u64)le16_to_cpu(raw_inode->i_blocks_high)) << 32 |
4231 le32_to_cpu(raw_inode->i_blocks_lo);
4232 if (ei->i_flags & EXT4_HUGE_FILE_FL) {
4233 /* i_blocks represent file system block size */
4234 return i_blocks << (inode->i_blkbits - 9);
4235 } else {
4236 return i_blocks;
4238 } else {
4239 return le32_to_cpu(raw_inode->i_blocks_lo);
4243 struct inode *ext4_iget(struct super_block *sb, unsigned long ino)
4245 struct ext4_iloc iloc;
4246 struct ext4_inode *raw_inode;
4247 struct ext4_inode_info *ei;
4248 struct buffer_head *bh;
4249 struct inode *inode;
4250 long ret;
4251 int block;
4253 inode = iget_locked(sb, ino);
4254 if (!inode)
4255 return ERR_PTR(-ENOMEM);
4256 if (!(inode->i_state & I_NEW))
4257 return inode;
4259 ei = EXT4_I(inode);
4260 #ifdef CONFIG_EXT4_FS_POSIX_ACL
4261 ei->i_acl = EXT4_ACL_NOT_CACHED;
4262 ei->i_default_acl = EXT4_ACL_NOT_CACHED;
4263 #endif
4265 ret = __ext4_get_inode_loc(inode, &iloc, 0);
4266 if (ret < 0)
4267 goto bad_inode;
4268 bh = iloc.bh;
4269 raw_inode = ext4_raw_inode(&iloc);
4270 inode->i_mode = le16_to_cpu(raw_inode->i_mode);
4271 inode->i_uid = (uid_t)le16_to_cpu(raw_inode->i_uid_low);
4272 inode->i_gid = (gid_t)le16_to_cpu(raw_inode->i_gid_low);
4273 if (!(test_opt(inode->i_sb, NO_UID32))) {
4274 inode->i_uid |= le16_to_cpu(raw_inode->i_uid_high) << 16;
4275 inode->i_gid |= le16_to_cpu(raw_inode->i_gid_high) << 16;
4277 inode->i_nlink = le16_to_cpu(raw_inode->i_links_count);
4279 ei->i_state = 0;
4280 ei->i_dir_start_lookup = 0;
4281 ei->i_dtime = le32_to_cpu(raw_inode->i_dtime);
4282 /* We now have enough fields to check if the inode was active or not.
4283 * This is needed because nfsd might try to access dead inodes
4284 * the test is that same one that e2fsck uses
4285 * NeilBrown 1999oct15
4287 if (inode->i_nlink == 0) {
4288 if (inode->i_mode == 0 ||
4289 !(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_ORPHAN_FS)) {
4290 /* this inode is deleted */
4291 brelse(bh);
4292 ret = -ESTALE;
4293 goto bad_inode;
4295 /* The only unlinked inodes we let through here have
4296 * valid i_mode and are being read by the orphan
4297 * recovery code: that's fine, we're about to complete
4298 * the process of deleting those. */
4300 ei->i_flags = le32_to_cpu(raw_inode->i_flags);
4301 inode->i_blocks = ext4_inode_blocks(raw_inode, ei);
4302 ei->i_file_acl = le32_to_cpu(raw_inode->i_file_acl_lo);
4303 if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
4304 cpu_to_le32(EXT4_OS_HURD)) {
4305 ei->i_file_acl |=
4306 ((__u64)le16_to_cpu(raw_inode->i_file_acl_high)) << 32;
4308 inode->i_size = ext4_isize(raw_inode);
4309 ei->i_disksize = inode->i_size;
4310 inode->i_generation = le32_to_cpu(raw_inode->i_generation);
4311 ei->i_block_group = iloc.block_group;
4313 * NOTE! The in-memory inode i_data array is in little-endian order
4314 * even on big-endian machines: we do NOT byteswap the block numbers!
4316 for (block = 0; block < EXT4_N_BLOCKS; block++)
4317 ei->i_data[block] = raw_inode->i_block[block];
4318 INIT_LIST_HEAD(&ei->i_orphan);
4320 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4321 ei->i_extra_isize = le16_to_cpu(raw_inode->i_extra_isize);
4322 if (EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize >
4323 EXT4_INODE_SIZE(inode->i_sb)) {
4324 brelse(bh);
4325 ret = -EIO;
4326 goto bad_inode;
4328 if (ei->i_extra_isize == 0) {
4329 /* The extra space is currently unused. Use it. */
4330 ei->i_extra_isize = sizeof(struct ext4_inode) -
4331 EXT4_GOOD_OLD_INODE_SIZE;
4332 } else {
4333 __le32 *magic = (void *)raw_inode +
4334 EXT4_GOOD_OLD_INODE_SIZE +
4335 ei->i_extra_isize;
4336 if (*magic == cpu_to_le32(EXT4_XATTR_MAGIC))
4337 ei->i_state |= EXT4_STATE_XATTR;
4339 } else
4340 ei->i_extra_isize = 0;
4342 EXT4_INODE_GET_XTIME(i_ctime, inode, raw_inode);
4343 EXT4_INODE_GET_XTIME(i_mtime, inode, raw_inode);
4344 EXT4_INODE_GET_XTIME(i_atime, inode, raw_inode);
4345 EXT4_EINODE_GET_XTIME(i_crtime, ei, raw_inode);
4347 inode->i_version = le32_to_cpu(raw_inode->i_disk_version);
4348 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4349 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
4350 inode->i_version |=
4351 (__u64)(le32_to_cpu(raw_inode->i_version_hi)) << 32;
4354 if (S_ISREG(inode->i_mode)) {
4355 inode->i_op = &ext4_file_inode_operations;
4356 inode->i_fop = &ext4_file_operations;
4357 ext4_set_aops(inode);
4358 } else if (S_ISDIR(inode->i_mode)) {
4359 inode->i_op = &ext4_dir_inode_operations;
4360 inode->i_fop = &ext4_dir_operations;
4361 } else if (S_ISLNK(inode->i_mode)) {
4362 if (ext4_inode_is_fast_symlink(inode)) {
4363 inode->i_op = &ext4_fast_symlink_inode_operations;
4364 nd_terminate_link(ei->i_data, inode->i_size,
4365 sizeof(ei->i_data) - 1);
4366 } else {
4367 inode->i_op = &ext4_symlink_inode_operations;
4368 ext4_set_aops(inode);
4370 } else {
4371 inode->i_op = &ext4_special_inode_operations;
4372 if (raw_inode->i_block[0])
4373 init_special_inode(inode, inode->i_mode,
4374 old_decode_dev(le32_to_cpu(raw_inode->i_block[0])));
4375 else
4376 init_special_inode(inode, inode->i_mode,
4377 new_decode_dev(le32_to_cpu(raw_inode->i_block[1])));
4379 brelse(iloc.bh);
4380 ext4_set_inode_flags(inode);
4381 unlock_new_inode(inode);
4382 return inode;
4384 bad_inode:
4385 iget_failed(inode);
4386 return ERR_PTR(ret);
4389 static int ext4_inode_blocks_set(handle_t *handle,
4390 struct ext4_inode *raw_inode,
4391 struct ext4_inode_info *ei)
4393 struct inode *inode = &(ei->vfs_inode);
4394 u64 i_blocks = inode->i_blocks;
4395 struct super_block *sb = inode->i_sb;
4397 if (i_blocks <= ~0U) {
4399 * i_blocks can be represnted in a 32 bit variable
4400 * as multiple of 512 bytes
4402 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
4403 raw_inode->i_blocks_high = 0;
4404 ei->i_flags &= ~EXT4_HUGE_FILE_FL;
4405 return 0;
4407 if (!EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_HUGE_FILE))
4408 return -EFBIG;
4410 if (i_blocks <= 0xffffffffffffULL) {
4412 * i_blocks can be represented in a 48 bit variable
4413 * as multiple of 512 bytes
4415 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
4416 raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
4417 ei->i_flags &= ~EXT4_HUGE_FILE_FL;
4418 } else {
4419 ei->i_flags |= EXT4_HUGE_FILE_FL;
4420 /* i_block is stored in file system block size */
4421 i_blocks = i_blocks >> (inode->i_blkbits - 9);
4422 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
4423 raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
4425 return 0;
4429 * Post the struct inode info into an on-disk inode location in the
4430 * buffer-cache. This gobbles the caller's reference to the
4431 * buffer_head in the inode location struct.
4433 * The caller must have write access to iloc->bh.
4435 static int ext4_do_update_inode(handle_t *handle,
4436 struct inode *inode,
4437 struct ext4_iloc *iloc)
4439 struct ext4_inode *raw_inode = ext4_raw_inode(iloc);
4440 struct ext4_inode_info *ei = EXT4_I(inode);
4441 struct buffer_head *bh = iloc->bh;
4442 int err = 0, rc, block;
4444 /* For fields not not tracking in the in-memory inode,
4445 * initialise them to zero for new inodes. */
4446 if (ei->i_state & EXT4_STATE_NEW)
4447 memset(raw_inode, 0, EXT4_SB(inode->i_sb)->s_inode_size);
4449 ext4_get_inode_flags(ei);
4450 raw_inode->i_mode = cpu_to_le16(inode->i_mode);
4451 if (!(test_opt(inode->i_sb, NO_UID32))) {
4452 raw_inode->i_uid_low = cpu_to_le16(low_16_bits(inode->i_uid));
4453 raw_inode->i_gid_low = cpu_to_le16(low_16_bits(inode->i_gid));
4455 * Fix up interoperability with old kernels. Otherwise, old inodes get
4456 * re-used with the upper 16 bits of the uid/gid intact
4458 if (!ei->i_dtime) {
4459 raw_inode->i_uid_high =
4460 cpu_to_le16(high_16_bits(inode->i_uid));
4461 raw_inode->i_gid_high =
4462 cpu_to_le16(high_16_bits(inode->i_gid));
4463 } else {
4464 raw_inode->i_uid_high = 0;
4465 raw_inode->i_gid_high = 0;
4467 } else {
4468 raw_inode->i_uid_low =
4469 cpu_to_le16(fs_high2lowuid(inode->i_uid));
4470 raw_inode->i_gid_low =
4471 cpu_to_le16(fs_high2lowgid(inode->i_gid));
4472 raw_inode->i_uid_high = 0;
4473 raw_inode->i_gid_high = 0;
4475 raw_inode->i_links_count = cpu_to_le16(inode->i_nlink);
4477 EXT4_INODE_SET_XTIME(i_ctime, inode, raw_inode);
4478 EXT4_INODE_SET_XTIME(i_mtime, inode, raw_inode);
4479 EXT4_INODE_SET_XTIME(i_atime, inode, raw_inode);
4480 EXT4_EINODE_SET_XTIME(i_crtime, ei, raw_inode);
4482 if (ext4_inode_blocks_set(handle, raw_inode, ei))
4483 goto out_brelse;
4484 raw_inode->i_dtime = cpu_to_le32(ei->i_dtime);
4485 /* clear the migrate flag in the raw_inode */
4486 raw_inode->i_flags = cpu_to_le32(ei->i_flags & ~EXT4_EXT_MIGRATE);
4487 if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
4488 cpu_to_le32(EXT4_OS_HURD))
4489 raw_inode->i_file_acl_high =
4490 cpu_to_le16(ei->i_file_acl >> 32);
4491 raw_inode->i_file_acl_lo = cpu_to_le32(ei->i_file_acl);
4492 ext4_isize_set(raw_inode, ei->i_disksize);
4493 if (ei->i_disksize > 0x7fffffffULL) {
4494 struct super_block *sb = inode->i_sb;
4495 if (!EXT4_HAS_RO_COMPAT_FEATURE(sb,
4496 EXT4_FEATURE_RO_COMPAT_LARGE_FILE) ||
4497 EXT4_SB(sb)->s_es->s_rev_level ==
4498 cpu_to_le32(EXT4_GOOD_OLD_REV)) {
4499 /* If this is the first large file
4500 * created, add a flag to the superblock.
4502 err = ext4_journal_get_write_access(handle,
4503 EXT4_SB(sb)->s_sbh);
4504 if (err)
4505 goto out_brelse;
4506 ext4_update_dynamic_rev(sb);
4507 EXT4_SET_RO_COMPAT_FEATURE(sb,
4508 EXT4_FEATURE_RO_COMPAT_LARGE_FILE);
4509 sb->s_dirt = 1;
4510 ext4_handle_sync(handle);
4511 err = ext4_handle_dirty_metadata(handle, inode,
4512 EXT4_SB(sb)->s_sbh);
4515 raw_inode->i_generation = cpu_to_le32(inode->i_generation);
4516 if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) {
4517 if (old_valid_dev(inode->i_rdev)) {
4518 raw_inode->i_block[0] =
4519 cpu_to_le32(old_encode_dev(inode->i_rdev));
4520 raw_inode->i_block[1] = 0;
4521 } else {
4522 raw_inode->i_block[0] = 0;
4523 raw_inode->i_block[1] =
4524 cpu_to_le32(new_encode_dev(inode->i_rdev));
4525 raw_inode->i_block[2] = 0;
4527 } else for (block = 0; block < EXT4_N_BLOCKS; block++)
4528 raw_inode->i_block[block] = ei->i_data[block];
4530 raw_inode->i_disk_version = cpu_to_le32(inode->i_version);
4531 if (ei->i_extra_isize) {
4532 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
4533 raw_inode->i_version_hi =
4534 cpu_to_le32(inode->i_version >> 32);
4535 raw_inode->i_extra_isize = cpu_to_le16(ei->i_extra_isize);
4538 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
4539 rc = ext4_handle_dirty_metadata(handle, inode, bh);
4540 if (!err)
4541 err = rc;
4542 ei->i_state &= ~EXT4_STATE_NEW;
4544 out_brelse:
4545 brelse(bh);
4546 ext4_std_error(inode->i_sb, err);
4547 return err;
4551 * ext4_write_inode()
4553 * We are called from a few places:
4555 * - Within generic_file_write() for O_SYNC files.
4556 * Here, there will be no transaction running. We wait for any running
4557 * trasnaction to commit.
4559 * - Within sys_sync(), kupdate and such.
4560 * We wait on commit, if tol to.
4562 * - Within prune_icache() (PF_MEMALLOC == true)
4563 * Here we simply return. We can't afford to block kswapd on the
4564 * journal commit.
4566 * In all cases it is actually safe for us to return without doing anything,
4567 * because the inode has been copied into a raw inode buffer in
4568 * ext4_mark_inode_dirty(). This is a correctness thing for O_SYNC and for
4569 * knfsd.
4571 * Note that we are absolutely dependent upon all inode dirtiers doing the
4572 * right thing: they *must* call mark_inode_dirty() after dirtying info in
4573 * which we are interested.
4575 * It would be a bug for them to not do this. The code:
4577 * mark_inode_dirty(inode)
4578 * stuff();
4579 * inode->i_size = expr;
4581 * is in error because a kswapd-driven write_inode() could occur while
4582 * `stuff()' is running, and the new i_size will be lost. Plus the inode
4583 * will no longer be on the superblock's dirty inode list.
4585 int ext4_write_inode(struct inode *inode, int wait)
4587 if (current->flags & PF_MEMALLOC)
4588 return 0;
4590 if (ext4_journal_current_handle()) {
4591 jbd_debug(1, "called recursively, non-PF_MEMALLOC!\n");
4592 dump_stack();
4593 return -EIO;
4596 if (!wait)
4597 return 0;
4599 return ext4_force_commit(inode->i_sb);
4602 int __ext4_write_dirty_metadata(struct inode *inode, struct buffer_head *bh)
4604 int err = 0;
4606 mark_buffer_dirty(bh);
4607 if (inode && inode_needs_sync(inode)) {
4608 sync_dirty_buffer(bh);
4609 if (buffer_req(bh) && !buffer_uptodate(bh)) {
4610 ext4_error(inode->i_sb, __func__,
4611 "IO error syncing inode, "
4612 "inode=%lu, block=%llu",
4613 inode->i_ino,
4614 (unsigned long long)bh->b_blocknr);
4615 err = -EIO;
4618 return err;
4622 * ext4_setattr()
4624 * Called from notify_change.
4626 * We want to trap VFS attempts to truncate the file as soon as
4627 * possible. In particular, we want to make sure that when the VFS
4628 * shrinks i_size, we put the inode on the orphan list and modify
4629 * i_disksize immediately, so that during the subsequent flushing of
4630 * dirty pages and freeing of disk blocks, we can guarantee that any
4631 * commit will leave the blocks being flushed in an unused state on
4632 * disk. (On recovery, the inode will get truncated and the blocks will
4633 * be freed, so we have a strong guarantee that no future commit will
4634 * leave these blocks visible to the user.)
4636 * Another thing we have to assure is that if we are in ordered mode
4637 * and inode is still attached to the committing transaction, we must
4638 * we start writeout of all the dirty pages which are being truncated.
4639 * This way we are sure that all the data written in the previous
4640 * transaction are already on disk (truncate waits for pages under
4641 * writeback).
4643 * Called with inode->i_mutex down.
4645 int ext4_setattr(struct dentry *dentry, struct iattr *attr)
4647 struct inode *inode = dentry->d_inode;
4648 int error, rc = 0;
4649 const unsigned int ia_valid = attr->ia_valid;
4651 error = inode_change_ok(inode, attr);
4652 if (error)
4653 return error;
4655 if ((ia_valid & ATTR_UID && attr->ia_uid != inode->i_uid) ||
4656 (ia_valid & ATTR_GID && attr->ia_gid != inode->i_gid)) {
4657 handle_t *handle;
4659 /* (user+group)*(old+new) structure, inode write (sb,
4660 * inode block, ? - but truncate inode update has it) */
4661 handle = ext4_journal_start(inode, 2*(EXT4_QUOTA_INIT_BLOCKS(inode->i_sb)+
4662 EXT4_QUOTA_DEL_BLOCKS(inode->i_sb))+3);
4663 if (IS_ERR(handle)) {
4664 error = PTR_ERR(handle);
4665 goto err_out;
4667 error = DQUOT_TRANSFER(inode, attr) ? -EDQUOT : 0;
4668 if (error) {
4669 ext4_journal_stop(handle);
4670 return error;
4672 /* Update corresponding info in inode so that everything is in
4673 * one transaction */
4674 if (attr->ia_valid & ATTR_UID)
4675 inode->i_uid = attr->ia_uid;
4676 if (attr->ia_valid & ATTR_GID)
4677 inode->i_gid = attr->ia_gid;
4678 error = ext4_mark_inode_dirty(handle, inode);
4679 ext4_journal_stop(handle);
4682 if (attr->ia_valid & ATTR_SIZE) {
4683 if (!(EXT4_I(inode)->i_flags & EXT4_EXTENTS_FL)) {
4684 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4686 if (attr->ia_size > sbi->s_bitmap_maxbytes) {
4687 error = -EFBIG;
4688 goto err_out;
4693 if (S_ISREG(inode->i_mode) &&
4694 attr->ia_valid & ATTR_SIZE && attr->ia_size < inode->i_size) {
4695 handle_t *handle;
4697 handle = ext4_journal_start(inode, 3);
4698 if (IS_ERR(handle)) {
4699 error = PTR_ERR(handle);
4700 goto err_out;
4703 error = ext4_orphan_add(handle, inode);
4704 EXT4_I(inode)->i_disksize = attr->ia_size;
4705 rc = ext4_mark_inode_dirty(handle, inode);
4706 if (!error)
4707 error = rc;
4708 ext4_journal_stop(handle);
4710 if (ext4_should_order_data(inode)) {
4711 error = ext4_begin_ordered_truncate(inode,
4712 attr->ia_size);
4713 if (error) {
4714 /* Do as much error cleanup as possible */
4715 handle = ext4_journal_start(inode, 3);
4716 if (IS_ERR(handle)) {
4717 ext4_orphan_del(NULL, inode);
4718 goto err_out;
4720 ext4_orphan_del(handle, inode);
4721 ext4_journal_stop(handle);
4722 goto err_out;
4727 rc = inode_setattr(inode, attr);
4729 /* If inode_setattr's call to ext4_truncate failed to get a
4730 * transaction handle at all, we need to clean up the in-core
4731 * orphan list manually. */
4732 if (inode->i_nlink)
4733 ext4_orphan_del(NULL, inode);
4735 if (!rc && (ia_valid & ATTR_MODE))
4736 rc = ext4_acl_chmod(inode);
4738 err_out:
4739 ext4_std_error(inode->i_sb, error);
4740 if (!error)
4741 error = rc;
4742 return error;
4745 int ext4_getattr(struct vfsmount *mnt, struct dentry *dentry,
4746 struct kstat *stat)
4748 struct inode *inode;
4749 unsigned long delalloc_blocks;
4751 inode = dentry->d_inode;
4752 generic_fillattr(inode, stat);
4755 * We can't update i_blocks if the block allocation is delayed
4756 * otherwise in the case of system crash before the real block
4757 * allocation is done, we will have i_blocks inconsistent with
4758 * on-disk file blocks.
4759 * We always keep i_blocks updated together with real
4760 * allocation. But to not confuse with user, stat
4761 * will return the blocks that include the delayed allocation
4762 * blocks for this file.
4764 spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
4765 delalloc_blocks = EXT4_I(inode)->i_reserved_data_blocks;
4766 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
4768 stat->blocks += (delalloc_blocks << inode->i_sb->s_blocksize_bits)>>9;
4769 return 0;
4772 static int ext4_indirect_trans_blocks(struct inode *inode, int nrblocks,
4773 int chunk)
4775 int indirects;
4777 /* if nrblocks are contiguous */
4778 if (chunk) {
4780 * With N contiguous data blocks, it need at most
4781 * N/EXT4_ADDR_PER_BLOCK(inode->i_sb) indirect blocks
4782 * 2 dindirect blocks
4783 * 1 tindirect block
4785 indirects = nrblocks / EXT4_ADDR_PER_BLOCK(inode->i_sb);
4786 return indirects + 3;
4789 * if nrblocks are not contiguous, worse case, each block touch
4790 * a indirect block, and each indirect block touch a double indirect
4791 * block, plus a triple indirect block
4793 indirects = nrblocks * 2 + 1;
4794 return indirects;
4797 static int ext4_index_trans_blocks(struct inode *inode, int nrblocks, int chunk)
4799 if (!(EXT4_I(inode)->i_flags & EXT4_EXTENTS_FL))
4800 return ext4_indirect_trans_blocks(inode, nrblocks, chunk);
4801 return ext4_ext_index_trans_blocks(inode, nrblocks, chunk);
4805 * Account for index blocks, block groups bitmaps and block group
4806 * descriptor blocks if modify datablocks and index blocks
4807 * worse case, the indexs blocks spread over different block groups
4809 * If datablocks are discontiguous, they are possible to spread over
4810 * different block groups too. If they are contiugous, with flexbg,
4811 * they could still across block group boundary.
4813 * Also account for superblock, inode, quota and xattr blocks
4815 int ext4_meta_trans_blocks(struct inode *inode, int nrblocks, int chunk)
4817 int groups, gdpblocks;
4818 int idxblocks;
4819 int ret = 0;
4822 * How many index blocks need to touch to modify nrblocks?
4823 * The "Chunk" flag indicating whether the nrblocks is
4824 * physically contiguous on disk
4826 * For Direct IO and fallocate, they calls get_block to allocate
4827 * one single extent at a time, so they could set the "Chunk" flag
4829 idxblocks = ext4_index_trans_blocks(inode, nrblocks, chunk);
4831 ret = idxblocks;
4834 * Now let's see how many group bitmaps and group descriptors need
4835 * to account
4837 groups = idxblocks;
4838 if (chunk)
4839 groups += 1;
4840 else
4841 groups += nrblocks;
4843 gdpblocks = groups;
4844 if (groups > EXT4_SB(inode->i_sb)->s_groups_count)
4845 groups = EXT4_SB(inode->i_sb)->s_groups_count;
4846 if (groups > EXT4_SB(inode->i_sb)->s_gdb_count)
4847 gdpblocks = EXT4_SB(inode->i_sb)->s_gdb_count;
4849 /* bitmaps and block group descriptor blocks */
4850 ret += groups + gdpblocks;
4852 /* Blocks for super block, inode, quota and xattr blocks */
4853 ret += EXT4_META_TRANS_BLOCKS(inode->i_sb);
4855 return ret;
4859 * Calulate the total number of credits to reserve to fit
4860 * the modification of a single pages into a single transaction,
4861 * which may include multiple chunks of block allocations.
4863 * This could be called via ext4_write_begin()
4865 * We need to consider the worse case, when
4866 * one new block per extent.
4868 int ext4_writepage_trans_blocks(struct inode *inode)
4870 int bpp = ext4_journal_blocks_per_page(inode);
4871 int ret;
4873 ret = ext4_meta_trans_blocks(inode, bpp, 0);
4875 /* Account for data blocks for journalled mode */
4876 if (ext4_should_journal_data(inode))
4877 ret += bpp;
4878 return ret;
4882 * Calculate the journal credits for a chunk of data modification.
4884 * This is called from DIO, fallocate or whoever calling
4885 * ext4_get_blocks_wrap() to map/allocate a chunk of contigous disk blocks.
4887 * journal buffers for data blocks are not included here, as DIO
4888 * and fallocate do no need to journal data buffers.
4890 int ext4_chunk_trans_blocks(struct inode *inode, int nrblocks)
4892 return ext4_meta_trans_blocks(inode, nrblocks, 1);
4896 * The caller must have previously called ext4_reserve_inode_write().
4897 * Give this, we know that the caller already has write access to iloc->bh.
4899 int ext4_mark_iloc_dirty(handle_t *handle,
4900 struct inode *inode, struct ext4_iloc *iloc)
4902 int err = 0;
4904 if (test_opt(inode->i_sb, I_VERSION))
4905 inode_inc_iversion(inode);
4907 /* the do_update_inode consumes one bh->b_count */
4908 get_bh(iloc->bh);
4910 /* ext4_do_update_inode() does jbd2_journal_dirty_metadata */
4911 err = ext4_do_update_inode(handle, inode, iloc);
4912 put_bh(iloc->bh);
4913 return err;
4917 * On success, We end up with an outstanding reference count against
4918 * iloc->bh. This _must_ be cleaned up later.
4922 ext4_reserve_inode_write(handle_t *handle, struct inode *inode,
4923 struct ext4_iloc *iloc)
4925 int err;
4927 err = ext4_get_inode_loc(inode, iloc);
4928 if (!err) {
4929 BUFFER_TRACE(iloc->bh, "get_write_access");
4930 err = ext4_journal_get_write_access(handle, iloc->bh);
4931 if (err) {
4932 brelse(iloc->bh);
4933 iloc->bh = NULL;
4936 ext4_std_error(inode->i_sb, err);
4937 return err;
4941 * Expand an inode by new_extra_isize bytes.
4942 * Returns 0 on success or negative error number on failure.
4944 static int ext4_expand_extra_isize(struct inode *inode,
4945 unsigned int new_extra_isize,
4946 struct ext4_iloc iloc,
4947 handle_t *handle)
4949 struct ext4_inode *raw_inode;
4950 struct ext4_xattr_ibody_header *header;
4951 struct ext4_xattr_entry *entry;
4953 if (EXT4_I(inode)->i_extra_isize >= new_extra_isize)
4954 return 0;
4956 raw_inode = ext4_raw_inode(&iloc);
4958 header = IHDR(inode, raw_inode);
4959 entry = IFIRST(header);
4961 /* No extended attributes present */
4962 if (!(EXT4_I(inode)->i_state & EXT4_STATE_XATTR) ||
4963 header->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC)) {
4964 memset((void *)raw_inode + EXT4_GOOD_OLD_INODE_SIZE, 0,
4965 new_extra_isize);
4966 EXT4_I(inode)->i_extra_isize = new_extra_isize;
4967 return 0;
4970 /* try to expand with EAs present */
4971 return ext4_expand_extra_isize_ea(inode, new_extra_isize,
4972 raw_inode, handle);
4976 * What we do here is to mark the in-core inode as clean with respect to inode
4977 * dirtiness (it may still be data-dirty).
4978 * This means that the in-core inode may be reaped by prune_icache
4979 * without having to perform any I/O. This is a very good thing,
4980 * because *any* task may call prune_icache - even ones which
4981 * have a transaction open against a different journal.
4983 * Is this cheating? Not really. Sure, we haven't written the
4984 * inode out, but prune_icache isn't a user-visible syncing function.
4985 * Whenever the user wants stuff synced (sys_sync, sys_msync, sys_fsync)
4986 * we start and wait on commits.
4988 * Is this efficient/effective? Well, we're being nice to the system
4989 * by cleaning up our inodes proactively so they can be reaped
4990 * without I/O. But we are potentially leaving up to five seconds'
4991 * worth of inodes floating about which prune_icache wants us to
4992 * write out. One way to fix that would be to get prune_icache()
4993 * to do a write_super() to free up some memory. It has the desired
4994 * effect.
4996 int ext4_mark_inode_dirty(handle_t *handle, struct inode *inode)
4998 struct ext4_iloc iloc;
4999 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
5000 static unsigned int mnt_count;
5001 int err, ret;
5003 might_sleep();
5004 err = ext4_reserve_inode_write(handle, inode, &iloc);
5005 if (ext4_handle_valid(handle) &&
5006 EXT4_I(inode)->i_extra_isize < sbi->s_want_extra_isize &&
5007 !(EXT4_I(inode)->i_state & EXT4_STATE_NO_EXPAND)) {
5009 * We need extra buffer credits since we may write into EA block
5010 * with this same handle. If journal_extend fails, then it will
5011 * only result in a minor loss of functionality for that inode.
5012 * If this is felt to be critical, then e2fsck should be run to
5013 * force a large enough s_min_extra_isize.
5015 if ((jbd2_journal_extend(handle,
5016 EXT4_DATA_TRANS_BLOCKS(inode->i_sb))) == 0) {
5017 ret = ext4_expand_extra_isize(inode,
5018 sbi->s_want_extra_isize,
5019 iloc, handle);
5020 if (ret) {
5021 EXT4_I(inode)->i_state |= EXT4_STATE_NO_EXPAND;
5022 if (mnt_count !=
5023 le16_to_cpu(sbi->s_es->s_mnt_count)) {
5024 ext4_warning(inode->i_sb, __func__,
5025 "Unable to expand inode %lu. Delete"
5026 " some EAs or run e2fsck.",
5027 inode->i_ino);
5028 mnt_count =
5029 le16_to_cpu(sbi->s_es->s_mnt_count);
5034 if (!err)
5035 err = ext4_mark_iloc_dirty(handle, inode, &iloc);
5036 return err;
5040 * ext4_dirty_inode() is called from __mark_inode_dirty()
5042 * We're really interested in the case where a file is being extended.
5043 * i_size has been changed by generic_commit_write() and we thus need
5044 * to include the updated inode in the current transaction.
5046 * Also, DQUOT_ALLOC_SPACE() will always dirty the inode when blocks
5047 * are allocated to the file.
5049 * If the inode is marked synchronous, we don't honour that here - doing
5050 * so would cause a commit on atime updates, which we don't bother doing.
5051 * We handle synchronous inodes at the highest possible level.
5053 void ext4_dirty_inode(struct inode *inode)
5055 handle_t *current_handle = ext4_journal_current_handle();
5056 handle_t *handle;
5058 if (!ext4_handle_valid(current_handle)) {
5059 ext4_mark_inode_dirty(current_handle, inode);
5060 return;
5063 handle = ext4_journal_start(inode, 2);
5064 if (IS_ERR(handle))
5065 goto out;
5066 if (current_handle &&
5067 current_handle->h_transaction != handle->h_transaction) {
5068 /* This task has a transaction open against a different fs */
5069 printk(KERN_EMERG "%s: transactions do not match!\n",
5070 __func__);
5071 } else {
5072 jbd_debug(5, "marking dirty. outer handle=%p\n",
5073 current_handle);
5074 ext4_mark_inode_dirty(handle, inode);
5076 ext4_journal_stop(handle);
5077 out:
5078 return;
5081 #if 0
5083 * Bind an inode's backing buffer_head into this transaction, to prevent
5084 * it from being flushed to disk early. Unlike
5085 * ext4_reserve_inode_write, this leaves behind no bh reference and
5086 * returns no iloc structure, so the caller needs to repeat the iloc
5087 * lookup to mark the inode dirty later.
5089 static int ext4_pin_inode(handle_t *handle, struct inode *inode)
5091 struct ext4_iloc iloc;
5093 int err = 0;
5094 if (handle) {
5095 err = ext4_get_inode_loc(inode, &iloc);
5096 if (!err) {
5097 BUFFER_TRACE(iloc.bh, "get_write_access");
5098 err = jbd2_journal_get_write_access(handle, iloc.bh);
5099 if (!err)
5100 err = ext4_handle_dirty_metadata(handle,
5101 inode,
5102 iloc.bh);
5103 brelse(iloc.bh);
5106 ext4_std_error(inode->i_sb, err);
5107 return err;
5109 #endif
5111 int ext4_change_inode_journal_flag(struct inode *inode, int val)
5113 journal_t *journal;
5114 handle_t *handle;
5115 int err;
5118 * We have to be very careful here: changing a data block's
5119 * journaling status dynamically is dangerous. If we write a
5120 * data block to the journal, change the status and then delete
5121 * that block, we risk forgetting to revoke the old log record
5122 * from the journal and so a subsequent replay can corrupt data.
5123 * So, first we make sure that the journal is empty and that
5124 * nobody is changing anything.
5127 journal = EXT4_JOURNAL(inode);
5128 if (!journal)
5129 return 0;
5130 if (is_journal_aborted(journal))
5131 return -EROFS;
5133 jbd2_journal_lock_updates(journal);
5134 jbd2_journal_flush(journal);
5137 * OK, there are no updates running now, and all cached data is
5138 * synced to disk. We are now in a completely consistent state
5139 * which doesn't have anything in the journal, and we know that
5140 * no filesystem updates are running, so it is safe to modify
5141 * the inode's in-core data-journaling state flag now.
5144 if (val)
5145 EXT4_I(inode)->i_flags |= EXT4_JOURNAL_DATA_FL;
5146 else
5147 EXT4_I(inode)->i_flags &= ~EXT4_JOURNAL_DATA_FL;
5148 ext4_set_aops(inode);
5150 jbd2_journal_unlock_updates(journal);
5152 /* Finally we can mark the inode as dirty. */
5154 handle = ext4_journal_start(inode, 1);
5155 if (IS_ERR(handle))
5156 return PTR_ERR(handle);
5158 err = ext4_mark_inode_dirty(handle, inode);
5159 ext4_handle_sync(handle);
5160 ext4_journal_stop(handle);
5161 ext4_std_error(inode->i_sb, err);
5163 return err;
5166 static int ext4_bh_unmapped(handle_t *handle, struct buffer_head *bh)
5168 return !buffer_mapped(bh);
5171 int ext4_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
5173 struct page *page = vmf->page;
5174 loff_t size;
5175 unsigned long len;
5176 int ret = -EINVAL;
5177 void *fsdata;
5178 struct file *file = vma->vm_file;
5179 struct inode *inode = file->f_path.dentry->d_inode;
5180 struct address_space *mapping = inode->i_mapping;
5183 * Get i_alloc_sem to stop truncates messing with the inode. We cannot
5184 * get i_mutex because we are already holding mmap_sem.
5186 down_read(&inode->i_alloc_sem);
5187 size = i_size_read(inode);
5188 if (page->mapping != mapping || size <= page_offset(page)
5189 || !PageUptodate(page)) {
5190 /* page got truncated from under us? */
5191 goto out_unlock;
5193 ret = 0;
5194 if (PageMappedToDisk(page))
5195 goto out_unlock;
5197 if (page->index == size >> PAGE_CACHE_SHIFT)
5198 len = size & ~PAGE_CACHE_MASK;
5199 else
5200 len = PAGE_CACHE_SIZE;
5202 if (page_has_buffers(page)) {
5203 /* return if we have all the buffers mapped */
5204 if (!walk_page_buffers(NULL, page_buffers(page), 0, len, NULL,
5205 ext4_bh_unmapped))
5206 goto out_unlock;
5209 * OK, we need to fill the hole... Do write_begin write_end
5210 * to do block allocation/reservation.We are not holding
5211 * inode.i__mutex here. That allow * parallel write_begin,
5212 * write_end call. lock_page prevent this from happening
5213 * on the same page though
5215 ret = mapping->a_ops->write_begin(file, mapping, page_offset(page),
5216 len, AOP_FLAG_UNINTERRUPTIBLE, &page, &fsdata);
5217 if (ret < 0)
5218 goto out_unlock;
5219 ret = mapping->a_ops->write_end(file, mapping, page_offset(page),
5220 len, len, page, fsdata);
5221 if (ret < 0)
5222 goto out_unlock;
5223 ret = 0;
5224 out_unlock:
5225 if (ret)
5226 ret = VM_FAULT_SIGBUS;
5227 up_read(&inode->i_alloc_sem);
5228 return ret;