char: moxa, prevent opening unavailable ports
[linux-2.6/linux-acpi-2.6/ibm-acpi-2.6.git] / fs / ext4 / inode.c
blob725f20ab62083889a5c3001dc7df4afd74049dda
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);
1079 clear_buffer_unwritten(bh);
1082 * Try to see if we can get the block without requesting
1083 * for new file system block.
1085 down_read((&EXT4_I(inode)->i_data_sem));
1086 if (EXT4_I(inode)->i_flags & EXT4_EXTENTS_FL) {
1087 retval = ext4_ext_get_blocks(handle, inode, block, max_blocks,
1088 bh, 0, 0);
1089 } else {
1090 retval = ext4_get_blocks_handle(handle,
1091 inode, block, max_blocks, bh, 0, 0);
1093 up_read((&EXT4_I(inode)->i_data_sem));
1095 /* If it is only a block(s) look up */
1096 if (!create)
1097 return retval;
1100 * Returns if the blocks have already allocated
1102 * Note that if blocks have been preallocated
1103 * ext4_ext_get_block() returns th create = 0
1104 * with buffer head unmapped.
1106 if (retval > 0 && buffer_mapped(bh))
1107 return retval;
1110 * When we call get_blocks without the create flag, the
1111 * BH_Unwritten flag could have gotten set if the blocks
1112 * requested were part of a uninitialized extent. We need to
1113 * clear this flag now that we are committed to convert all or
1114 * part of the uninitialized extent to be an initialized
1115 * extent. This is because we need to avoid the combination
1116 * of BH_Unwritten and BH_Mapped flags being simultaneously
1117 * set on the buffer_head.
1119 clear_buffer_unwritten(bh);
1122 * New blocks allocate and/or writing to uninitialized extent
1123 * will possibly result in updating i_data, so we take
1124 * the write lock of i_data_sem, and call get_blocks()
1125 * with create == 1 flag.
1127 down_write((&EXT4_I(inode)->i_data_sem));
1130 * if the caller is from delayed allocation writeout path
1131 * we have already reserved fs blocks for allocation
1132 * let the underlying get_block() function know to
1133 * avoid double accounting
1135 if (flag)
1136 EXT4_I(inode)->i_delalloc_reserved_flag = 1;
1138 * We need to check for EXT4 here because migrate
1139 * could have changed the inode type in between
1141 if (EXT4_I(inode)->i_flags & EXT4_EXTENTS_FL) {
1142 retval = ext4_ext_get_blocks(handle, inode, block, max_blocks,
1143 bh, create, extend_disksize);
1144 } else {
1145 retval = ext4_get_blocks_handle(handle, inode, block,
1146 max_blocks, bh, create, extend_disksize);
1148 if (retval > 0 && buffer_new(bh)) {
1150 * We allocated new blocks which will result in
1151 * i_data's format changing. Force the migrate
1152 * to fail by clearing migrate flags
1154 EXT4_I(inode)->i_flags = EXT4_I(inode)->i_flags &
1155 ~EXT4_EXT_MIGRATE;
1159 if (flag) {
1160 EXT4_I(inode)->i_delalloc_reserved_flag = 0;
1162 * Update reserved blocks/metadata blocks
1163 * after successful block allocation
1164 * which were deferred till now
1166 if ((retval > 0) && buffer_delay(bh))
1167 ext4_da_update_reserve_space(inode, retval);
1170 up_write((&EXT4_I(inode)->i_data_sem));
1171 return retval;
1174 /* Maximum number of blocks we map for direct IO at once. */
1175 #define DIO_MAX_BLOCKS 4096
1177 int ext4_get_block(struct inode *inode, sector_t iblock,
1178 struct buffer_head *bh_result, int create)
1180 handle_t *handle = ext4_journal_current_handle();
1181 int ret = 0, started = 0;
1182 unsigned max_blocks = bh_result->b_size >> inode->i_blkbits;
1183 int dio_credits;
1185 if (create && !handle) {
1186 /* Direct IO write... */
1187 if (max_blocks > DIO_MAX_BLOCKS)
1188 max_blocks = DIO_MAX_BLOCKS;
1189 dio_credits = ext4_chunk_trans_blocks(inode, max_blocks);
1190 handle = ext4_journal_start(inode, dio_credits);
1191 if (IS_ERR(handle)) {
1192 ret = PTR_ERR(handle);
1193 goto out;
1195 started = 1;
1198 ret = ext4_get_blocks_wrap(handle, inode, iblock,
1199 max_blocks, bh_result, create, 0, 0);
1200 if (ret > 0) {
1201 bh_result->b_size = (ret << inode->i_blkbits);
1202 ret = 0;
1204 if (started)
1205 ext4_journal_stop(handle);
1206 out:
1207 return ret;
1211 * `handle' can be NULL if create is zero
1213 struct buffer_head *ext4_getblk(handle_t *handle, struct inode *inode,
1214 ext4_lblk_t block, int create, int *errp)
1216 struct buffer_head dummy;
1217 int fatal = 0, err;
1219 J_ASSERT(handle != NULL || create == 0);
1221 dummy.b_state = 0;
1222 dummy.b_blocknr = -1000;
1223 buffer_trace_init(&dummy.b_history);
1224 err = ext4_get_blocks_wrap(handle, inode, block, 1,
1225 &dummy, create, 1, 0);
1227 * ext4_get_blocks_handle() returns number of blocks
1228 * mapped. 0 in case of a HOLE.
1230 if (err > 0) {
1231 if (err > 1)
1232 WARN_ON(1);
1233 err = 0;
1235 *errp = err;
1236 if (!err && buffer_mapped(&dummy)) {
1237 struct buffer_head *bh;
1238 bh = sb_getblk(inode->i_sb, dummy.b_blocknr);
1239 if (!bh) {
1240 *errp = -EIO;
1241 goto err;
1243 if (buffer_new(&dummy)) {
1244 J_ASSERT(create != 0);
1245 J_ASSERT(handle != NULL);
1248 * Now that we do not always journal data, we should
1249 * keep in mind whether this should always journal the
1250 * new buffer as metadata. For now, regular file
1251 * writes use ext4_get_block instead, so it's not a
1252 * problem.
1254 lock_buffer(bh);
1255 BUFFER_TRACE(bh, "call get_create_access");
1256 fatal = ext4_journal_get_create_access(handle, bh);
1257 if (!fatal && !buffer_uptodate(bh)) {
1258 memset(bh->b_data, 0, inode->i_sb->s_blocksize);
1259 set_buffer_uptodate(bh);
1261 unlock_buffer(bh);
1262 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
1263 err = ext4_handle_dirty_metadata(handle, inode, bh);
1264 if (!fatal)
1265 fatal = err;
1266 } else {
1267 BUFFER_TRACE(bh, "not a new buffer");
1269 if (fatal) {
1270 *errp = fatal;
1271 brelse(bh);
1272 bh = NULL;
1274 return bh;
1276 err:
1277 return NULL;
1280 struct buffer_head *ext4_bread(handle_t *handle, struct inode *inode,
1281 ext4_lblk_t block, int create, int *err)
1283 struct buffer_head *bh;
1285 bh = ext4_getblk(handle, inode, block, create, err);
1286 if (!bh)
1287 return bh;
1288 if (buffer_uptodate(bh))
1289 return bh;
1290 ll_rw_block(READ_META, 1, &bh);
1291 wait_on_buffer(bh);
1292 if (buffer_uptodate(bh))
1293 return bh;
1294 put_bh(bh);
1295 *err = -EIO;
1296 return NULL;
1299 static int walk_page_buffers(handle_t *handle,
1300 struct buffer_head *head,
1301 unsigned from,
1302 unsigned to,
1303 int *partial,
1304 int (*fn)(handle_t *handle,
1305 struct buffer_head *bh))
1307 struct buffer_head *bh;
1308 unsigned block_start, block_end;
1309 unsigned blocksize = head->b_size;
1310 int err, ret = 0;
1311 struct buffer_head *next;
1313 for (bh = head, block_start = 0;
1314 ret == 0 && (bh != head || !block_start);
1315 block_start = block_end, bh = next)
1317 next = bh->b_this_page;
1318 block_end = block_start + blocksize;
1319 if (block_end <= from || block_start >= to) {
1320 if (partial && !buffer_uptodate(bh))
1321 *partial = 1;
1322 continue;
1324 err = (*fn)(handle, bh);
1325 if (!ret)
1326 ret = err;
1328 return ret;
1332 * To preserve ordering, it is essential that the hole instantiation and
1333 * the data write be encapsulated in a single transaction. We cannot
1334 * close off a transaction and start a new one between the ext4_get_block()
1335 * and the commit_write(). So doing the jbd2_journal_start at the start of
1336 * prepare_write() is the right place.
1338 * Also, this function can nest inside ext4_writepage() ->
1339 * block_write_full_page(). In that case, we *know* that ext4_writepage()
1340 * has generated enough buffer credits to do the whole page. So we won't
1341 * block on the journal in that case, which is good, because the caller may
1342 * be PF_MEMALLOC.
1344 * By accident, ext4 can be reentered when a transaction is open via
1345 * quota file writes. If we were to commit the transaction while thus
1346 * reentered, there can be a deadlock - we would be holding a quota
1347 * lock, and the commit would never complete if another thread had a
1348 * transaction open and was blocking on the quota lock - a ranking
1349 * violation.
1351 * So what we do is to rely on the fact that jbd2_journal_stop/journal_start
1352 * will _not_ run commit under these circumstances because handle->h_ref
1353 * is elevated. We'll still have enough credits for the tiny quotafile
1354 * write.
1356 static int do_journal_get_write_access(handle_t *handle,
1357 struct buffer_head *bh)
1359 if (!buffer_mapped(bh) || buffer_freed(bh))
1360 return 0;
1361 return ext4_journal_get_write_access(handle, bh);
1364 static int ext4_write_begin(struct file *file, struct address_space *mapping,
1365 loff_t pos, unsigned len, unsigned flags,
1366 struct page **pagep, void **fsdata)
1368 struct inode *inode = mapping->host;
1369 int ret, needed_blocks = ext4_writepage_trans_blocks(inode);
1370 handle_t *handle;
1371 int retries = 0;
1372 struct page *page;
1373 pgoff_t index;
1374 unsigned from, to;
1376 trace_mark(ext4_write_begin,
1377 "dev %s ino %lu pos %llu len %u flags %u",
1378 inode->i_sb->s_id, inode->i_ino,
1379 (unsigned long long) pos, len, flags);
1380 index = pos >> PAGE_CACHE_SHIFT;
1381 from = pos & (PAGE_CACHE_SIZE - 1);
1382 to = from + len;
1384 retry:
1385 handle = ext4_journal_start(inode, needed_blocks);
1386 if (IS_ERR(handle)) {
1387 ret = PTR_ERR(handle);
1388 goto out;
1391 /* We cannot recurse into the filesystem as the transaction is already
1392 * started */
1393 flags |= AOP_FLAG_NOFS;
1395 page = grab_cache_page_write_begin(mapping, index, flags);
1396 if (!page) {
1397 ext4_journal_stop(handle);
1398 ret = -ENOMEM;
1399 goto out;
1401 *pagep = page;
1403 ret = block_write_begin(file, mapping, pos, len, flags, pagep, fsdata,
1404 ext4_get_block);
1406 if (!ret && ext4_should_journal_data(inode)) {
1407 ret = walk_page_buffers(handle, page_buffers(page),
1408 from, to, NULL, do_journal_get_write_access);
1411 if (ret) {
1412 unlock_page(page);
1413 ext4_journal_stop(handle);
1414 page_cache_release(page);
1416 * block_write_begin may have instantiated a few blocks
1417 * outside i_size. Trim these off again. Don't need
1418 * i_size_read because we hold i_mutex.
1420 if (pos + len > inode->i_size)
1421 vmtruncate(inode, inode->i_size);
1424 if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
1425 goto retry;
1426 out:
1427 return ret;
1430 /* For write_end() in data=journal mode */
1431 static int write_end_fn(handle_t *handle, struct buffer_head *bh)
1433 if (!buffer_mapped(bh) || buffer_freed(bh))
1434 return 0;
1435 set_buffer_uptodate(bh);
1436 return ext4_handle_dirty_metadata(handle, NULL, bh);
1440 * We need to pick up the new inode size which generic_commit_write gave us
1441 * `file' can be NULL - eg, when called from page_symlink().
1443 * ext4 never places buffers on inode->i_mapping->private_list. metadata
1444 * buffers are managed internally.
1446 static int ext4_ordered_write_end(struct file *file,
1447 struct address_space *mapping,
1448 loff_t pos, unsigned len, unsigned copied,
1449 struct page *page, void *fsdata)
1451 handle_t *handle = ext4_journal_current_handle();
1452 struct inode *inode = mapping->host;
1453 int ret = 0, ret2;
1455 trace_mark(ext4_ordered_write_end,
1456 "dev %s ino %lu pos %llu len %u copied %u",
1457 inode->i_sb->s_id, inode->i_ino,
1458 (unsigned long long) pos, len, copied);
1459 ret = ext4_jbd2_file_inode(handle, inode);
1461 if (ret == 0) {
1462 loff_t new_i_size;
1464 new_i_size = pos + copied;
1465 if (new_i_size > EXT4_I(inode)->i_disksize) {
1466 ext4_update_i_disksize(inode, new_i_size);
1467 /* We need to mark inode dirty even if
1468 * new_i_size is less that inode->i_size
1469 * bu greater than i_disksize.(hint delalloc)
1471 ext4_mark_inode_dirty(handle, inode);
1474 ret2 = generic_write_end(file, mapping, pos, len, copied,
1475 page, fsdata);
1476 copied = ret2;
1477 if (ret2 < 0)
1478 ret = ret2;
1480 ret2 = ext4_journal_stop(handle);
1481 if (!ret)
1482 ret = ret2;
1484 return ret ? ret : copied;
1487 static int ext4_writeback_write_end(struct file *file,
1488 struct address_space *mapping,
1489 loff_t pos, unsigned len, unsigned copied,
1490 struct page *page, void *fsdata)
1492 handle_t *handle = ext4_journal_current_handle();
1493 struct inode *inode = mapping->host;
1494 int ret = 0, ret2;
1495 loff_t new_i_size;
1497 trace_mark(ext4_writeback_write_end,
1498 "dev %s ino %lu pos %llu len %u copied %u",
1499 inode->i_sb->s_id, inode->i_ino,
1500 (unsigned long long) pos, len, copied);
1501 new_i_size = pos + copied;
1502 if (new_i_size > EXT4_I(inode)->i_disksize) {
1503 ext4_update_i_disksize(inode, new_i_size);
1504 /* We need to mark inode dirty even if
1505 * new_i_size is less that inode->i_size
1506 * bu greater than i_disksize.(hint delalloc)
1508 ext4_mark_inode_dirty(handle, inode);
1511 ret2 = generic_write_end(file, mapping, pos, len, copied,
1512 page, fsdata);
1513 copied = ret2;
1514 if (ret2 < 0)
1515 ret = ret2;
1517 ret2 = ext4_journal_stop(handle);
1518 if (!ret)
1519 ret = ret2;
1521 return ret ? ret : copied;
1524 static int ext4_journalled_write_end(struct file *file,
1525 struct address_space *mapping,
1526 loff_t pos, unsigned len, unsigned copied,
1527 struct page *page, void *fsdata)
1529 handle_t *handle = ext4_journal_current_handle();
1530 struct inode *inode = mapping->host;
1531 int ret = 0, ret2;
1532 int partial = 0;
1533 unsigned from, to;
1534 loff_t new_i_size;
1536 trace_mark(ext4_journalled_write_end,
1537 "dev %s ino %lu pos %llu len %u copied %u",
1538 inode->i_sb->s_id, inode->i_ino,
1539 (unsigned long long) pos, len, copied);
1540 from = pos & (PAGE_CACHE_SIZE - 1);
1541 to = from + len;
1543 if (copied < len) {
1544 if (!PageUptodate(page))
1545 copied = 0;
1546 page_zero_new_buffers(page, from+copied, to);
1549 ret = walk_page_buffers(handle, page_buffers(page), from,
1550 to, &partial, write_end_fn);
1551 if (!partial)
1552 SetPageUptodate(page);
1553 new_i_size = pos + copied;
1554 if (new_i_size > inode->i_size)
1555 i_size_write(inode, pos+copied);
1556 EXT4_I(inode)->i_state |= EXT4_STATE_JDATA;
1557 if (new_i_size > EXT4_I(inode)->i_disksize) {
1558 ext4_update_i_disksize(inode, new_i_size);
1559 ret2 = ext4_mark_inode_dirty(handle, inode);
1560 if (!ret)
1561 ret = ret2;
1564 unlock_page(page);
1565 ret2 = ext4_journal_stop(handle);
1566 if (!ret)
1567 ret = ret2;
1568 page_cache_release(page);
1570 return ret ? ret : copied;
1573 static int ext4_da_reserve_space(struct inode *inode, int nrblocks)
1575 int retries = 0;
1576 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1577 unsigned long md_needed, mdblocks, total = 0;
1580 * recalculate the amount of metadata blocks to reserve
1581 * in order to allocate nrblocks
1582 * worse case is one extent per block
1584 repeat:
1585 spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
1586 total = EXT4_I(inode)->i_reserved_data_blocks + nrblocks;
1587 mdblocks = ext4_calc_metadata_amount(inode, total);
1588 BUG_ON(mdblocks < EXT4_I(inode)->i_reserved_meta_blocks);
1590 md_needed = mdblocks - EXT4_I(inode)->i_reserved_meta_blocks;
1591 total = md_needed + nrblocks;
1593 if (ext4_claim_free_blocks(sbi, total)) {
1594 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
1595 if (ext4_should_retry_alloc(inode->i_sb, &retries)) {
1596 yield();
1597 goto repeat;
1599 return -ENOSPC;
1601 EXT4_I(inode)->i_reserved_data_blocks += nrblocks;
1602 EXT4_I(inode)->i_reserved_meta_blocks = mdblocks;
1604 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
1605 return 0; /* success */
1608 static void ext4_da_release_space(struct inode *inode, int to_free)
1610 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1611 int total, mdb, mdb_free, release;
1613 if (!to_free)
1614 return; /* Nothing to release, exit */
1616 spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
1618 if (!EXT4_I(inode)->i_reserved_data_blocks) {
1620 * if there is no reserved blocks, but we try to free some
1621 * then the counter is messed up somewhere.
1622 * but since this function is called from invalidate
1623 * page, it's harmless to return without any action
1625 printk(KERN_INFO "ext4 delalloc try to release %d reserved "
1626 "blocks for inode %lu, but there is no reserved "
1627 "data blocks\n", to_free, inode->i_ino);
1628 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
1629 return;
1632 /* recalculate the number of metablocks still need to be reserved */
1633 total = EXT4_I(inode)->i_reserved_data_blocks - to_free;
1634 mdb = ext4_calc_metadata_amount(inode, total);
1636 /* figure out how many metablocks to release */
1637 BUG_ON(mdb > EXT4_I(inode)->i_reserved_meta_blocks);
1638 mdb_free = EXT4_I(inode)->i_reserved_meta_blocks - mdb;
1640 release = to_free + mdb_free;
1642 /* update fs dirty blocks counter for truncate case */
1643 percpu_counter_sub(&sbi->s_dirtyblocks_counter, release);
1645 /* update per-inode reservations */
1646 BUG_ON(to_free > EXT4_I(inode)->i_reserved_data_blocks);
1647 EXT4_I(inode)->i_reserved_data_blocks -= to_free;
1649 BUG_ON(mdb > EXT4_I(inode)->i_reserved_meta_blocks);
1650 EXT4_I(inode)->i_reserved_meta_blocks = mdb;
1651 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
1654 static void ext4_da_page_release_reservation(struct page *page,
1655 unsigned long offset)
1657 int to_release = 0;
1658 struct buffer_head *head, *bh;
1659 unsigned int curr_off = 0;
1661 head = page_buffers(page);
1662 bh = head;
1663 do {
1664 unsigned int next_off = curr_off + bh->b_size;
1666 if ((offset <= curr_off) && (buffer_delay(bh))) {
1667 to_release++;
1668 clear_buffer_delay(bh);
1670 curr_off = next_off;
1671 } while ((bh = bh->b_this_page) != head);
1672 ext4_da_release_space(page->mapping->host, to_release);
1676 * Delayed allocation stuff
1679 struct mpage_da_data {
1680 struct inode *inode;
1681 struct buffer_head lbh; /* extent of blocks */
1682 unsigned long first_page, next_page; /* extent of pages */
1683 get_block_t *get_block;
1684 struct writeback_control *wbc;
1685 int io_done;
1686 int pages_written;
1687 int retval;
1691 * mpage_da_submit_io - walks through extent of pages and try to write
1692 * them with writepage() call back
1694 * @mpd->inode: inode
1695 * @mpd->first_page: first page of the extent
1696 * @mpd->next_page: page after the last page of the extent
1697 * @mpd->get_block: the filesystem's block mapper function
1699 * By the time mpage_da_submit_io() is called we expect all blocks
1700 * to be allocated. this may be wrong if allocation failed.
1702 * As pages are already locked by write_cache_pages(), we can't use it
1704 static int mpage_da_submit_io(struct mpage_da_data *mpd)
1706 long pages_skipped;
1707 struct pagevec pvec;
1708 unsigned long index, end;
1709 int ret = 0, err, nr_pages, i;
1710 struct inode *inode = mpd->inode;
1711 struct address_space *mapping = inode->i_mapping;
1713 BUG_ON(mpd->next_page <= mpd->first_page);
1715 * We need to start from the first_page to the next_page - 1
1716 * to make sure we also write the mapped dirty buffer_heads.
1717 * If we look at mpd->lbh.b_blocknr we would only be looking
1718 * at the currently mapped buffer_heads.
1720 index = mpd->first_page;
1721 end = mpd->next_page - 1;
1723 pagevec_init(&pvec, 0);
1724 while (index <= end) {
1725 nr_pages = pagevec_lookup(&pvec, mapping, index, PAGEVEC_SIZE);
1726 if (nr_pages == 0)
1727 break;
1728 for (i = 0; i < nr_pages; i++) {
1729 struct page *page = pvec.pages[i];
1731 index = page->index;
1732 if (index > end)
1733 break;
1734 index++;
1736 BUG_ON(!PageLocked(page));
1737 BUG_ON(PageWriteback(page));
1739 pages_skipped = mpd->wbc->pages_skipped;
1740 err = mapping->a_ops->writepage(page, mpd->wbc);
1741 if (!err && (pages_skipped == mpd->wbc->pages_skipped))
1743 * have successfully written the page
1744 * without skipping the same
1746 mpd->pages_written++;
1748 * In error case, we have to continue because
1749 * remaining pages are still locked
1750 * XXX: unlock and re-dirty them?
1752 if (ret == 0)
1753 ret = err;
1755 pagevec_release(&pvec);
1757 return ret;
1761 * mpage_put_bnr_to_bhs - walk blocks and assign them actual numbers
1763 * @mpd->inode - inode to walk through
1764 * @exbh->b_blocknr - first block on a disk
1765 * @exbh->b_size - amount of space in bytes
1766 * @logical - first logical block to start assignment with
1768 * the function goes through all passed space and put actual disk
1769 * block numbers into buffer heads, dropping BH_Delay
1771 static void mpage_put_bnr_to_bhs(struct mpage_da_data *mpd, sector_t logical,
1772 struct buffer_head *exbh)
1774 struct inode *inode = mpd->inode;
1775 struct address_space *mapping = inode->i_mapping;
1776 int blocks = exbh->b_size >> inode->i_blkbits;
1777 sector_t pblock = exbh->b_blocknr, cur_logical;
1778 struct buffer_head *head, *bh;
1779 pgoff_t index, end;
1780 struct pagevec pvec;
1781 int nr_pages, i;
1783 index = logical >> (PAGE_CACHE_SHIFT - inode->i_blkbits);
1784 end = (logical + blocks - 1) >> (PAGE_CACHE_SHIFT - inode->i_blkbits);
1785 cur_logical = index << (PAGE_CACHE_SHIFT - inode->i_blkbits);
1787 pagevec_init(&pvec, 0);
1789 while (index <= end) {
1790 /* XXX: optimize tail */
1791 nr_pages = pagevec_lookup(&pvec, mapping, index, PAGEVEC_SIZE);
1792 if (nr_pages == 0)
1793 break;
1794 for (i = 0; i < nr_pages; i++) {
1795 struct page *page = pvec.pages[i];
1797 index = page->index;
1798 if (index > end)
1799 break;
1800 index++;
1802 BUG_ON(!PageLocked(page));
1803 BUG_ON(PageWriteback(page));
1804 BUG_ON(!page_has_buffers(page));
1806 bh = page_buffers(page);
1807 head = bh;
1809 /* skip blocks out of the range */
1810 do {
1811 if (cur_logical >= logical)
1812 break;
1813 cur_logical++;
1814 } while ((bh = bh->b_this_page) != head);
1816 do {
1817 if (cur_logical >= logical + blocks)
1818 break;
1819 if (buffer_delay(bh)) {
1820 bh->b_blocknr = pblock;
1821 clear_buffer_delay(bh);
1822 bh->b_bdev = inode->i_sb->s_bdev;
1823 } else if (buffer_unwritten(bh)) {
1824 bh->b_blocknr = pblock;
1825 clear_buffer_unwritten(bh);
1826 set_buffer_mapped(bh);
1827 set_buffer_new(bh);
1828 bh->b_bdev = inode->i_sb->s_bdev;
1829 } else if (buffer_mapped(bh))
1830 BUG_ON(bh->b_blocknr != pblock);
1832 cur_logical++;
1833 pblock++;
1834 } while ((bh = bh->b_this_page) != head);
1836 pagevec_release(&pvec);
1842 * __unmap_underlying_blocks - just a helper function to unmap
1843 * set of blocks described by @bh
1845 static inline void __unmap_underlying_blocks(struct inode *inode,
1846 struct buffer_head *bh)
1848 struct block_device *bdev = inode->i_sb->s_bdev;
1849 int blocks, i;
1851 blocks = bh->b_size >> inode->i_blkbits;
1852 for (i = 0; i < blocks; i++)
1853 unmap_underlying_metadata(bdev, bh->b_blocknr + i);
1856 static void ext4_da_block_invalidatepages(struct mpage_da_data *mpd,
1857 sector_t logical, long blk_cnt)
1859 int nr_pages, i;
1860 pgoff_t index, end;
1861 struct pagevec pvec;
1862 struct inode *inode = mpd->inode;
1863 struct address_space *mapping = inode->i_mapping;
1865 index = logical >> (PAGE_CACHE_SHIFT - inode->i_blkbits);
1866 end = (logical + blk_cnt - 1) >>
1867 (PAGE_CACHE_SHIFT - inode->i_blkbits);
1868 while (index <= end) {
1869 nr_pages = pagevec_lookup(&pvec, mapping, index, PAGEVEC_SIZE);
1870 if (nr_pages == 0)
1871 break;
1872 for (i = 0; i < nr_pages; i++) {
1873 struct page *page = pvec.pages[i];
1874 index = page->index;
1875 if (index > end)
1876 break;
1877 index++;
1879 BUG_ON(!PageLocked(page));
1880 BUG_ON(PageWriteback(page));
1881 block_invalidatepage(page, 0);
1882 ClearPageUptodate(page);
1883 unlock_page(page);
1886 return;
1889 static void ext4_print_free_blocks(struct inode *inode)
1891 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1892 printk(KERN_EMERG "Total free blocks count %lld\n",
1893 ext4_count_free_blocks(inode->i_sb));
1894 printk(KERN_EMERG "Free/Dirty block details\n");
1895 printk(KERN_EMERG "free_blocks=%lld\n",
1896 (long long)percpu_counter_sum(&sbi->s_freeblocks_counter));
1897 printk(KERN_EMERG "dirty_blocks=%lld\n",
1898 (long long)percpu_counter_sum(&sbi->s_dirtyblocks_counter));
1899 printk(KERN_EMERG "Block reservation details\n");
1900 printk(KERN_EMERG "i_reserved_data_blocks=%u\n",
1901 EXT4_I(inode)->i_reserved_data_blocks);
1902 printk(KERN_EMERG "i_reserved_meta_blocks=%u\n",
1903 EXT4_I(inode)->i_reserved_meta_blocks);
1904 return;
1908 * mpage_da_map_blocks - go through given space
1910 * @mpd->lbh - bh describing space
1911 * @mpd->get_block - the filesystem's block mapper function
1913 * The function skips space we know is already mapped to disk blocks.
1916 static int mpage_da_map_blocks(struct mpage_da_data *mpd)
1918 int err = 0;
1919 struct buffer_head new;
1920 struct buffer_head *lbh = &mpd->lbh;
1921 sector_t next;
1924 * We consider only non-mapped and non-allocated blocks
1926 if (buffer_mapped(lbh) && !buffer_delay(lbh))
1927 return 0;
1928 new.b_state = lbh->b_state;
1929 new.b_blocknr = 0;
1930 new.b_size = lbh->b_size;
1931 next = lbh->b_blocknr;
1933 * If we didn't accumulate anything
1934 * to write simply return
1936 if (!new.b_size)
1937 return 0;
1938 err = mpd->get_block(mpd->inode, next, &new, 1);
1939 if (err) {
1941 /* If get block returns with error
1942 * we simply return. Later writepage
1943 * will redirty the page and writepages
1944 * will find the dirty page again
1946 if (err == -EAGAIN)
1947 return 0;
1949 if (err == -ENOSPC &&
1950 ext4_count_free_blocks(mpd->inode->i_sb)) {
1951 mpd->retval = err;
1952 return 0;
1956 * get block failure will cause us
1957 * to loop in writepages. Because
1958 * a_ops->writepage won't be able to
1959 * make progress. The page will be redirtied
1960 * by writepage and writepages will again
1961 * try to write the same.
1963 printk(KERN_EMERG "%s block allocation failed for inode %lu "
1964 "at logical offset %llu with max blocks "
1965 "%zd with error %d\n",
1966 __func__, mpd->inode->i_ino,
1967 (unsigned long long)next,
1968 lbh->b_size >> mpd->inode->i_blkbits, err);
1969 printk(KERN_EMERG "This should not happen.!! "
1970 "Data will be lost\n");
1971 if (err == -ENOSPC) {
1972 ext4_print_free_blocks(mpd->inode);
1974 /* invlaidate all the pages */
1975 ext4_da_block_invalidatepages(mpd, next,
1976 lbh->b_size >> mpd->inode->i_blkbits);
1977 return err;
1979 BUG_ON(new.b_size == 0);
1981 if (buffer_new(&new))
1982 __unmap_underlying_blocks(mpd->inode, &new);
1985 * If blocks are delayed marked, we need to
1986 * put actual blocknr and drop delayed bit
1988 if (buffer_delay(lbh) || buffer_unwritten(lbh))
1989 mpage_put_bnr_to_bhs(mpd, next, &new);
1991 return 0;
1994 #define BH_FLAGS ((1 << BH_Uptodate) | (1 << BH_Mapped) | \
1995 (1 << BH_Delay) | (1 << BH_Unwritten))
1998 * mpage_add_bh_to_extent - try to add one more block to extent of blocks
2000 * @mpd->lbh - extent of blocks
2001 * @logical - logical number of the block in the file
2002 * @bh - bh of the block (used to access block's state)
2004 * the function is used to collect contig. blocks in same state
2006 static void mpage_add_bh_to_extent(struct mpage_da_data *mpd,
2007 sector_t logical, struct buffer_head *bh)
2009 sector_t next;
2010 size_t b_size = bh->b_size;
2011 struct buffer_head *lbh = &mpd->lbh;
2012 int nrblocks = lbh->b_size >> mpd->inode->i_blkbits;
2014 /* check if thereserved journal credits might overflow */
2015 if (!(EXT4_I(mpd->inode)->i_flags & EXT4_EXTENTS_FL)) {
2016 if (nrblocks >= EXT4_MAX_TRANS_DATA) {
2018 * With non-extent format we are limited by the journal
2019 * credit available. Total credit needed to insert
2020 * nrblocks contiguous blocks is dependent on the
2021 * nrblocks. So limit nrblocks.
2023 goto flush_it;
2024 } else if ((nrblocks + (b_size >> mpd->inode->i_blkbits)) >
2025 EXT4_MAX_TRANS_DATA) {
2027 * Adding the new buffer_head would make it cross the
2028 * allowed limit for which we have journal credit
2029 * reserved. So limit the new bh->b_size
2031 b_size = (EXT4_MAX_TRANS_DATA - nrblocks) <<
2032 mpd->inode->i_blkbits;
2033 /* we will do mpage_da_submit_io in the next loop */
2037 * First block in the extent
2039 if (lbh->b_size == 0) {
2040 lbh->b_blocknr = logical;
2041 lbh->b_size = b_size;
2042 lbh->b_state = bh->b_state & BH_FLAGS;
2043 return;
2046 next = lbh->b_blocknr + nrblocks;
2048 * Can we merge the block to our big extent?
2050 if (logical == next && (bh->b_state & BH_FLAGS) == lbh->b_state) {
2051 lbh->b_size += b_size;
2052 return;
2055 flush_it:
2057 * We couldn't merge the block to our extent, so we
2058 * need to flush current extent and start new one
2060 if (mpage_da_map_blocks(mpd) == 0)
2061 mpage_da_submit_io(mpd);
2062 mpd->io_done = 1;
2063 return;
2067 * __mpage_da_writepage - finds extent of pages and blocks
2069 * @page: page to consider
2070 * @wbc: not used, we just follow rules
2071 * @data: context
2073 * The function finds extents of pages and scan them for all blocks.
2075 static int __mpage_da_writepage(struct page *page,
2076 struct writeback_control *wbc, void *data)
2078 struct mpage_da_data *mpd = data;
2079 struct inode *inode = mpd->inode;
2080 struct buffer_head *bh, *head, fake;
2081 sector_t logical;
2083 if (mpd->io_done) {
2085 * Rest of the page in the page_vec
2086 * redirty then and skip then. We will
2087 * try to to write them again after
2088 * starting a new transaction
2090 redirty_page_for_writepage(wbc, page);
2091 unlock_page(page);
2092 return MPAGE_DA_EXTENT_TAIL;
2095 * Can we merge this page to current extent?
2097 if (mpd->next_page != page->index) {
2099 * Nope, we can't. So, we map non-allocated blocks
2100 * and start IO on them using writepage()
2102 if (mpd->next_page != mpd->first_page) {
2103 if (mpage_da_map_blocks(mpd) == 0)
2104 mpage_da_submit_io(mpd);
2106 * skip rest of the page in the page_vec
2108 mpd->io_done = 1;
2109 redirty_page_for_writepage(wbc, page);
2110 unlock_page(page);
2111 return MPAGE_DA_EXTENT_TAIL;
2115 * Start next extent of pages ...
2117 mpd->first_page = page->index;
2120 * ... and blocks
2122 mpd->lbh.b_size = 0;
2123 mpd->lbh.b_state = 0;
2124 mpd->lbh.b_blocknr = 0;
2127 mpd->next_page = page->index + 1;
2128 logical = (sector_t) page->index <<
2129 (PAGE_CACHE_SHIFT - inode->i_blkbits);
2131 if (!page_has_buffers(page)) {
2133 * There is no attached buffer heads yet (mmap?)
2134 * we treat the page asfull of dirty blocks
2136 bh = &fake;
2137 bh->b_size = PAGE_CACHE_SIZE;
2138 bh->b_state = 0;
2139 set_buffer_dirty(bh);
2140 set_buffer_uptodate(bh);
2141 mpage_add_bh_to_extent(mpd, logical, bh);
2142 if (mpd->io_done)
2143 return MPAGE_DA_EXTENT_TAIL;
2144 } else {
2146 * Page with regular buffer heads, just add all dirty ones
2148 head = page_buffers(page);
2149 bh = head;
2150 do {
2151 BUG_ON(buffer_locked(bh));
2153 * We need to try to allocate
2154 * unmapped blocks in the same page.
2155 * Otherwise we won't make progress
2156 * with the page in ext4_da_writepage
2158 if (buffer_dirty(bh) &&
2159 (!buffer_mapped(bh) || buffer_delay(bh))) {
2160 mpage_add_bh_to_extent(mpd, logical, bh);
2161 if (mpd->io_done)
2162 return MPAGE_DA_EXTENT_TAIL;
2163 } else if (buffer_dirty(bh) && (buffer_mapped(bh))) {
2165 * mapped dirty buffer. We need to update
2166 * the b_state because we look at
2167 * b_state in mpage_da_map_blocks. We don't
2168 * update b_size because if we find an
2169 * unmapped buffer_head later we need to
2170 * use the b_state flag of that buffer_head.
2172 if (mpd->lbh.b_size == 0)
2173 mpd->lbh.b_state =
2174 bh->b_state & BH_FLAGS;
2176 logical++;
2177 } while ((bh = bh->b_this_page) != head);
2180 return 0;
2184 * mpage_da_writepages - walk the list of dirty pages of the given
2185 * address space, allocates non-allocated blocks, maps newly-allocated
2186 * blocks to existing bhs and issue IO them
2188 * @mapping: address space structure to write
2189 * @wbc: subtract the number of written pages from *@wbc->nr_to_write
2190 * @get_block: the filesystem's block mapper function.
2192 * This is a library function, which implements the writepages()
2193 * address_space_operation.
2195 static int mpage_da_writepages(struct address_space *mapping,
2196 struct writeback_control *wbc,
2197 struct mpage_da_data *mpd)
2199 int ret;
2201 if (!mpd->get_block)
2202 return generic_writepages(mapping, wbc);
2204 mpd->lbh.b_size = 0;
2205 mpd->lbh.b_state = 0;
2206 mpd->lbh.b_blocknr = 0;
2207 mpd->first_page = 0;
2208 mpd->next_page = 0;
2209 mpd->io_done = 0;
2210 mpd->pages_written = 0;
2211 mpd->retval = 0;
2213 ret = write_cache_pages(mapping, wbc, __mpage_da_writepage, mpd);
2215 * Handle last extent of pages
2217 if (!mpd->io_done && mpd->next_page != mpd->first_page) {
2218 if (mpage_da_map_blocks(mpd) == 0)
2219 mpage_da_submit_io(mpd);
2221 mpd->io_done = 1;
2222 ret = MPAGE_DA_EXTENT_TAIL;
2224 wbc->nr_to_write -= mpd->pages_written;
2225 return ret;
2229 * this is a special callback for ->write_begin() only
2230 * it's intention is to return mapped block or reserve space
2232 static int ext4_da_get_block_prep(struct inode *inode, sector_t iblock,
2233 struct buffer_head *bh_result, int create)
2235 int ret = 0;
2236 sector_t invalid_block = ~((sector_t) 0xffff);
2238 if (invalid_block < ext4_blocks_count(EXT4_SB(inode->i_sb)->s_es))
2239 invalid_block = ~0;
2241 BUG_ON(create == 0);
2242 BUG_ON(bh_result->b_size != inode->i_sb->s_blocksize);
2245 * first, we need to know whether the block is allocated already
2246 * preallocated blocks are unmapped but should treated
2247 * the same as allocated blocks.
2249 ret = ext4_get_blocks_wrap(NULL, inode, iblock, 1, bh_result, 0, 0, 0);
2250 if ((ret == 0) && !buffer_delay(bh_result)) {
2251 /* the block isn't (pre)allocated yet, let's reserve space */
2253 * XXX: __block_prepare_write() unmaps passed block,
2254 * is it OK?
2256 ret = ext4_da_reserve_space(inode, 1);
2257 if (ret)
2258 /* not enough space to reserve */
2259 return ret;
2261 map_bh(bh_result, inode->i_sb, invalid_block);
2262 set_buffer_new(bh_result);
2263 set_buffer_delay(bh_result);
2264 } else if (ret > 0) {
2265 bh_result->b_size = (ret << inode->i_blkbits);
2267 * With sub-block writes into unwritten extents
2268 * we also need to mark the buffer as new so that
2269 * the unwritten parts of the buffer gets correctly zeroed.
2271 if (buffer_unwritten(bh_result))
2272 set_buffer_new(bh_result);
2273 ret = 0;
2276 return ret;
2278 #define EXT4_DELALLOC_RSVED 1
2279 static int ext4_da_get_block_write(struct inode *inode, sector_t iblock,
2280 struct buffer_head *bh_result, int create)
2282 int ret;
2283 unsigned max_blocks = bh_result->b_size >> inode->i_blkbits;
2284 loff_t disksize = EXT4_I(inode)->i_disksize;
2285 handle_t *handle = NULL;
2287 handle = ext4_journal_current_handle();
2288 BUG_ON(!handle);
2289 ret = ext4_get_blocks_wrap(handle, inode, iblock, max_blocks,
2290 bh_result, create, 0, EXT4_DELALLOC_RSVED);
2291 if (ret > 0) {
2293 bh_result->b_size = (ret << inode->i_blkbits);
2295 if (ext4_should_order_data(inode)) {
2296 int retval;
2297 retval = ext4_jbd2_file_inode(handle, inode);
2298 if (retval)
2300 * Failed to add inode for ordered
2301 * mode. Don't update file size
2303 return retval;
2307 * Update on-disk size along with block allocation
2308 * we don't use 'extend_disksize' as size may change
2309 * within already allocated block -bzzz
2311 disksize = ((loff_t) iblock + ret) << inode->i_blkbits;
2312 if (disksize > i_size_read(inode))
2313 disksize = i_size_read(inode);
2314 if (disksize > EXT4_I(inode)->i_disksize) {
2315 ext4_update_i_disksize(inode, disksize);
2316 ret = ext4_mark_inode_dirty(handle, inode);
2317 return ret;
2319 ret = 0;
2321 return ret;
2324 static int ext4_bh_unmapped_or_delay(handle_t *handle, struct buffer_head *bh)
2327 * unmapped buffer is possible for holes.
2328 * delay buffer is possible with delayed allocation
2330 return ((!buffer_mapped(bh) || buffer_delay(bh)) && buffer_dirty(bh));
2333 static int ext4_normal_get_block_write(struct inode *inode, sector_t iblock,
2334 struct buffer_head *bh_result, int create)
2336 int ret = 0;
2337 unsigned max_blocks = bh_result->b_size >> inode->i_blkbits;
2340 * we don't want to do block allocation in writepage
2341 * so call get_block_wrap with create = 0
2343 ret = ext4_get_blocks_wrap(NULL, inode, iblock, max_blocks,
2344 bh_result, 0, 0, 0);
2345 if (ret > 0) {
2346 bh_result->b_size = (ret << inode->i_blkbits);
2347 ret = 0;
2349 return ret;
2353 * get called vi ext4_da_writepages after taking page lock (have journal handle)
2354 * get called via journal_submit_inode_data_buffers (no journal handle)
2355 * get called via shrink_page_list via pdflush (no journal handle)
2356 * or grab_page_cache when doing write_begin (have journal handle)
2358 static int ext4_da_writepage(struct page *page,
2359 struct writeback_control *wbc)
2361 int ret = 0;
2362 loff_t size;
2363 unsigned int len;
2364 struct buffer_head *page_bufs;
2365 struct inode *inode = page->mapping->host;
2367 trace_mark(ext4_da_writepage,
2368 "dev %s ino %lu page_index %lu",
2369 inode->i_sb->s_id, inode->i_ino, page->index);
2370 size = i_size_read(inode);
2371 if (page->index == size >> PAGE_CACHE_SHIFT)
2372 len = size & ~PAGE_CACHE_MASK;
2373 else
2374 len = PAGE_CACHE_SIZE;
2376 if (page_has_buffers(page)) {
2377 page_bufs = page_buffers(page);
2378 if (walk_page_buffers(NULL, page_bufs, 0, len, NULL,
2379 ext4_bh_unmapped_or_delay)) {
2381 * We don't want to do block allocation
2382 * So redirty the page and return
2383 * We may reach here when we do a journal commit
2384 * via journal_submit_inode_data_buffers.
2385 * If we don't have mapping block we just ignore
2386 * them. We can also reach here via shrink_page_list
2388 redirty_page_for_writepage(wbc, page);
2389 unlock_page(page);
2390 return 0;
2392 } else {
2394 * The test for page_has_buffers() is subtle:
2395 * We know the page is dirty but it lost buffers. That means
2396 * that at some moment in time after write_begin()/write_end()
2397 * has been called all buffers have been clean and thus they
2398 * must have been written at least once. So they are all
2399 * mapped and we can happily proceed with mapping them
2400 * and writing the page.
2402 * Try to initialize the buffer_heads and check whether
2403 * all are mapped and non delay. We don't want to
2404 * do block allocation here.
2406 ret = block_prepare_write(page, 0, PAGE_CACHE_SIZE,
2407 ext4_normal_get_block_write);
2408 if (!ret) {
2409 page_bufs = page_buffers(page);
2410 /* check whether all are mapped and non delay */
2411 if (walk_page_buffers(NULL, page_bufs, 0, len, NULL,
2412 ext4_bh_unmapped_or_delay)) {
2413 redirty_page_for_writepage(wbc, page);
2414 unlock_page(page);
2415 return 0;
2417 } else {
2419 * We can't do block allocation here
2420 * so just redity the page and unlock
2421 * and return
2423 redirty_page_for_writepage(wbc, page);
2424 unlock_page(page);
2425 return 0;
2427 /* now mark the buffer_heads as dirty and uptodate */
2428 block_commit_write(page, 0, PAGE_CACHE_SIZE);
2431 if (test_opt(inode->i_sb, NOBH) && ext4_should_writeback_data(inode))
2432 ret = nobh_writepage(page, ext4_normal_get_block_write, wbc);
2433 else
2434 ret = block_write_full_page(page,
2435 ext4_normal_get_block_write,
2436 wbc);
2438 return ret;
2442 * This is called via ext4_da_writepages() to
2443 * calulate the total number of credits to reserve to fit
2444 * a single extent allocation into a single transaction,
2445 * ext4_da_writpeages() will loop calling this before
2446 * the block allocation.
2449 static int ext4_da_writepages_trans_blocks(struct inode *inode)
2451 int max_blocks = EXT4_I(inode)->i_reserved_data_blocks;
2454 * With non-extent format the journal credit needed to
2455 * insert nrblocks contiguous block is dependent on
2456 * number of contiguous block. So we will limit
2457 * number of contiguous block to a sane value
2459 if (!(inode->i_flags & EXT4_EXTENTS_FL) &&
2460 (max_blocks > EXT4_MAX_TRANS_DATA))
2461 max_blocks = EXT4_MAX_TRANS_DATA;
2463 return ext4_chunk_trans_blocks(inode, max_blocks);
2466 static int ext4_da_writepages(struct address_space *mapping,
2467 struct writeback_control *wbc)
2469 pgoff_t index;
2470 int range_whole = 0;
2471 handle_t *handle = NULL;
2472 struct mpage_da_data mpd;
2473 struct inode *inode = mapping->host;
2474 int no_nrwrite_index_update;
2475 int pages_written = 0;
2476 long pages_skipped;
2477 int range_cyclic, cycled = 1, io_done = 0;
2478 int needed_blocks, ret = 0, nr_to_writebump = 0;
2479 struct ext4_sb_info *sbi = EXT4_SB(mapping->host->i_sb);
2481 trace_mark(ext4_da_writepages,
2482 "dev %s ino %lu nr_t_write %ld "
2483 "pages_skipped %ld range_start %llu "
2484 "range_end %llu nonblocking %d "
2485 "for_kupdate %d for_reclaim %d "
2486 "for_writepages %d range_cyclic %d",
2487 inode->i_sb->s_id, inode->i_ino,
2488 wbc->nr_to_write, wbc->pages_skipped,
2489 (unsigned long long) wbc->range_start,
2490 (unsigned long long) wbc->range_end,
2491 wbc->nonblocking, wbc->for_kupdate,
2492 wbc->for_reclaim, wbc->for_writepages,
2493 wbc->range_cyclic);
2496 * No pages to write? This is mainly a kludge to avoid starting
2497 * a transaction for special inodes like journal inode on last iput()
2498 * because that could violate lock ordering on umount
2500 if (!mapping->nrpages || !mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
2501 return 0;
2504 * If the filesystem has aborted, it is read-only, so return
2505 * right away instead of dumping stack traces later on that
2506 * will obscure the real source of the problem. We test
2507 * EXT4_MOUNT_ABORT instead of sb->s_flag's MS_RDONLY because
2508 * the latter could be true if the filesystem is mounted
2509 * read-only, and in that case, ext4_da_writepages should
2510 * *never* be called, so if that ever happens, we would want
2511 * the stack trace.
2513 if (unlikely(sbi->s_mount_opt & EXT4_MOUNT_ABORT))
2514 return -EROFS;
2517 * Make sure nr_to_write is >= sbi->s_mb_stream_request
2518 * This make sure small files blocks are allocated in
2519 * single attempt. This ensure that small files
2520 * get less fragmented.
2522 if (wbc->nr_to_write < sbi->s_mb_stream_request) {
2523 nr_to_writebump = sbi->s_mb_stream_request - wbc->nr_to_write;
2524 wbc->nr_to_write = sbi->s_mb_stream_request;
2526 if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
2527 range_whole = 1;
2529 range_cyclic = wbc->range_cyclic;
2530 if (wbc->range_cyclic) {
2531 index = mapping->writeback_index;
2532 if (index)
2533 cycled = 0;
2534 wbc->range_start = index << PAGE_CACHE_SHIFT;
2535 wbc->range_end = LLONG_MAX;
2536 wbc->range_cyclic = 0;
2537 } else
2538 index = wbc->range_start >> PAGE_CACHE_SHIFT;
2540 mpd.wbc = wbc;
2541 mpd.inode = mapping->host;
2544 * we don't want write_cache_pages to update
2545 * nr_to_write and writeback_index
2547 no_nrwrite_index_update = wbc->no_nrwrite_index_update;
2548 wbc->no_nrwrite_index_update = 1;
2549 pages_skipped = wbc->pages_skipped;
2551 retry:
2552 while (!ret && wbc->nr_to_write > 0) {
2555 * we insert one extent at a time. So we need
2556 * credit needed for single extent allocation.
2557 * journalled mode is currently not supported
2558 * by delalloc
2560 BUG_ON(ext4_should_journal_data(inode));
2561 needed_blocks = ext4_da_writepages_trans_blocks(inode);
2563 /* start a new transaction*/
2564 handle = ext4_journal_start(inode, needed_blocks);
2565 if (IS_ERR(handle)) {
2566 ret = PTR_ERR(handle);
2567 printk(KERN_CRIT "%s: jbd2_start: "
2568 "%ld pages, ino %lu; err %d\n", __func__,
2569 wbc->nr_to_write, inode->i_ino, ret);
2570 dump_stack();
2571 goto out_writepages;
2573 mpd.get_block = ext4_da_get_block_write;
2574 ret = mpage_da_writepages(mapping, wbc, &mpd);
2576 ext4_journal_stop(handle);
2578 if ((mpd.retval == -ENOSPC) && sbi->s_journal) {
2579 /* commit the transaction which would
2580 * free blocks released in the transaction
2581 * and try again
2583 jbd2_journal_force_commit_nested(sbi->s_journal);
2584 wbc->pages_skipped = pages_skipped;
2585 ret = 0;
2586 } else if (ret == MPAGE_DA_EXTENT_TAIL) {
2588 * got one extent now try with
2589 * rest of the pages
2591 pages_written += mpd.pages_written;
2592 wbc->pages_skipped = pages_skipped;
2593 ret = 0;
2594 io_done = 1;
2595 } else if (wbc->nr_to_write)
2597 * There is no more writeout needed
2598 * or we requested for a noblocking writeout
2599 * and we found the device congested
2601 break;
2603 if (!io_done && !cycled) {
2604 cycled = 1;
2605 index = 0;
2606 wbc->range_start = index << PAGE_CACHE_SHIFT;
2607 wbc->range_end = mapping->writeback_index - 1;
2608 goto retry;
2610 if (pages_skipped != wbc->pages_skipped)
2611 printk(KERN_EMERG "This should not happen leaving %s "
2612 "with nr_to_write = %ld ret = %d\n",
2613 __func__, wbc->nr_to_write, ret);
2615 /* Update index */
2616 index += pages_written;
2617 wbc->range_cyclic = range_cyclic;
2618 if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
2620 * set the writeback_index so that range_cyclic
2621 * mode will write it back later
2623 mapping->writeback_index = index;
2625 out_writepages:
2626 if (!no_nrwrite_index_update)
2627 wbc->no_nrwrite_index_update = 0;
2628 wbc->nr_to_write -= nr_to_writebump;
2629 trace_mark(ext4_da_writepage_result,
2630 "dev %s ino %lu ret %d pages_written %d "
2631 "pages_skipped %ld congestion %d "
2632 "more_io %d no_nrwrite_index_update %d",
2633 inode->i_sb->s_id, inode->i_ino, ret,
2634 pages_written, wbc->pages_skipped,
2635 wbc->encountered_congestion, wbc->more_io,
2636 wbc->no_nrwrite_index_update);
2637 return ret;
2640 #define FALL_BACK_TO_NONDELALLOC 1
2641 static int ext4_nonda_switch(struct super_block *sb)
2643 s64 free_blocks, dirty_blocks;
2644 struct ext4_sb_info *sbi = EXT4_SB(sb);
2647 * switch to non delalloc mode if we are running low
2648 * on free block. The free block accounting via percpu
2649 * counters can get slightly wrong with percpu_counter_batch getting
2650 * accumulated on each CPU without updating global counters
2651 * Delalloc need an accurate free block accounting. So switch
2652 * to non delalloc when we are near to error range.
2654 free_blocks = percpu_counter_read_positive(&sbi->s_freeblocks_counter);
2655 dirty_blocks = percpu_counter_read_positive(&sbi->s_dirtyblocks_counter);
2656 if (2 * free_blocks < 3 * dirty_blocks ||
2657 free_blocks < (dirty_blocks + EXT4_FREEBLOCKS_WATERMARK)) {
2659 * free block count is less that 150% of dirty blocks
2660 * or free blocks is less that watermark
2662 return 1;
2664 return 0;
2667 static int ext4_da_write_begin(struct file *file, struct address_space *mapping,
2668 loff_t pos, unsigned len, unsigned flags,
2669 struct page **pagep, void **fsdata)
2671 int ret, retries = 0;
2672 struct page *page;
2673 pgoff_t index;
2674 unsigned from, to;
2675 struct inode *inode = mapping->host;
2676 handle_t *handle;
2678 index = pos >> PAGE_CACHE_SHIFT;
2679 from = pos & (PAGE_CACHE_SIZE - 1);
2680 to = from + len;
2682 if (ext4_nonda_switch(inode->i_sb)) {
2683 *fsdata = (void *)FALL_BACK_TO_NONDELALLOC;
2684 return ext4_write_begin(file, mapping, pos,
2685 len, flags, pagep, fsdata);
2687 *fsdata = (void *)0;
2689 trace_mark(ext4_da_write_begin,
2690 "dev %s ino %lu pos %llu len %u flags %u",
2691 inode->i_sb->s_id, inode->i_ino,
2692 (unsigned long long) pos, len, flags);
2693 retry:
2695 * With delayed allocation, we don't log the i_disksize update
2696 * if there is delayed block allocation. But we still need
2697 * to journalling the i_disksize update if writes to the end
2698 * of file which has an already mapped buffer.
2700 handle = ext4_journal_start(inode, 1);
2701 if (IS_ERR(handle)) {
2702 ret = PTR_ERR(handle);
2703 goto out;
2705 /* We cannot recurse into the filesystem as the transaction is already
2706 * started */
2707 flags |= AOP_FLAG_NOFS;
2709 page = grab_cache_page_write_begin(mapping, index, flags);
2710 if (!page) {
2711 ext4_journal_stop(handle);
2712 ret = -ENOMEM;
2713 goto out;
2715 *pagep = page;
2717 ret = block_write_begin(file, mapping, pos, len, flags, pagep, fsdata,
2718 ext4_da_get_block_prep);
2719 if (ret < 0) {
2720 unlock_page(page);
2721 ext4_journal_stop(handle);
2722 page_cache_release(page);
2724 * block_write_begin may have instantiated a few blocks
2725 * outside i_size. Trim these off again. Don't need
2726 * i_size_read because we hold i_mutex.
2728 if (pos + len > inode->i_size)
2729 vmtruncate(inode, inode->i_size);
2732 if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
2733 goto retry;
2734 out:
2735 return ret;
2739 * Check if we should update i_disksize
2740 * when write to the end of file but not require block allocation
2742 static int ext4_da_should_update_i_disksize(struct page *page,
2743 unsigned long offset)
2745 struct buffer_head *bh;
2746 struct inode *inode = page->mapping->host;
2747 unsigned int idx;
2748 int i;
2750 bh = page_buffers(page);
2751 idx = offset >> inode->i_blkbits;
2753 for (i = 0; i < idx; i++)
2754 bh = bh->b_this_page;
2756 if (!buffer_mapped(bh) || (buffer_delay(bh)))
2757 return 0;
2758 return 1;
2761 static int ext4_da_write_end(struct file *file,
2762 struct address_space *mapping,
2763 loff_t pos, unsigned len, unsigned copied,
2764 struct page *page, void *fsdata)
2766 struct inode *inode = mapping->host;
2767 int ret = 0, ret2;
2768 handle_t *handle = ext4_journal_current_handle();
2769 loff_t new_i_size;
2770 unsigned long start, end;
2771 int write_mode = (int)(unsigned long)fsdata;
2773 if (write_mode == FALL_BACK_TO_NONDELALLOC) {
2774 if (ext4_should_order_data(inode)) {
2775 return ext4_ordered_write_end(file, mapping, pos,
2776 len, copied, page, fsdata);
2777 } else if (ext4_should_writeback_data(inode)) {
2778 return ext4_writeback_write_end(file, mapping, pos,
2779 len, copied, page, fsdata);
2780 } else {
2781 BUG();
2785 trace_mark(ext4_da_write_end,
2786 "dev %s ino %lu pos %llu len %u copied %u",
2787 inode->i_sb->s_id, inode->i_ino,
2788 (unsigned long long) pos, len, copied);
2789 start = pos & (PAGE_CACHE_SIZE - 1);
2790 end = start + copied - 1;
2793 * generic_write_end() will run mark_inode_dirty() if i_size
2794 * changes. So let's piggyback the i_disksize mark_inode_dirty
2795 * into that.
2798 new_i_size = pos + copied;
2799 if (new_i_size > EXT4_I(inode)->i_disksize) {
2800 if (ext4_da_should_update_i_disksize(page, end)) {
2801 down_write(&EXT4_I(inode)->i_data_sem);
2802 if (new_i_size > EXT4_I(inode)->i_disksize) {
2804 * Updating i_disksize when extending file
2805 * without needing block allocation
2807 if (ext4_should_order_data(inode))
2808 ret = ext4_jbd2_file_inode(handle,
2809 inode);
2811 EXT4_I(inode)->i_disksize = new_i_size;
2813 up_write(&EXT4_I(inode)->i_data_sem);
2814 /* We need to mark inode dirty even if
2815 * new_i_size is less that inode->i_size
2816 * bu greater than i_disksize.(hint delalloc)
2818 ext4_mark_inode_dirty(handle, inode);
2821 ret2 = generic_write_end(file, mapping, pos, len, copied,
2822 page, fsdata);
2823 copied = ret2;
2824 if (ret2 < 0)
2825 ret = ret2;
2826 ret2 = ext4_journal_stop(handle);
2827 if (!ret)
2828 ret = ret2;
2830 return ret ? ret : copied;
2833 static void ext4_da_invalidatepage(struct page *page, unsigned long offset)
2836 * Drop reserved blocks
2838 BUG_ON(!PageLocked(page));
2839 if (!page_has_buffers(page))
2840 goto out;
2842 ext4_da_page_release_reservation(page, offset);
2844 out:
2845 ext4_invalidatepage(page, offset);
2847 return;
2851 * Force all delayed allocation blocks to be allocated for a given inode.
2853 int ext4_alloc_da_blocks(struct inode *inode)
2855 if (!EXT4_I(inode)->i_reserved_data_blocks &&
2856 !EXT4_I(inode)->i_reserved_meta_blocks)
2857 return 0;
2860 * We do something simple for now. The filemap_flush() will
2861 * also start triggering a write of the data blocks, which is
2862 * not strictly speaking necessary (and for users of
2863 * laptop_mode, not even desirable). However, to do otherwise
2864 * would require replicating code paths in:
2866 * ext4_da_writepages() ->
2867 * write_cache_pages() ---> (via passed in callback function)
2868 * __mpage_da_writepage() -->
2869 * mpage_add_bh_to_extent()
2870 * mpage_da_map_blocks()
2872 * The problem is that write_cache_pages(), located in
2873 * mm/page-writeback.c, marks pages clean in preparation for
2874 * doing I/O, which is not desirable if we're not planning on
2875 * doing I/O at all.
2877 * We could call write_cache_pages(), and then redirty all of
2878 * the pages by calling redirty_page_for_writeback() but that
2879 * would be ugly in the extreme. So instead we would need to
2880 * replicate parts of the code in the above functions,
2881 * simplifying them becuase we wouldn't actually intend to
2882 * write out the pages, but rather only collect contiguous
2883 * logical block extents, call the multi-block allocator, and
2884 * then update the buffer heads with the block allocations.
2886 * For now, though, we'll cheat by calling filemap_flush(),
2887 * which will map the blocks, and start the I/O, but not
2888 * actually wait for the I/O to complete.
2890 return filemap_flush(inode->i_mapping);
2894 * bmap() is special. It gets used by applications such as lilo and by
2895 * the swapper to find the on-disk block of a specific piece of data.
2897 * Naturally, this is dangerous if the block concerned is still in the
2898 * journal. If somebody makes a swapfile on an ext4 data-journaling
2899 * filesystem and enables swap, then they may get a nasty shock when the
2900 * data getting swapped to that swapfile suddenly gets overwritten by
2901 * the original zero's written out previously to the journal and
2902 * awaiting writeback in the kernel's buffer cache.
2904 * So, if we see any bmap calls here on a modified, data-journaled file,
2905 * take extra steps to flush any blocks which might be in the cache.
2907 static sector_t ext4_bmap(struct address_space *mapping, sector_t block)
2909 struct inode *inode = mapping->host;
2910 journal_t *journal;
2911 int err;
2913 if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY) &&
2914 test_opt(inode->i_sb, DELALLOC)) {
2916 * With delalloc we want to sync the file
2917 * so that we can make sure we allocate
2918 * blocks for file
2920 filemap_write_and_wait(mapping);
2923 if (EXT4_JOURNAL(inode) && EXT4_I(inode)->i_state & EXT4_STATE_JDATA) {
2925 * This is a REALLY heavyweight approach, but the use of
2926 * bmap on dirty files is expected to be extremely rare:
2927 * only if we run lilo or swapon on a freshly made file
2928 * do we expect this to happen.
2930 * (bmap requires CAP_SYS_RAWIO so this does not
2931 * represent an unprivileged user DOS attack --- we'd be
2932 * in trouble if mortal users could trigger this path at
2933 * will.)
2935 * NB. EXT4_STATE_JDATA is not set on files other than
2936 * regular files. If somebody wants to bmap a directory
2937 * or symlink and gets confused because the buffer
2938 * hasn't yet been flushed to disk, they deserve
2939 * everything they get.
2942 EXT4_I(inode)->i_state &= ~EXT4_STATE_JDATA;
2943 journal = EXT4_JOURNAL(inode);
2944 jbd2_journal_lock_updates(journal);
2945 err = jbd2_journal_flush(journal);
2946 jbd2_journal_unlock_updates(journal);
2948 if (err)
2949 return 0;
2952 return generic_block_bmap(mapping, block, ext4_get_block);
2955 static int bget_one(handle_t *handle, struct buffer_head *bh)
2957 get_bh(bh);
2958 return 0;
2961 static int bput_one(handle_t *handle, struct buffer_head *bh)
2963 put_bh(bh);
2964 return 0;
2968 * Note that we don't need to start a transaction unless we're journaling data
2969 * because we should have holes filled from ext4_page_mkwrite(). We even don't
2970 * need to file the inode to the transaction's list in ordered mode because if
2971 * we are writing back data added by write(), the inode is already there and if
2972 * we are writing back data modified via mmap(), noone guarantees in which
2973 * transaction the data will hit the disk. In case we are journaling data, we
2974 * cannot start transaction directly because transaction start ranks above page
2975 * lock so we have to do some magic.
2977 * In all journaling modes block_write_full_page() will start the I/O.
2979 * Problem:
2981 * ext4_writepage() -> kmalloc() -> __alloc_pages() -> page_launder() ->
2982 * ext4_writepage()
2984 * Similar for:
2986 * ext4_file_write() -> generic_file_write() -> __alloc_pages() -> ...
2988 * Same applies to ext4_get_block(). We will deadlock on various things like
2989 * lock_journal and i_data_sem
2991 * Setting PF_MEMALLOC here doesn't work - too many internal memory
2992 * allocations fail.
2994 * 16May01: If we're reentered then journal_current_handle() will be
2995 * non-zero. We simply *return*.
2997 * 1 July 2001: @@@ FIXME:
2998 * In journalled data mode, a data buffer may be metadata against the
2999 * current transaction. But the same file is part of a shared mapping
3000 * and someone does a writepage() on it.
3002 * We will move the buffer onto the async_data list, but *after* it has
3003 * been dirtied. So there's a small window where we have dirty data on
3004 * BJ_Metadata.
3006 * Note that this only applies to the last partial page in the file. The
3007 * bit which block_write_full_page() uses prepare/commit for. (That's
3008 * broken code anyway: it's wrong for msync()).
3010 * It's a rare case: affects the final partial page, for journalled data
3011 * where the file is subject to bith write() and writepage() in the same
3012 * transction. To fix it we'll need a custom block_write_full_page().
3013 * We'll probably need that anyway for journalling writepage() output.
3015 * We don't honour synchronous mounts for writepage(). That would be
3016 * disastrous. Any write() or metadata operation will sync the fs for
3017 * us.
3020 static int __ext4_normal_writepage(struct page *page,
3021 struct writeback_control *wbc)
3023 struct inode *inode = page->mapping->host;
3025 if (test_opt(inode->i_sb, NOBH))
3026 return nobh_writepage(page,
3027 ext4_normal_get_block_write, wbc);
3028 else
3029 return block_write_full_page(page,
3030 ext4_normal_get_block_write,
3031 wbc);
3034 static int ext4_normal_writepage(struct page *page,
3035 struct writeback_control *wbc)
3037 struct inode *inode = page->mapping->host;
3038 loff_t size = i_size_read(inode);
3039 loff_t len;
3041 trace_mark(ext4_normal_writepage,
3042 "dev %s ino %lu page_index %lu",
3043 inode->i_sb->s_id, inode->i_ino, page->index);
3044 J_ASSERT(PageLocked(page));
3045 if (page->index == size >> PAGE_CACHE_SHIFT)
3046 len = size & ~PAGE_CACHE_MASK;
3047 else
3048 len = PAGE_CACHE_SIZE;
3050 if (page_has_buffers(page)) {
3051 /* if page has buffers it should all be mapped
3052 * and allocated. If there are not buffers attached
3053 * to the page we know the page is dirty but it lost
3054 * buffers. That means that at some moment in time
3055 * after write_begin() / write_end() has been called
3056 * all buffers have been clean and thus they must have been
3057 * written at least once. So they are all mapped and we can
3058 * happily proceed with mapping them and writing the page.
3060 BUG_ON(walk_page_buffers(NULL, page_buffers(page), 0, len, NULL,
3061 ext4_bh_unmapped_or_delay));
3064 if (!ext4_journal_current_handle())
3065 return __ext4_normal_writepage(page, wbc);
3067 redirty_page_for_writepage(wbc, page);
3068 unlock_page(page);
3069 return 0;
3072 static int __ext4_journalled_writepage(struct page *page,
3073 struct writeback_control *wbc)
3075 struct address_space *mapping = page->mapping;
3076 struct inode *inode = mapping->host;
3077 struct buffer_head *page_bufs;
3078 handle_t *handle = NULL;
3079 int ret = 0;
3080 int err;
3082 ret = block_prepare_write(page, 0, PAGE_CACHE_SIZE,
3083 ext4_normal_get_block_write);
3084 if (ret != 0)
3085 goto out_unlock;
3087 page_bufs = page_buffers(page);
3088 walk_page_buffers(handle, page_bufs, 0, PAGE_CACHE_SIZE, NULL,
3089 bget_one);
3090 /* As soon as we unlock the page, it can go away, but we have
3091 * references to buffers so we are safe */
3092 unlock_page(page);
3094 handle = ext4_journal_start(inode, ext4_writepage_trans_blocks(inode));
3095 if (IS_ERR(handle)) {
3096 ret = PTR_ERR(handle);
3097 goto out;
3100 ret = walk_page_buffers(handle, page_bufs, 0,
3101 PAGE_CACHE_SIZE, NULL, do_journal_get_write_access);
3103 err = walk_page_buffers(handle, page_bufs, 0,
3104 PAGE_CACHE_SIZE, NULL, write_end_fn);
3105 if (ret == 0)
3106 ret = err;
3107 err = ext4_journal_stop(handle);
3108 if (!ret)
3109 ret = err;
3111 walk_page_buffers(handle, page_bufs, 0,
3112 PAGE_CACHE_SIZE, NULL, bput_one);
3113 EXT4_I(inode)->i_state |= EXT4_STATE_JDATA;
3114 goto out;
3116 out_unlock:
3117 unlock_page(page);
3118 out:
3119 return ret;
3122 static int ext4_journalled_writepage(struct page *page,
3123 struct writeback_control *wbc)
3125 struct inode *inode = page->mapping->host;
3126 loff_t size = i_size_read(inode);
3127 loff_t len;
3129 trace_mark(ext4_journalled_writepage,
3130 "dev %s ino %lu page_index %lu",
3131 inode->i_sb->s_id, inode->i_ino, page->index);
3132 J_ASSERT(PageLocked(page));
3133 if (page->index == size >> PAGE_CACHE_SHIFT)
3134 len = size & ~PAGE_CACHE_MASK;
3135 else
3136 len = PAGE_CACHE_SIZE;
3138 if (page_has_buffers(page)) {
3139 /* if page has buffers it should all be mapped
3140 * and allocated. If there are not buffers attached
3141 * to the page we know the page is dirty but it lost
3142 * buffers. That means that at some moment in time
3143 * after write_begin() / write_end() has been called
3144 * all buffers have been clean and thus they must have been
3145 * written at least once. So they are all mapped and we can
3146 * happily proceed with mapping them and writing the page.
3148 BUG_ON(walk_page_buffers(NULL, page_buffers(page), 0, len, NULL,
3149 ext4_bh_unmapped_or_delay));
3152 if (ext4_journal_current_handle())
3153 goto no_write;
3155 if (PageChecked(page)) {
3157 * It's mmapped pagecache. Add buffers and journal it. There
3158 * doesn't seem much point in redirtying the page here.
3160 ClearPageChecked(page);
3161 return __ext4_journalled_writepage(page, wbc);
3162 } else {
3164 * It may be a page full of checkpoint-mode buffers. We don't
3165 * really know unless we go poke around in the buffer_heads.
3166 * But block_write_full_page will do the right thing.
3168 return block_write_full_page(page,
3169 ext4_normal_get_block_write,
3170 wbc);
3172 no_write:
3173 redirty_page_for_writepage(wbc, page);
3174 unlock_page(page);
3175 return 0;
3178 static int ext4_readpage(struct file *file, struct page *page)
3180 return mpage_readpage(page, ext4_get_block);
3183 static int
3184 ext4_readpages(struct file *file, struct address_space *mapping,
3185 struct list_head *pages, unsigned nr_pages)
3187 return mpage_readpages(mapping, pages, nr_pages, ext4_get_block);
3190 static void ext4_invalidatepage(struct page *page, unsigned long offset)
3192 journal_t *journal = EXT4_JOURNAL(page->mapping->host);
3195 * If it's a full truncate we just forget about the pending dirtying
3197 if (offset == 0)
3198 ClearPageChecked(page);
3200 if (journal)
3201 jbd2_journal_invalidatepage(journal, page, offset);
3202 else
3203 block_invalidatepage(page, offset);
3206 static int ext4_releasepage(struct page *page, gfp_t wait)
3208 journal_t *journal = EXT4_JOURNAL(page->mapping->host);
3210 WARN_ON(PageChecked(page));
3211 if (!page_has_buffers(page))
3212 return 0;
3213 if (journal)
3214 return jbd2_journal_try_to_free_buffers(journal, page, wait);
3215 else
3216 return try_to_free_buffers(page);
3220 * If the O_DIRECT write will extend the file then add this inode to the
3221 * orphan list. So recovery will truncate it back to the original size
3222 * if the machine crashes during the write.
3224 * If the O_DIRECT write is intantiating holes inside i_size and the machine
3225 * crashes then stale disk data _may_ be exposed inside the file. But current
3226 * VFS code falls back into buffered path in that case so we are safe.
3228 static ssize_t ext4_direct_IO(int rw, struct kiocb *iocb,
3229 const struct iovec *iov, loff_t offset,
3230 unsigned long nr_segs)
3232 struct file *file = iocb->ki_filp;
3233 struct inode *inode = file->f_mapping->host;
3234 struct ext4_inode_info *ei = EXT4_I(inode);
3235 handle_t *handle;
3236 ssize_t ret;
3237 int orphan = 0;
3238 size_t count = iov_length(iov, nr_segs);
3240 if (rw == WRITE) {
3241 loff_t final_size = offset + count;
3243 if (final_size > inode->i_size) {
3244 /* Credits for sb + inode write */
3245 handle = ext4_journal_start(inode, 2);
3246 if (IS_ERR(handle)) {
3247 ret = PTR_ERR(handle);
3248 goto out;
3250 ret = ext4_orphan_add(handle, inode);
3251 if (ret) {
3252 ext4_journal_stop(handle);
3253 goto out;
3255 orphan = 1;
3256 ei->i_disksize = inode->i_size;
3257 ext4_journal_stop(handle);
3261 ret = blockdev_direct_IO(rw, iocb, inode, inode->i_sb->s_bdev, iov,
3262 offset, nr_segs,
3263 ext4_get_block, NULL);
3265 if (orphan) {
3266 int err;
3268 /* Credits for sb + inode write */
3269 handle = ext4_journal_start(inode, 2);
3270 if (IS_ERR(handle)) {
3271 /* This is really bad luck. We've written the data
3272 * but cannot extend i_size. Bail out and pretend
3273 * the write failed... */
3274 ret = PTR_ERR(handle);
3275 goto out;
3277 if (inode->i_nlink)
3278 ext4_orphan_del(handle, inode);
3279 if (ret > 0) {
3280 loff_t end = offset + ret;
3281 if (end > inode->i_size) {
3282 ei->i_disksize = end;
3283 i_size_write(inode, end);
3285 * We're going to return a positive `ret'
3286 * here due to non-zero-length I/O, so there's
3287 * no way of reporting error returns from
3288 * ext4_mark_inode_dirty() to userspace. So
3289 * ignore it.
3291 ext4_mark_inode_dirty(handle, inode);
3294 err = ext4_journal_stop(handle);
3295 if (ret == 0)
3296 ret = err;
3298 out:
3299 return ret;
3303 * Pages can be marked dirty completely asynchronously from ext4's journalling
3304 * activity. By filemap_sync_pte(), try_to_unmap_one(), etc. We cannot do
3305 * much here because ->set_page_dirty is called under VFS locks. The page is
3306 * not necessarily locked.
3308 * We cannot just dirty the page and leave attached buffers clean, because the
3309 * buffers' dirty state is "definitive". We cannot just set the buffers dirty
3310 * or jbddirty because all the journalling code will explode.
3312 * So what we do is to mark the page "pending dirty" and next time writepage
3313 * is called, propagate that into the buffers appropriately.
3315 static int ext4_journalled_set_page_dirty(struct page *page)
3317 SetPageChecked(page);
3318 return __set_page_dirty_nobuffers(page);
3321 static const struct address_space_operations ext4_ordered_aops = {
3322 .readpage = ext4_readpage,
3323 .readpages = ext4_readpages,
3324 .writepage = ext4_normal_writepage,
3325 .sync_page = block_sync_page,
3326 .write_begin = ext4_write_begin,
3327 .write_end = ext4_ordered_write_end,
3328 .bmap = ext4_bmap,
3329 .invalidatepage = ext4_invalidatepage,
3330 .releasepage = ext4_releasepage,
3331 .direct_IO = ext4_direct_IO,
3332 .migratepage = buffer_migrate_page,
3333 .is_partially_uptodate = block_is_partially_uptodate,
3336 static const struct address_space_operations ext4_writeback_aops = {
3337 .readpage = ext4_readpage,
3338 .readpages = ext4_readpages,
3339 .writepage = ext4_normal_writepage,
3340 .sync_page = block_sync_page,
3341 .write_begin = ext4_write_begin,
3342 .write_end = ext4_writeback_write_end,
3343 .bmap = ext4_bmap,
3344 .invalidatepage = ext4_invalidatepage,
3345 .releasepage = ext4_releasepage,
3346 .direct_IO = ext4_direct_IO,
3347 .migratepage = buffer_migrate_page,
3348 .is_partially_uptodate = block_is_partially_uptodate,
3351 static const struct address_space_operations ext4_journalled_aops = {
3352 .readpage = ext4_readpage,
3353 .readpages = ext4_readpages,
3354 .writepage = ext4_journalled_writepage,
3355 .sync_page = block_sync_page,
3356 .write_begin = ext4_write_begin,
3357 .write_end = ext4_journalled_write_end,
3358 .set_page_dirty = ext4_journalled_set_page_dirty,
3359 .bmap = ext4_bmap,
3360 .invalidatepage = ext4_invalidatepage,
3361 .releasepage = ext4_releasepage,
3362 .is_partially_uptodate = block_is_partially_uptodate,
3365 static const struct address_space_operations ext4_da_aops = {
3366 .readpage = ext4_readpage,
3367 .readpages = ext4_readpages,
3368 .writepage = ext4_da_writepage,
3369 .writepages = ext4_da_writepages,
3370 .sync_page = block_sync_page,
3371 .write_begin = ext4_da_write_begin,
3372 .write_end = ext4_da_write_end,
3373 .bmap = ext4_bmap,
3374 .invalidatepage = ext4_da_invalidatepage,
3375 .releasepage = ext4_releasepage,
3376 .direct_IO = ext4_direct_IO,
3377 .migratepage = buffer_migrate_page,
3378 .is_partially_uptodate = block_is_partially_uptodate,
3381 void ext4_set_aops(struct inode *inode)
3383 if (ext4_should_order_data(inode) &&
3384 test_opt(inode->i_sb, DELALLOC))
3385 inode->i_mapping->a_ops = &ext4_da_aops;
3386 else if (ext4_should_order_data(inode))
3387 inode->i_mapping->a_ops = &ext4_ordered_aops;
3388 else if (ext4_should_writeback_data(inode) &&
3389 test_opt(inode->i_sb, DELALLOC))
3390 inode->i_mapping->a_ops = &ext4_da_aops;
3391 else if (ext4_should_writeback_data(inode))
3392 inode->i_mapping->a_ops = &ext4_writeback_aops;
3393 else
3394 inode->i_mapping->a_ops = &ext4_journalled_aops;
3398 * ext4_block_truncate_page() zeroes out a mapping from file offset `from'
3399 * up to the end of the block which corresponds to `from'.
3400 * This required during truncate. We need to physically zero the tail end
3401 * of that block so it doesn't yield old data if the file is later grown.
3403 int ext4_block_truncate_page(handle_t *handle,
3404 struct address_space *mapping, loff_t from)
3406 ext4_fsblk_t index = from >> PAGE_CACHE_SHIFT;
3407 unsigned offset = from & (PAGE_CACHE_SIZE-1);
3408 unsigned blocksize, length, pos;
3409 ext4_lblk_t iblock;
3410 struct inode *inode = mapping->host;
3411 struct buffer_head *bh;
3412 struct page *page;
3413 int err = 0;
3415 page = grab_cache_page(mapping, from >> PAGE_CACHE_SHIFT);
3416 if (!page)
3417 return -EINVAL;
3419 blocksize = inode->i_sb->s_blocksize;
3420 length = blocksize - (offset & (blocksize - 1));
3421 iblock = index << (PAGE_CACHE_SHIFT - inode->i_sb->s_blocksize_bits);
3424 * For "nobh" option, we can only work if we don't need to
3425 * read-in the page - otherwise we create buffers to do the IO.
3427 if (!page_has_buffers(page) && test_opt(inode->i_sb, NOBH) &&
3428 ext4_should_writeback_data(inode) && PageUptodate(page)) {
3429 zero_user(page, offset, length);
3430 set_page_dirty(page);
3431 goto unlock;
3434 if (!page_has_buffers(page))
3435 create_empty_buffers(page, blocksize, 0);
3437 /* Find the buffer that contains "offset" */
3438 bh = page_buffers(page);
3439 pos = blocksize;
3440 while (offset >= pos) {
3441 bh = bh->b_this_page;
3442 iblock++;
3443 pos += blocksize;
3446 err = 0;
3447 if (buffer_freed(bh)) {
3448 BUFFER_TRACE(bh, "freed: skip");
3449 goto unlock;
3452 if (!buffer_mapped(bh)) {
3453 BUFFER_TRACE(bh, "unmapped");
3454 ext4_get_block(inode, iblock, bh, 0);
3455 /* unmapped? It's a hole - nothing to do */
3456 if (!buffer_mapped(bh)) {
3457 BUFFER_TRACE(bh, "still unmapped");
3458 goto unlock;
3462 /* Ok, it's mapped. Make sure it's up-to-date */
3463 if (PageUptodate(page))
3464 set_buffer_uptodate(bh);
3466 if (!buffer_uptodate(bh)) {
3467 err = -EIO;
3468 ll_rw_block(READ, 1, &bh);
3469 wait_on_buffer(bh);
3470 /* Uhhuh. Read error. Complain and punt. */
3471 if (!buffer_uptodate(bh))
3472 goto unlock;
3475 if (ext4_should_journal_data(inode)) {
3476 BUFFER_TRACE(bh, "get write access");
3477 err = ext4_journal_get_write_access(handle, bh);
3478 if (err)
3479 goto unlock;
3482 zero_user(page, offset, length);
3484 BUFFER_TRACE(bh, "zeroed end of block");
3486 err = 0;
3487 if (ext4_should_journal_data(inode)) {
3488 err = ext4_handle_dirty_metadata(handle, inode, bh);
3489 } else {
3490 if (ext4_should_order_data(inode))
3491 err = ext4_jbd2_file_inode(handle, inode);
3492 mark_buffer_dirty(bh);
3495 unlock:
3496 unlock_page(page);
3497 page_cache_release(page);
3498 return err;
3502 * Probably it should be a library function... search for first non-zero word
3503 * or memcmp with zero_page, whatever is better for particular architecture.
3504 * Linus?
3506 static inline int all_zeroes(__le32 *p, __le32 *q)
3508 while (p < q)
3509 if (*p++)
3510 return 0;
3511 return 1;
3515 * ext4_find_shared - find the indirect blocks for partial truncation.
3516 * @inode: inode in question
3517 * @depth: depth of the affected branch
3518 * @offsets: offsets of pointers in that branch (see ext4_block_to_path)
3519 * @chain: place to store the pointers to partial indirect blocks
3520 * @top: place to the (detached) top of branch
3522 * This is a helper function used by ext4_truncate().
3524 * When we do truncate() we may have to clean the ends of several
3525 * indirect blocks but leave the blocks themselves alive. Block is
3526 * partially truncated if some data below the new i_size is refered
3527 * from it (and it is on the path to the first completely truncated
3528 * data block, indeed). We have to free the top of that path along
3529 * with everything to the right of the path. Since no allocation
3530 * past the truncation point is possible until ext4_truncate()
3531 * finishes, we may safely do the latter, but top of branch may
3532 * require special attention - pageout below the truncation point
3533 * might try to populate it.
3535 * We atomically detach the top of branch from the tree, store the
3536 * block number of its root in *@top, pointers to buffer_heads of
3537 * partially truncated blocks - in @chain[].bh and pointers to
3538 * their last elements that should not be removed - in
3539 * @chain[].p. Return value is the pointer to last filled element
3540 * of @chain.
3542 * The work left to caller to do the actual freeing of subtrees:
3543 * a) free the subtree starting from *@top
3544 * b) free the subtrees whose roots are stored in
3545 * (@chain[i].p+1 .. end of @chain[i].bh->b_data)
3546 * c) free the subtrees growing from the inode past the @chain[0].
3547 * (no partially truncated stuff there). */
3549 static Indirect *ext4_find_shared(struct inode *inode, int depth,
3550 ext4_lblk_t offsets[4], Indirect chain[4], __le32 *top)
3552 Indirect *partial, *p;
3553 int k, err;
3555 *top = 0;
3556 /* Make k index the deepest non-null offest + 1 */
3557 for (k = depth; k > 1 && !offsets[k-1]; k--)
3559 partial = ext4_get_branch(inode, k, offsets, chain, &err);
3560 /* Writer: pointers */
3561 if (!partial)
3562 partial = chain + k-1;
3564 * If the branch acquired continuation since we've looked at it -
3565 * fine, it should all survive and (new) top doesn't belong to us.
3567 if (!partial->key && *partial->p)
3568 /* Writer: end */
3569 goto no_top;
3570 for (p = partial; (p > chain) && all_zeroes((__le32 *) p->bh->b_data, p->p); p--)
3573 * OK, we've found the last block that must survive. The rest of our
3574 * branch should be detached before unlocking. However, if that rest
3575 * of branch is all ours and does not grow immediately from the inode
3576 * it's easier to cheat and just decrement partial->p.
3578 if (p == chain + k - 1 && p > chain) {
3579 p->p--;
3580 } else {
3581 *top = *p->p;
3582 /* Nope, don't do this in ext4. Must leave the tree intact */
3583 #if 0
3584 *p->p = 0;
3585 #endif
3587 /* Writer: end */
3589 while (partial > p) {
3590 brelse(partial->bh);
3591 partial--;
3593 no_top:
3594 return partial;
3598 * Zero a number of block pointers in either an inode or an indirect block.
3599 * If we restart the transaction we must again get write access to the
3600 * indirect block for further modification.
3602 * We release `count' blocks on disk, but (last - first) may be greater
3603 * than `count' because there can be holes in there.
3605 static void ext4_clear_blocks(handle_t *handle, struct inode *inode,
3606 struct buffer_head *bh, ext4_fsblk_t block_to_free,
3607 unsigned long count, __le32 *first, __le32 *last)
3609 __le32 *p;
3610 if (try_to_extend_transaction(handle, inode)) {
3611 if (bh) {
3612 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
3613 ext4_handle_dirty_metadata(handle, inode, bh);
3615 ext4_mark_inode_dirty(handle, inode);
3616 ext4_journal_test_restart(handle, inode);
3617 if (bh) {
3618 BUFFER_TRACE(bh, "retaking write access");
3619 ext4_journal_get_write_access(handle, bh);
3624 * Any buffers which are on the journal will be in memory. We find
3625 * them on the hash table so jbd2_journal_revoke() will run jbd2_journal_forget()
3626 * on them. We've already detached each block from the file, so
3627 * bforget() in jbd2_journal_forget() should be safe.
3629 * AKPM: turn on bforget in jbd2_journal_forget()!!!
3631 for (p = first; p < last; p++) {
3632 u32 nr = le32_to_cpu(*p);
3633 if (nr) {
3634 struct buffer_head *tbh;
3636 *p = 0;
3637 tbh = sb_find_get_block(inode->i_sb, nr);
3638 ext4_forget(handle, 0, inode, tbh, nr);
3642 ext4_free_blocks(handle, inode, block_to_free, count, 0);
3646 * ext4_free_data - free a list of data blocks
3647 * @handle: handle for this transaction
3648 * @inode: inode we are dealing with
3649 * @this_bh: indirect buffer_head which contains *@first and *@last
3650 * @first: array of block numbers
3651 * @last: points immediately past the end of array
3653 * We are freeing all blocks refered from that array (numbers are stored as
3654 * little-endian 32-bit) and updating @inode->i_blocks appropriately.
3656 * We accumulate contiguous runs of blocks to free. Conveniently, if these
3657 * blocks are contiguous then releasing them at one time will only affect one
3658 * or two bitmap blocks (+ group descriptor(s) and superblock) and we won't
3659 * actually use a lot of journal space.
3661 * @this_bh will be %NULL if @first and @last point into the inode's direct
3662 * block pointers.
3664 static void ext4_free_data(handle_t *handle, struct inode *inode,
3665 struct buffer_head *this_bh,
3666 __le32 *first, __le32 *last)
3668 ext4_fsblk_t block_to_free = 0; /* Starting block # of a run */
3669 unsigned long count = 0; /* Number of blocks in the run */
3670 __le32 *block_to_free_p = NULL; /* Pointer into inode/ind
3671 corresponding to
3672 block_to_free */
3673 ext4_fsblk_t nr; /* Current block # */
3674 __le32 *p; /* Pointer into inode/ind
3675 for current block */
3676 int err;
3678 if (this_bh) { /* For indirect block */
3679 BUFFER_TRACE(this_bh, "get_write_access");
3680 err = ext4_journal_get_write_access(handle, this_bh);
3681 /* Important: if we can't update the indirect pointers
3682 * to the blocks, we can't free them. */
3683 if (err)
3684 return;
3687 for (p = first; p < last; p++) {
3688 nr = le32_to_cpu(*p);
3689 if (nr) {
3690 /* accumulate blocks to free if they're contiguous */
3691 if (count == 0) {
3692 block_to_free = nr;
3693 block_to_free_p = p;
3694 count = 1;
3695 } else if (nr == block_to_free + count) {
3696 count++;
3697 } else {
3698 ext4_clear_blocks(handle, inode, this_bh,
3699 block_to_free,
3700 count, block_to_free_p, p);
3701 block_to_free = nr;
3702 block_to_free_p = p;
3703 count = 1;
3708 if (count > 0)
3709 ext4_clear_blocks(handle, inode, this_bh, block_to_free,
3710 count, block_to_free_p, p);
3712 if (this_bh) {
3713 BUFFER_TRACE(this_bh, "call ext4_handle_dirty_metadata");
3716 * The buffer head should have an attached journal head at this
3717 * point. However, if the data is corrupted and an indirect
3718 * block pointed to itself, it would have been detached when
3719 * the block was cleared. Check for this instead of OOPSing.
3721 if ((EXT4_JOURNAL(inode) == NULL) || bh2jh(this_bh))
3722 ext4_handle_dirty_metadata(handle, inode, this_bh);
3723 else
3724 ext4_error(inode->i_sb, __func__,
3725 "circular indirect block detected, "
3726 "inode=%lu, block=%llu",
3727 inode->i_ino,
3728 (unsigned long long) this_bh->b_blocknr);
3733 * ext4_free_branches - free an array of branches
3734 * @handle: JBD handle for this transaction
3735 * @inode: inode we are dealing with
3736 * @parent_bh: the buffer_head which contains *@first and *@last
3737 * @first: array of block numbers
3738 * @last: pointer immediately past the end of array
3739 * @depth: depth of the branches to free
3741 * We are freeing all blocks refered from these branches (numbers are
3742 * stored as little-endian 32-bit) and updating @inode->i_blocks
3743 * appropriately.
3745 static void ext4_free_branches(handle_t *handle, struct inode *inode,
3746 struct buffer_head *parent_bh,
3747 __le32 *first, __le32 *last, int depth)
3749 ext4_fsblk_t nr;
3750 __le32 *p;
3752 if (ext4_handle_is_aborted(handle))
3753 return;
3755 if (depth--) {
3756 struct buffer_head *bh;
3757 int addr_per_block = EXT4_ADDR_PER_BLOCK(inode->i_sb);
3758 p = last;
3759 while (--p >= first) {
3760 nr = le32_to_cpu(*p);
3761 if (!nr)
3762 continue; /* A hole */
3764 /* Go read the buffer for the next level down */
3765 bh = sb_bread(inode->i_sb, nr);
3768 * A read failure? Report error and clear slot
3769 * (should be rare).
3771 if (!bh) {
3772 ext4_error(inode->i_sb, "ext4_free_branches",
3773 "Read failure, inode=%lu, block=%llu",
3774 inode->i_ino, nr);
3775 continue;
3778 /* This zaps the entire block. Bottom up. */
3779 BUFFER_TRACE(bh, "free child branches");
3780 ext4_free_branches(handle, inode, bh,
3781 (__le32 *) bh->b_data,
3782 (__le32 *) bh->b_data + addr_per_block,
3783 depth);
3786 * We've probably journalled the indirect block several
3787 * times during the truncate. But it's no longer
3788 * needed and we now drop it from the transaction via
3789 * jbd2_journal_revoke().
3791 * That's easy if it's exclusively part of this
3792 * transaction. But if it's part of the committing
3793 * transaction then jbd2_journal_forget() will simply
3794 * brelse() it. That means that if the underlying
3795 * block is reallocated in ext4_get_block(),
3796 * unmap_underlying_metadata() will find this block
3797 * and will try to get rid of it. damn, damn.
3799 * If this block has already been committed to the
3800 * journal, a revoke record will be written. And
3801 * revoke records must be emitted *before* clearing
3802 * this block's bit in the bitmaps.
3804 ext4_forget(handle, 1, inode, bh, bh->b_blocknr);
3807 * Everything below this this pointer has been
3808 * released. Now let this top-of-subtree go.
3810 * We want the freeing of this indirect block to be
3811 * atomic in the journal with the updating of the
3812 * bitmap block which owns it. So make some room in
3813 * the journal.
3815 * We zero the parent pointer *after* freeing its
3816 * pointee in the bitmaps, so if extend_transaction()
3817 * for some reason fails to put the bitmap changes and
3818 * the release into the same transaction, recovery
3819 * will merely complain about releasing a free block,
3820 * rather than leaking blocks.
3822 if (ext4_handle_is_aborted(handle))
3823 return;
3824 if (try_to_extend_transaction(handle, inode)) {
3825 ext4_mark_inode_dirty(handle, inode);
3826 ext4_journal_test_restart(handle, inode);
3829 ext4_free_blocks(handle, inode, nr, 1, 1);
3831 if (parent_bh) {
3833 * The block which we have just freed is
3834 * pointed to by an indirect block: journal it
3836 BUFFER_TRACE(parent_bh, "get_write_access");
3837 if (!ext4_journal_get_write_access(handle,
3838 parent_bh)){
3839 *p = 0;
3840 BUFFER_TRACE(parent_bh,
3841 "call ext4_handle_dirty_metadata");
3842 ext4_handle_dirty_metadata(handle,
3843 inode,
3844 parent_bh);
3848 } else {
3849 /* We have reached the bottom of the tree. */
3850 BUFFER_TRACE(parent_bh, "free data blocks");
3851 ext4_free_data(handle, inode, parent_bh, first, last);
3855 int ext4_can_truncate(struct inode *inode)
3857 if (IS_APPEND(inode) || IS_IMMUTABLE(inode))
3858 return 0;
3859 if (S_ISREG(inode->i_mode))
3860 return 1;
3861 if (S_ISDIR(inode->i_mode))
3862 return 1;
3863 if (S_ISLNK(inode->i_mode))
3864 return !ext4_inode_is_fast_symlink(inode);
3865 return 0;
3869 * ext4_truncate()
3871 * We block out ext4_get_block() block instantiations across the entire
3872 * transaction, and VFS/VM ensures that ext4_truncate() cannot run
3873 * simultaneously on behalf of the same inode.
3875 * As we work through the truncate and commmit bits of it to the journal there
3876 * is one core, guiding principle: the file's tree must always be consistent on
3877 * disk. We must be able to restart the truncate after a crash.
3879 * The file's tree may be transiently inconsistent in memory (although it
3880 * probably isn't), but whenever we close off and commit a journal transaction,
3881 * the contents of (the filesystem + the journal) must be consistent and
3882 * restartable. It's pretty simple, really: bottom up, right to left (although
3883 * left-to-right works OK too).
3885 * Note that at recovery time, journal replay occurs *before* the restart of
3886 * truncate against the orphan inode list.
3888 * The committed inode has the new, desired i_size (which is the same as
3889 * i_disksize in this case). After a crash, ext4_orphan_cleanup() will see
3890 * that this inode's truncate did not complete and it will again call
3891 * ext4_truncate() to have another go. So there will be instantiated blocks
3892 * to the right of the truncation point in a crashed ext4 filesystem. But
3893 * that's fine - as long as they are linked from the inode, the post-crash
3894 * ext4_truncate() run will find them and release them.
3896 void ext4_truncate(struct inode *inode)
3898 handle_t *handle;
3899 struct ext4_inode_info *ei = EXT4_I(inode);
3900 __le32 *i_data = ei->i_data;
3901 int addr_per_block = EXT4_ADDR_PER_BLOCK(inode->i_sb);
3902 struct address_space *mapping = inode->i_mapping;
3903 ext4_lblk_t offsets[4];
3904 Indirect chain[4];
3905 Indirect *partial;
3906 __le32 nr = 0;
3907 int n;
3908 ext4_lblk_t last_block;
3909 unsigned blocksize = inode->i_sb->s_blocksize;
3911 if (!ext4_can_truncate(inode))
3912 return;
3914 if (inode->i_size == 0 && !test_opt(inode->i_sb, NO_AUTO_DA_ALLOC))
3915 ei->i_state |= EXT4_STATE_DA_ALLOC_CLOSE;
3917 if (EXT4_I(inode)->i_flags & EXT4_EXTENTS_FL) {
3918 ext4_ext_truncate(inode);
3919 return;
3922 handle = start_transaction(inode);
3923 if (IS_ERR(handle))
3924 return; /* AKPM: return what? */
3926 last_block = (inode->i_size + blocksize-1)
3927 >> EXT4_BLOCK_SIZE_BITS(inode->i_sb);
3929 if (inode->i_size & (blocksize - 1))
3930 if (ext4_block_truncate_page(handle, mapping, inode->i_size))
3931 goto out_stop;
3933 n = ext4_block_to_path(inode, last_block, offsets, NULL);
3934 if (n == 0)
3935 goto out_stop; /* error */
3938 * OK. This truncate is going to happen. We add the inode to the
3939 * orphan list, so that if this truncate spans multiple transactions,
3940 * and we crash, we will resume the truncate when the filesystem
3941 * recovers. It also marks the inode dirty, to catch the new size.
3943 * Implication: the file must always be in a sane, consistent
3944 * truncatable state while each transaction commits.
3946 if (ext4_orphan_add(handle, inode))
3947 goto out_stop;
3950 * From here we block out all ext4_get_block() callers who want to
3951 * modify the block allocation tree.
3953 down_write(&ei->i_data_sem);
3955 ext4_discard_preallocations(inode);
3958 * The orphan list entry will now protect us from any crash which
3959 * occurs before the truncate completes, so it is now safe to propagate
3960 * the new, shorter inode size (held for now in i_size) into the
3961 * on-disk inode. We do this via i_disksize, which is the value which
3962 * ext4 *really* writes onto the disk inode.
3964 ei->i_disksize = inode->i_size;
3966 if (n == 1) { /* direct blocks */
3967 ext4_free_data(handle, inode, NULL, i_data+offsets[0],
3968 i_data + EXT4_NDIR_BLOCKS);
3969 goto do_indirects;
3972 partial = ext4_find_shared(inode, n, offsets, chain, &nr);
3973 /* Kill the top of shared branch (not detached) */
3974 if (nr) {
3975 if (partial == chain) {
3976 /* Shared branch grows from the inode */
3977 ext4_free_branches(handle, inode, NULL,
3978 &nr, &nr+1, (chain+n-1) - partial);
3979 *partial->p = 0;
3981 * We mark the inode dirty prior to restart,
3982 * and prior to stop. No need for it here.
3984 } else {
3985 /* Shared branch grows from an indirect block */
3986 BUFFER_TRACE(partial->bh, "get_write_access");
3987 ext4_free_branches(handle, inode, partial->bh,
3988 partial->p,
3989 partial->p+1, (chain+n-1) - partial);
3992 /* Clear the ends of indirect blocks on the shared branch */
3993 while (partial > chain) {
3994 ext4_free_branches(handle, inode, partial->bh, partial->p + 1,
3995 (__le32*)partial->bh->b_data+addr_per_block,
3996 (chain+n-1) - partial);
3997 BUFFER_TRACE(partial->bh, "call brelse");
3998 brelse (partial->bh);
3999 partial--;
4001 do_indirects:
4002 /* Kill the remaining (whole) subtrees */
4003 switch (offsets[0]) {
4004 default:
4005 nr = i_data[EXT4_IND_BLOCK];
4006 if (nr) {
4007 ext4_free_branches(handle, inode, NULL, &nr, &nr+1, 1);
4008 i_data[EXT4_IND_BLOCK] = 0;
4010 case EXT4_IND_BLOCK:
4011 nr = i_data[EXT4_DIND_BLOCK];
4012 if (nr) {
4013 ext4_free_branches(handle, inode, NULL, &nr, &nr+1, 2);
4014 i_data[EXT4_DIND_BLOCK] = 0;
4016 case EXT4_DIND_BLOCK:
4017 nr = i_data[EXT4_TIND_BLOCK];
4018 if (nr) {
4019 ext4_free_branches(handle, inode, NULL, &nr, &nr+1, 3);
4020 i_data[EXT4_TIND_BLOCK] = 0;
4022 case EXT4_TIND_BLOCK:
4026 up_write(&ei->i_data_sem);
4027 inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
4028 ext4_mark_inode_dirty(handle, inode);
4031 * In a multi-transaction truncate, we only make the final transaction
4032 * synchronous
4034 if (IS_SYNC(inode))
4035 ext4_handle_sync(handle);
4036 out_stop:
4038 * If this was a simple ftruncate(), and the file will remain alive
4039 * then we need to clear up the orphan record which we created above.
4040 * However, if this was a real unlink then we were called by
4041 * ext4_delete_inode(), and we allow that function to clean up the
4042 * orphan info for us.
4044 if (inode->i_nlink)
4045 ext4_orphan_del(handle, inode);
4047 ext4_journal_stop(handle);
4051 * ext4_get_inode_loc returns with an extra refcount against the inode's
4052 * underlying buffer_head on success. If 'in_mem' is true, we have all
4053 * data in memory that is needed to recreate the on-disk version of this
4054 * inode.
4056 static int __ext4_get_inode_loc(struct inode *inode,
4057 struct ext4_iloc *iloc, int in_mem)
4059 struct ext4_group_desc *gdp;
4060 struct buffer_head *bh;
4061 struct super_block *sb = inode->i_sb;
4062 ext4_fsblk_t block;
4063 int inodes_per_block, inode_offset;
4065 iloc->bh = NULL;
4066 if (!ext4_valid_inum(sb, inode->i_ino))
4067 return -EIO;
4069 iloc->block_group = (inode->i_ino - 1) / EXT4_INODES_PER_GROUP(sb);
4070 gdp = ext4_get_group_desc(sb, iloc->block_group, NULL);
4071 if (!gdp)
4072 return -EIO;
4075 * Figure out the offset within the block group inode table
4077 inodes_per_block = (EXT4_BLOCK_SIZE(sb) / EXT4_INODE_SIZE(sb));
4078 inode_offset = ((inode->i_ino - 1) %
4079 EXT4_INODES_PER_GROUP(sb));
4080 block = ext4_inode_table(sb, gdp) + (inode_offset / inodes_per_block);
4081 iloc->offset = (inode_offset % inodes_per_block) * EXT4_INODE_SIZE(sb);
4083 bh = sb_getblk(sb, block);
4084 if (!bh) {
4085 ext4_error(sb, "ext4_get_inode_loc", "unable to read "
4086 "inode block - inode=%lu, block=%llu",
4087 inode->i_ino, block);
4088 return -EIO;
4090 if (!buffer_uptodate(bh)) {
4091 lock_buffer(bh);
4094 * If the buffer has the write error flag, we have failed
4095 * to write out another inode in the same block. In this
4096 * case, we don't have to read the block because we may
4097 * read the old inode data successfully.
4099 if (buffer_write_io_error(bh) && !buffer_uptodate(bh))
4100 set_buffer_uptodate(bh);
4102 if (buffer_uptodate(bh)) {
4103 /* someone brought it uptodate while we waited */
4104 unlock_buffer(bh);
4105 goto has_buffer;
4109 * If we have all information of the inode in memory and this
4110 * is the only valid inode in the block, we need not read the
4111 * block.
4113 if (in_mem) {
4114 struct buffer_head *bitmap_bh;
4115 int i, start;
4117 start = inode_offset & ~(inodes_per_block - 1);
4119 /* Is the inode bitmap in cache? */
4120 bitmap_bh = sb_getblk(sb, ext4_inode_bitmap(sb, gdp));
4121 if (!bitmap_bh)
4122 goto make_io;
4125 * If the inode bitmap isn't in cache then the
4126 * optimisation may end up performing two reads instead
4127 * of one, so skip it.
4129 if (!buffer_uptodate(bitmap_bh)) {
4130 brelse(bitmap_bh);
4131 goto make_io;
4133 for (i = start; i < start + inodes_per_block; i++) {
4134 if (i == inode_offset)
4135 continue;
4136 if (ext4_test_bit(i, bitmap_bh->b_data))
4137 break;
4139 brelse(bitmap_bh);
4140 if (i == start + inodes_per_block) {
4141 /* all other inodes are free, so skip I/O */
4142 memset(bh->b_data, 0, bh->b_size);
4143 set_buffer_uptodate(bh);
4144 unlock_buffer(bh);
4145 goto has_buffer;
4149 make_io:
4151 * If we need to do any I/O, try to pre-readahead extra
4152 * blocks from the inode table.
4154 if (EXT4_SB(sb)->s_inode_readahead_blks) {
4155 ext4_fsblk_t b, end, table;
4156 unsigned num;
4158 table = ext4_inode_table(sb, gdp);
4159 /* Make sure s_inode_readahead_blks is a power of 2 */
4160 while (EXT4_SB(sb)->s_inode_readahead_blks &
4161 (EXT4_SB(sb)->s_inode_readahead_blks-1))
4162 EXT4_SB(sb)->s_inode_readahead_blks =
4163 (EXT4_SB(sb)->s_inode_readahead_blks &
4164 (EXT4_SB(sb)->s_inode_readahead_blks-1));
4165 b = block & ~(EXT4_SB(sb)->s_inode_readahead_blks-1);
4166 if (table > b)
4167 b = table;
4168 end = b + EXT4_SB(sb)->s_inode_readahead_blks;
4169 num = EXT4_INODES_PER_GROUP(sb);
4170 if (EXT4_HAS_RO_COMPAT_FEATURE(sb,
4171 EXT4_FEATURE_RO_COMPAT_GDT_CSUM))
4172 num -= ext4_itable_unused_count(sb, gdp);
4173 table += num / inodes_per_block;
4174 if (end > table)
4175 end = table;
4176 while (b <= end)
4177 sb_breadahead(sb, b++);
4181 * There are other valid inodes in the buffer, this inode
4182 * has in-inode xattrs, or we don't have this inode in memory.
4183 * Read the block from disk.
4185 get_bh(bh);
4186 bh->b_end_io = end_buffer_read_sync;
4187 submit_bh(READ_META, bh);
4188 wait_on_buffer(bh);
4189 if (!buffer_uptodate(bh)) {
4190 ext4_error(sb, __func__,
4191 "unable to read inode block - inode=%lu, "
4192 "block=%llu", inode->i_ino, block);
4193 brelse(bh);
4194 return -EIO;
4197 has_buffer:
4198 iloc->bh = bh;
4199 return 0;
4202 int ext4_get_inode_loc(struct inode *inode, struct ext4_iloc *iloc)
4204 /* We have all inode data except xattrs in memory here. */
4205 return __ext4_get_inode_loc(inode, iloc,
4206 !(EXT4_I(inode)->i_state & EXT4_STATE_XATTR));
4209 void ext4_set_inode_flags(struct inode *inode)
4211 unsigned int flags = EXT4_I(inode)->i_flags;
4213 inode->i_flags &= ~(S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME|S_DIRSYNC);
4214 if (flags & EXT4_SYNC_FL)
4215 inode->i_flags |= S_SYNC;
4216 if (flags & EXT4_APPEND_FL)
4217 inode->i_flags |= S_APPEND;
4218 if (flags & EXT4_IMMUTABLE_FL)
4219 inode->i_flags |= S_IMMUTABLE;
4220 if (flags & EXT4_NOATIME_FL)
4221 inode->i_flags |= S_NOATIME;
4222 if (flags & EXT4_DIRSYNC_FL)
4223 inode->i_flags |= S_DIRSYNC;
4226 /* Propagate flags from i_flags to EXT4_I(inode)->i_flags */
4227 void ext4_get_inode_flags(struct ext4_inode_info *ei)
4229 unsigned int flags = ei->vfs_inode.i_flags;
4231 ei->i_flags &= ~(EXT4_SYNC_FL|EXT4_APPEND_FL|
4232 EXT4_IMMUTABLE_FL|EXT4_NOATIME_FL|EXT4_DIRSYNC_FL);
4233 if (flags & S_SYNC)
4234 ei->i_flags |= EXT4_SYNC_FL;
4235 if (flags & S_APPEND)
4236 ei->i_flags |= EXT4_APPEND_FL;
4237 if (flags & S_IMMUTABLE)
4238 ei->i_flags |= EXT4_IMMUTABLE_FL;
4239 if (flags & S_NOATIME)
4240 ei->i_flags |= EXT4_NOATIME_FL;
4241 if (flags & S_DIRSYNC)
4242 ei->i_flags |= EXT4_DIRSYNC_FL;
4244 static blkcnt_t ext4_inode_blocks(struct ext4_inode *raw_inode,
4245 struct ext4_inode_info *ei)
4247 blkcnt_t i_blocks ;
4248 struct inode *inode = &(ei->vfs_inode);
4249 struct super_block *sb = inode->i_sb;
4251 if (EXT4_HAS_RO_COMPAT_FEATURE(sb,
4252 EXT4_FEATURE_RO_COMPAT_HUGE_FILE)) {
4253 /* we are using combined 48 bit field */
4254 i_blocks = ((u64)le16_to_cpu(raw_inode->i_blocks_high)) << 32 |
4255 le32_to_cpu(raw_inode->i_blocks_lo);
4256 if (ei->i_flags & EXT4_HUGE_FILE_FL) {
4257 /* i_blocks represent file system block size */
4258 return i_blocks << (inode->i_blkbits - 9);
4259 } else {
4260 return i_blocks;
4262 } else {
4263 return le32_to_cpu(raw_inode->i_blocks_lo);
4267 struct inode *ext4_iget(struct super_block *sb, unsigned long ino)
4269 struct ext4_iloc iloc;
4270 struct ext4_inode *raw_inode;
4271 struct ext4_inode_info *ei;
4272 struct buffer_head *bh;
4273 struct inode *inode;
4274 long ret;
4275 int block;
4277 inode = iget_locked(sb, ino);
4278 if (!inode)
4279 return ERR_PTR(-ENOMEM);
4280 if (!(inode->i_state & I_NEW))
4281 return inode;
4283 ei = EXT4_I(inode);
4284 #ifdef CONFIG_EXT4_FS_POSIX_ACL
4285 ei->i_acl = EXT4_ACL_NOT_CACHED;
4286 ei->i_default_acl = EXT4_ACL_NOT_CACHED;
4287 #endif
4289 ret = __ext4_get_inode_loc(inode, &iloc, 0);
4290 if (ret < 0)
4291 goto bad_inode;
4292 bh = iloc.bh;
4293 raw_inode = ext4_raw_inode(&iloc);
4294 inode->i_mode = le16_to_cpu(raw_inode->i_mode);
4295 inode->i_uid = (uid_t)le16_to_cpu(raw_inode->i_uid_low);
4296 inode->i_gid = (gid_t)le16_to_cpu(raw_inode->i_gid_low);
4297 if (!(test_opt(inode->i_sb, NO_UID32))) {
4298 inode->i_uid |= le16_to_cpu(raw_inode->i_uid_high) << 16;
4299 inode->i_gid |= le16_to_cpu(raw_inode->i_gid_high) << 16;
4301 inode->i_nlink = le16_to_cpu(raw_inode->i_links_count);
4303 ei->i_state = 0;
4304 ei->i_dir_start_lookup = 0;
4305 ei->i_dtime = le32_to_cpu(raw_inode->i_dtime);
4306 /* We now have enough fields to check if the inode was active or not.
4307 * This is needed because nfsd might try to access dead inodes
4308 * the test is that same one that e2fsck uses
4309 * NeilBrown 1999oct15
4311 if (inode->i_nlink == 0) {
4312 if (inode->i_mode == 0 ||
4313 !(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_ORPHAN_FS)) {
4314 /* this inode is deleted */
4315 brelse(bh);
4316 ret = -ESTALE;
4317 goto bad_inode;
4319 /* The only unlinked inodes we let through here have
4320 * valid i_mode and are being read by the orphan
4321 * recovery code: that's fine, we're about to complete
4322 * the process of deleting those. */
4324 ei->i_flags = le32_to_cpu(raw_inode->i_flags);
4325 inode->i_blocks = ext4_inode_blocks(raw_inode, ei);
4326 ei->i_file_acl = le32_to_cpu(raw_inode->i_file_acl_lo);
4327 if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_64BIT))
4328 ei->i_file_acl |=
4329 ((__u64)le16_to_cpu(raw_inode->i_file_acl_high)) << 32;
4330 inode->i_size = ext4_isize(raw_inode);
4331 ei->i_disksize = inode->i_size;
4332 inode->i_generation = le32_to_cpu(raw_inode->i_generation);
4333 ei->i_block_group = iloc.block_group;
4335 * NOTE! The in-memory inode i_data array is in little-endian order
4336 * even on big-endian machines: we do NOT byteswap the block numbers!
4338 for (block = 0; block < EXT4_N_BLOCKS; block++)
4339 ei->i_data[block] = raw_inode->i_block[block];
4340 INIT_LIST_HEAD(&ei->i_orphan);
4342 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4343 ei->i_extra_isize = le16_to_cpu(raw_inode->i_extra_isize);
4344 if (EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize >
4345 EXT4_INODE_SIZE(inode->i_sb)) {
4346 brelse(bh);
4347 ret = -EIO;
4348 goto bad_inode;
4350 if (ei->i_extra_isize == 0) {
4351 /* The extra space is currently unused. Use it. */
4352 ei->i_extra_isize = sizeof(struct ext4_inode) -
4353 EXT4_GOOD_OLD_INODE_SIZE;
4354 } else {
4355 __le32 *magic = (void *)raw_inode +
4356 EXT4_GOOD_OLD_INODE_SIZE +
4357 ei->i_extra_isize;
4358 if (*magic == cpu_to_le32(EXT4_XATTR_MAGIC))
4359 ei->i_state |= EXT4_STATE_XATTR;
4361 } else
4362 ei->i_extra_isize = 0;
4364 EXT4_INODE_GET_XTIME(i_ctime, inode, raw_inode);
4365 EXT4_INODE_GET_XTIME(i_mtime, inode, raw_inode);
4366 EXT4_INODE_GET_XTIME(i_atime, inode, raw_inode);
4367 EXT4_EINODE_GET_XTIME(i_crtime, ei, raw_inode);
4369 inode->i_version = le32_to_cpu(raw_inode->i_disk_version);
4370 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4371 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
4372 inode->i_version |=
4373 (__u64)(le32_to_cpu(raw_inode->i_version_hi)) << 32;
4376 if (ei->i_file_acl &&
4377 ((ei->i_file_acl <
4378 (le32_to_cpu(EXT4_SB(sb)->s_es->s_first_data_block) +
4379 EXT4_SB(sb)->s_gdb_count)) ||
4380 (ei->i_file_acl >= ext4_blocks_count(EXT4_SB(sb)->s_es)))) {
4381 ext4_error(sb, __func__,
4382 "bad extended attribute block %llu in inode #%lu",
4383 ei->i_file_acl, inode->i_ino);
4384 ret = -EIO;
4385 goto bad_inode;
4388 if (S_ISREG(inode->i_mode)) {
4389 inode->i_op = &ext4_file_inode_operations;
4390 inode->i_fop = &ext4_file_operations;
4391 ext4_set_aops(inode);
4392 } else if (S_ISDIR(inode->i_mode)) {
4393 inode->i_op = &ext4_dir_inode_operations;
4394 inode->i_fop = &ext4_dir_operations;
4395 } else if (S_ISLNK(inode->i_mode)) {
4396 if (ext4_inode_is_fast_symlink(inode)) {
4397 inode->i_op = &ext4_fast_symlink_inode_operations;
4398 nd_terminate_link(ei->i_data, inode->i_size,
4399 sizeof(ei->i_data) - 1);
4400 } else {
4401 inode->i_op = &ext4_symlink_inode_operations;
4402 ext4_set_aops(inode);
4404 } else if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode) ||
4405 S_ISFIFO(inode->i_mode) || S_ISSOCK(inode->i_mode)) {
4406 inode->i_op = &ext4_special_inode_operations;
4407 if (raw_inode->i_block[0])
4408 init_special_inode(inode, inode->i_mode,
4409 old_decode_dev(le32_to_cpu(raw_inode->i_block[0])));
4410 else
4411 init_special_inode(inode, inode->i_mode,
4412 new_decode_dev(le32_to_cpu(raw_inode->i_block[1])));
4413 } else {
4414 brelse(bh);
4415 ret = -EIO;
4416 ext4_error(inode->i_sb, __func__,
4417 "bogus i_mode (%o) for inode=%lu",
4418 inode->i_mode, inode->i_ino);
4419 goto bad_inode;
4421 brelse(iloc.bh);
4422 ext4_set_inode_flags(inode);
4423 unlock_new_inode(inode);
4424 return inode;
4426 bad_inode:
4427 iget_failed(inode);
4428 return ERR_PTR(ret);
4431 static int ext4_inode_blocks_set(handle_t *handle,
4432 struct ext4_inode *raw_inode,
4433 struct ext4_inode_info *ei)
4435 struct inode *inode = &(ei->vfs_inode);
4436 u64 i_blocks = inode->i_blocks;
4437 struct super_block *sb = inode->i_sb;
4439 if (i_blocks <= ~0U) {
4441 * i_blocks can be represnted in a 32 bit variable
4442 * as multiple of 512 bytes
4444 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
4445 raw_inode->i_blocks_high = 0;
4446 ei->i_flags &= ~EXT4_HUGE_FILE_FL;
4447 return 0;
4449 if (!EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_HUGE_FILE))
4450 return -EFBIG;
4452 if (i_blocks <= 0xffffffffffffULL) {
4454 * i_blocks can be represented in a 48 bit variable
4455 * as multiple of 512 bytes
4457 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
4458 raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
4459 ei->i_flags &= ~EXT4_HUGE_FILE_FL;
4460 } else {
4461 ei->i_flags |= EXT4_HUGE_FILE_FL;
4462 /* i_block is stored in file system block size */
4463 i_blocks = i_blocks >> (inode->i_blkbits - 9);
4464 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
4465 raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
4467 return 0;
4471 * Post the struct inode info into an on-disk inode location in the
4472 * buffer-cache. This gobbles the caller's reference to the
4473 * buffer_head in the inode location struct.
4475 * The caller must have write access to iloc->bh.
4477 static int ext4_do_update_inode(handle_t *handle,
4478 struct inode *inode,
4479 struct ext4_iloc *iloc)
4481 struct ext4_inode *raw_inode = ext4_raw_inode(iloc);
4482 struct ext4_inode_info *ei = EXT4_I(inode);
4483 struct buffer_head *bh = iloc->bh;
4484 int err = 0, rc, block;
4486 /* For fields not not tracking in the in-memory inode,
4487 * initialise them to zero for new inodes. */
4488 if (ei->i_state & EXT4_STATE_NEW)
4489 memset(raw_inode, 0, EXT4_SB(inode->i_sb)->s_inode_size);
4491 ext4_get_inode_flags(ei);
4492 raw_inode->i_mode = cpu_to_le16(inode->i_mode);
4493 if (!(test_opt(inode->i_sb, NO_UID32))) {
4494 raw_inode->i_uid_low = cpu_to_le16(low_16_bits(inode->i_uid));
4495 raw_inode->i_gid_low = cpu_to_le16(low_16_bits(inode->i_gid));
4497 * Fix up interoperability with old kernels. Otherwise, old inodes get
4498 * re-used with the upper 16 bits of the uid/gid intact
4500 if (!ei->i_dtime) {
4501 raw_inode->i_uid_high =
4502 cpu_to_le16(high_16_bits(inode->i_uid));
4503 raw_inode->i_gid_high =
4504 cpu_to_le16(high_16_bits(inode->i_gid));
4505 } else {
4506 raw_inode->i_uid_high = 0;
4507 raw_inode->i_gid_high = 0;
4509 } else {
4510 raw_inode->i_uid_low =
4511 cpu_to_le16(fs_high2lowuid(inode->i_uid));
4512 raw_inode->i_gid_low =
4513 cpu_to_le16(fs_high2lowgid(inode->i_gid));
4514 raw_inode->i_uid_high = 0;
4515 raw_inode->i_gid_high = 0;
4517 raw_inode->i_links_count = cpu_to_le16(inode->i_nlink);
4519 EXT4_INODE_SET_XTIME(i_ctime, inode, raw_inode);
4520 EXT4_INODE_SET_XTIME(i_mtime, inode, raw_inode);
4521 EXT4_INODE_SET_XTIME(i_atime, inode, raw_inode);
4522 EXT4_EINODE_SET_XTIME(i_crtime, ei, raw_inode);
4524 if (ext4_inode_blocks_set(handle, raw_inode, ei))
4525 goto out_brelse;
4526 raw_inode->i_dtime = cpu_to_le32(ei->i_dtime);
4527 /* clear the migrate flag in the raw_inode */
4528 raw_inode->i_flags = cpu_to_le32(ei->i_flags & ~EXT4_EXT_MIGRATE);
4529 if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
4530 cpu_to_le32(EXT4_OS_HURD))
4531 raw_inode->i_file_acl_high =
4532 cpu_to_le16(ei->i_file_acl >> 32);
4533 raw_inode->i_file_acl_lo = cpu_to_le32(ei->i_file_acl);
4534 ext4_isize_set(raw_inode, ei->i_disksize);
4535 if (ei->i_disksize > 0x7fffffffULL) {
4536 struct super_block *sb = inode->i_sb;
4537 if (!EXT4_HAS_RO_COMPAT_FEATURE(sb,
4538 EXT4_FEATURE_RO_COMPAT_LARGE_FILE) ||
4539 EXT4_SB(sb)->s_es->s_rev_level ==
4540 cpu_to_le32(EXT4_GOOD_OLD_REV)) {
4541 /* If this is the first large file
4542 * created, add a flag to the superblock.
4544 err = ext4_journal_get_write_access(handle,
4545 EXT4_SB(sb)->s_sbh);
4546 if (err)
4547 goto out_brelse;
4548 ext4_update_dynamic_rev(sb);
4549 EXT4_SET_RO_COMPAT_FEATURE(sb,
4550 EXT4_FEATURE_RO_COMPAT_LARGE_FILE);
4551 sb->s_dirt = 1;
4552 ext4_handle_sync(handle);
4553 err = ext4_handle_dirty_metadata(handle, inode,
4554 EXT4_SB(sb)->s_sbh);
4557 raw_inode->i_generation = cpu_to_le32(inode->i_generation);
4558 if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) {
4559 if (old_valid_dev(inode->i_rdev)) {
4560 raw_inode->i_block[0] =
4561 cpu_to_le32(old_encode_dev(inode->i_rdev));
4562 raw_inode->i_block[1] = 0;
4563 } else {
4564 raw_inode->i_block[0] = 0;
4565 raw_inode->i_block[1] =
4566 cpu_to_le32(new_encode_dev(inode->i_rdev));
4567 raw_inode->i_block[2] = 0;
4569 } else for (block = 0; block < EXT4_N_BLOCKS; block++)
4570 raw_inode->i_block[block] = ei->i_data[block];
4572 raw_inode->i_disk_version = cpu_to_le32(inode->i_version);
4573 if (ei->i_extra_isize) {
4574 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
4575 raw_inode->i_version_hi =
4576 cpu_to_le32(inode->i_version >> 32);
4577 raw_inode->i_extra_isize = cpu_to_le16(ei->i_extra_isize);
4580 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
4581 rc = ext4_handle_dirty_metadata(handle, inode, bh);
4582 if (!err)
4583 err = rc;
4584 ei->i_state &= ~EXT4_STATE_NEW;
4586 out_brelse:
4587 brelse(bh);
4588 ext4_std_error(inode->i_sb, err);
4589 return err;
4593 * ext4_write_inode()
4595 * We are called from a few places:
4597 * - Within generic_file_write() for O_SYNC files.
4598 * Here, there will be no transaction running. We wait for any running
4599 * trasnaction to commit.
4601 * - Within sys_sync(), kupdate and such.
4602 * We wait on commit, if tol to.
4604 * - Within prune_icache() (PF_MEMALLOC == true)
4605 * Here we simply return. We can't afford to block kswapd on the
4606 * journal commit.
4608 * In all cases it is actually safe for us to return without doing anything,
4609 * because the inode has been copied into a raw inode buffer in
4610 * ext4_mark_inode_dirty(). This is a correctness thing for O_SYNC and for
4611 * knfsd.
4613 * Note that we are absolutely dependent upon all inode dirtiers doing the
4614 * right thing: they *must* call mark_inode_dirty() after dirtying info in
4615 * which we are interested.
4617 * It would be a bug for them to not do this. The code:
4619 * mark_inode_dirty(inode)
4620 * stuff();
4621 * inode->i_size = expr;
4623 * is in error because a kswapd-driven write_inode() could occur while
4624 * `stuff()' is running, and the new i_size will be lost. Plus the inode
4625 * will no longer be on the superblock's dirty inode list.
4627 int ext4_write_inode(struct inode *inode, int wait)
4629 if (current->flags & PF_MEMALLOC)
4630 return 0;
4632 if (ext4_journal_current_handle()) {
4633 jbd_debug(1, "called recursively, non-PF_MEMALLOC!\n");
4634 dump_stack();
4635 return -EIO;
4638 if (!wait)
4639 return 0;
4641 return ext4_force_commit(inode->i_sb);
4644 int __ext4_write_dirty_metadata(struct inode *inode, struct buffer_head *bh)
4646 int err = 0;
4648 mark_buffer_dirty(bh);
4649 if (inode && inode_needs_sync(inode)) {
4650 sync_dirty_buffer(bh);
4651 if (buffer_req(bh) && !buffer_uptodate(bh)) {
4652 ext4_error(inode->i_sb, __func__,
4653 "IO error syncing inode, "
4654 "inode=%lu, block=%llu",
4655 inode->i_ino,
4656 (unsigned long long)bh->b_blocknr);
4657 err = -EIO;
4660 return err;
4664 * ext4_setattr()
4666 * Called from notify_change.
4668 * We want to trap VFS attempts to truncate the file as soon as
4669 * possible. In particular, we want to make sure that when the VFS
4670 * shrinks i_size, we put the inode on the orphan list and modify
4671 * i_disksize immediately, so that during the subsequent flushing of
4672 * dirty pages and freeing of disk blocks, we can guarantee that any
4673 * commit will leave the blocks being flushed in an unused state on
4674 * disk. (On recovery, the inode will get truncated and the blocks will
4675 * be freed, so we have a strong guarantee that no future commit will
4676 * leave these blocks visible to the user.)
4678 * Another thing we have to assure is that if we are in ordered mode
4679 * and inode is still attached to the committing transaction, we must
4680 * we start writeout of all the dirty pages which are being truncated.
4681 * This way we are sure that all the data written in the previous
4682 * transaction are already on disk (truncate waits for pages under
4683 * writeback).
4685 * Called with inode->i_mutex down.
4687 int ext4_setattr(struct dentry *dentry, struct iattr *attr)
4689 struct inode *inode = dentry->d_inode;
4690 int error, rc = 0;
4691 const unsigned int ia_valid = attr->ia_valid;
4693 error = inode_change_ok(inode, attr);
4694 if (error)
4695 return error;
4697 if ((ia_valid & ATTR_UID && attr->ia_uid != inode->i_uid) ||
4698 (ia_valid & ATTR_GID && attr->ia_gid != inode->i_gid)) {
4699 handle_t *handle;
4701 /* (user+group)*(old+new) structure, inode write (sb,
4702 * inode block, ? - but truncate inode update has it) */
4703 handle = ext4_journal_start(inode, 2*(EXT4_QUOTA_INIT_BLOCKS(inode->i_sb)+
4704 EXT4_QUOTA_DEL_BLOCKS(inode->i_sb))+3);
4705 if (IS_ERR(handle)) {
4706 error = PTR_ERR(handle);
4707 goto err_out;
4709 error = DQUOT_TRANSFER(inode, attr) ? -EDQUOT : 0;
4710 if (error) {
4711 ext4_journal_stop(handle);
4712 return error;
4714 /* Update corresponding info in inode so that everything is in
4715 * one transaction */
4716 if (attr->ia_valid & ATTR_UID)
4717 inode->i_uid = attr->ia_uid;
4718 if (attr->ia_valid & ATTR_GID)
4719 inode->i_gid = attr->ia_gid;
4720 error = ext4_mark_inode_dirty(handle, inode);
4721 ext4_journal_stop(handle);
4724 if (attr->ia_valid & ATTR_SIZE) {
4725 if (!(EXT4_I(inode)->i_flags & EXT4_EXTENTS_FL)) {
4726 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4728 if (attr->ia_size > sbi->s_bitmap_maxbytes) {
4729 error = -EFBIG;
4730 goto err_out;
4735 if (S_ISREG(inode->i_mode) &&
4736 attr->ia_valid & ATTR_SIZE && attr->ia_size < inode->i_size) {
4737 handle_t *handle;
4739 handle = ext4_journal_start(inode, 3);
4740 if (IS_ERR(handle)) {
4741 error = PTR_ERR(handle);
4742 goto err_out;
4745 error = ext4_orphan_add(handle, inode);
4746 EXT4_I(inode)->i_disksize = attr->ia_size;
4747 rc = ext4_mark_inode_dirty(handle, inode);
4748 if (!error)
4749 error = rc;
4750 ext4_journal_stop(handle);
4752 if (ext4_should_order_data(inode)) {
4753 error = ext4_begin_ordered_truncate(inode,
4754 attr->ia_size);
4755 if (error) {
4756 /* Do as much error cleanup as possible */
4757 handle = ext4_journal_start(inode, 3);
4758 if (IS_ERR(handle)) {
4759 ext4_orphan_del(NULL, inode);
4760 goto err_out;
4762 ext4_orphan_del(handle, inode);
4763 ext4_journal_stop(handle);
4764 goto err_out;
4769 rc = inode_setattr(inode, attr);
4771 /* If inode_setattr's call to ext4_truncate failed to get a
4772 * transaction handle at all, we need to clean up the in-core
4773 * orphan list manually. */
4774 if (inode->i_nlink)
4775 ext4_orphan_del(NULL, inode);
4777 if (!rc && (ia_valid & ATTR_MODE))
4778 rc = ext4_acl_chmod(inode);
4780 err_out:
4781 ext4_std_error(inode->i_sb, error);
4782 if (!error)
4783 error = rc;
4784 return error;
4787 int ext4_getattr(struct vfsmount *mnt, struct dentry *dentry,
4788 struct kstat *stat)
4790 struct inode *inode;
4791 unsigned long delalloc_blocks;
4793 inode = dentry->d_inode;
4794 generic_fillattr(inode, stat);
4797 * We can't update i_blocks if the block allocation is delayed
4798 * otherwise in the case of system crash before the real block
4799 * allocation is done, we will have i_blocks inconsistent with
4800 * on-disk file blocks.
4801 * We always keep i_blocks updated together with real
4802 * allocation. But to not confuse with user, stat
4803 * will return the blocks that include the delayed allocation
4804 * blocks for this file.
4806 spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
4807 delalloc_blocks = EXT4_I(inode)->i_reserved_data_blocks;
4808 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
4810 stat->blocks += (delalloc_blocks << inode->i_sb->s_blocksize_bits)>>9;
4811 return 0;
4814 static int ext4_indirect_trans_blocks(struct inode *inode, int nrblocks,
4815 int chunk)
4817 int indirects;
4819 /* if nrblocks are contiguous */
4820 if (chunk) {
4822 * With N contiguous data blocks, it need at most
4823 * N/EXT4_ADDR_PER_BLOCK(inode->i_sb) indirect blocks
4824 * 2 dindirect blocks
4825 * 1 tindirect block
4827 indirects = nrblocks / EXT4_ADDR_PER_BLOCK(inode->i_sb);
4828 return indirects + 3;
4831 * if nrblocks are not contiguous, worse case, each block touch
4832 * a indirect block, and each indirect block touch a double indirect
4833 * block, plus a triple indirect block
4835 indirects = nrblocks * 2 + 1;
4836 return indirects;
4839 static int ext4_index_trans_blocks(struct inode *inode, int nrblocks, int chunk)
4841 if (!(EXT4_I(inode)->i_flags & EXT4_EXTENTS_FL))
4842 return ext4_indirect_trans_blocks(inode, nrblocks, chunk);
4843 return ext4_ext_index_trans_blocks(inode, nrblocks, chunk);
4847 * Account for index blocks, block groups bitmaps and block group
4848 * descriptor blocks if modify datablocks and index blocks
4849 * worse case, the indexs blocks spread over different block groups
4851 * If datablocks are discontiguous, they are possible to spread over
4852 * different block groups too. If they are contiugous, with flexbg,
4853 * they could still across block group boundary.
4855 * Also account for superblock, inode, quota and xattr blocks
4857 int ext4_meta_trans_blocks(struct inode *inode, int nrblocks, int chunk)
4859 int groups, gdpblocks;
4860 int idxblocks;
4861 int ret = 0;
4864 * How many index blocks need to touch to modify nrblocks?
4865 * The "Chunk" flag indicating whether the nrblocks is
4866 * physically contiguous on disk
4868 * For Direct IO and fallocate, they calls get_block to allocate
4869 * one single extent at a time, so they could set the "Chunk" flag
4871 idxblocks = ext4_index_trans_blocks(inode, nrblocks, chunk);
4873 ret = idxblocks;
4876 * Now let's see how many group bitmaps and group descriptors need
4877 * to account
4879 groups = idxblocks;
4880 if (chunk)
4881 groups += 1;
4882 else
4883 groups += nrblocks;
4885 gdpblocks = groups;
4886 if (groups > EXT4_SB(inode->i_sb)->s_groups_count)
4887 groups = EXT4_SB(inode->i_sb)->s_groups_count;
4888 if (groups > EXT4_SB(inode->i_sb)->s_gdb_count)
4889 gdpblocks = EXT4_SB(inode->i_sb)->s_gdb_count;
4891 /* bitmaps and block group descriptor blocks */
4892 ret += groups + gdpblocks;
4894 /* Blocks for super block, inode, quota and xattr blocks */
4895 ret += EXT4_META_TRANS_BLOCKS(inode->i_sb);
4897 return ret;
4901 * Calulate the total number of credits to reserve to fit
4902 * the modification of a single pages into a single transaction,
4903 * which may include multiple chunks of block allocations.
4905 * This could be called via ext4_write_begin()
4907 * We need to consider the worse case, when
4908 * one new block per extent.
4910 int ext4_writepage_trans_blocks(struct inode *inode)
4912 int bpp = ext4_journal_blocks_per_page(inode);
4913 int ret;
4915 ret = ext4_meta_trans_blocks(inode, bpp, 0);
4917 /* Account for data blocks for journalled mode */
4918 if (ext4_should_journal_data(inode))
4919 ret += bpp;
4920 return ret;
4924 * Calculate the journal credits for a chunk of data modification.
4926 * This is called from DIO, fallocate or whoever calling
4927 * ext4_get_blocks_wrap() to map/allocate a chunk of contigous disk blocks.
4929 * journal buffers for data blocks are not included here, as DIO
4930 * and fallocate do no need to journal data buffers.
4932 int ext4_chunk_trans_blocks(struct inode *inode, int nrblocks)
4934 return ext4_meta_trans_blocks(inode, nrblocks, 1);
4938 * The caller must have previously called ext4_reserve_inode_write().
4939 * Give this, we know that the caller already has write access to iloc->bh.
4941 int ext4_mark_iloc_dirty(handle_t *handle,
4942 struct inode *inode, struct ext4_iloc *iloc)
4944 int err = 0;
4946 if (test_opt(inode->i_sb, I_VERSION))
4947 inode_inc_iversion(inode);
4949 /* the do_update_inode consumes one bh->b_count */
4950 get_bh(iloc->bh);
4952 /* ext4_do_update_inode() does jbd2_journal_dirty_metadata */
4953 err = ext4_do_update_inode(handle, inode, iloc);
4954 put_bh(iloc->bh);
4955 return err;
4959 * On success, We end up with an outstanding reference count against
4960 * iloc->bh. This _must_ be cleaned up later.
4964 ext4_reserve_inode_write(handle_t *handle, struct inode *inode,
4965 struct ext4_iloc *iloc)
4967 int err;
4969 err = ext4_get_inode_loc(inode, iloc);
4970 if (!err) {
4971 BUFFER_TRACE(iloc->bh, "get_write_access");
4972 err = ext4_journal_get_write_access(handle, iloc->bh);
4973 if (err) {
4974 brelse(iloc->bh);
4975 iloc->bh = NULL;
4978 ext4_std_error(inode->i_sb, err);
4979 return err;
4983 * Expand an inode by new_extra_isize bytes.
4984 * Returns 0 on success or negative error number on failure.
4986 static int ext4_expand_extra_isize(struct inode *inode,
4987 unsigned int new_extra_isize,
4988 struct ext4_iloc iloc,
4989 handle_t *handle)
4991 struct ext4_inode *raw_inode;
4992 struct ext4_xattr_ibody_header *header;
4993 struct ext4_xattr_entry *entry;
4995 if (EXT4_I(inode)->i_extra_isize >= new_extra_isize)
4996 return 0;
4998 raw_inode = ext4_raw_inode(&iloc);
5000 header = IHDR(inode, raw_inode);
5001 entry = IFIRST(header);
5003 /* No extended attributes present */
5004 if (!(EXT4_I(inode)->i_state & EXT4_STATE_XATTR) ||
5005 header->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC)) {
5006 memset((void *)raw_inode + EXT4_GOOD_OLD_INODE_SIZE, 0,
5007 new_extra_isize);
5008 EXT4_I(inode)->i_extra_isize = new_extra_isize;
5009 return 0;
5012 /* try to expand with EAs present */
5013 return ext4_expand_extra_isize_ea(inode, new_extra_isize,
5014 raw_inode, handle);
5018 * What we do here is to mark the in-core inode as clean with respect to inode
5019 * dirtiness (it may still be data-dirty).
5020 * This means that the in-core inode may be reaped by prune_icache
5021 * without having to perform any I/O. This is a very good thing,
5022 * because *any* task may call prune_icache - even ones which
5023 * have a transaction open against a different journal.
5025 * Is this cheating? Not really. Sure, we haven't written the
5026 * inode out, but prune_icache isn't a user-visible syncing function.
5027 * Whenever the user wants stuff synced (sys_sync, sys_msync, sys_fsync)
5028 * we start and wait on commits.
5030 * Is this efficient/effective? Well, we're being nice to the system
5031 * by cleaning up our inodes proactively so they can be reaped
5032 * without I/O. But we are potentially leaving up to five seconds'
5033 * worth of inodes floating about which prune_icache wants us to
5034 * write out. One way to fix that would be to get prune_icache()
5035 * to do a write_super() to free up some memory. It has the desired
5036 * effect.
5038 int ext4_mark_inode_dirty(handle_t *handle, struct inode *inode)
5040 struct ext4_iloc iloc;
5041 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
5042 static unsigned int mnt_count;
5043 int err, ret;
5045 might_sleep();
5046 err = ext4_reserve_inode_write(handle, inode, &iloc);
5047 if (ext4_handle_valid(handle) &&
5048 EXT4_I(inode)->i_extra_isize < sbi->s_want_extra_isize &&
5049 !(EXT4_I(inode)->i_state & EXT4_STATE_NO_EXPAND)) {
5051 * We need extra buffer credits since we may write into EA block
5052 * with this same handle. If journal_extend fails, then it will
5053 * only result in a minor loss of functionality for that inode.
5054 * If this is felt to be critical, then e2fsck should be run to
5055 * force a large enough s_min_extra_isize.
5057 if ((jbd2_journal_extend(handle,
5058 EXT4_DATA_TRANS_BLOCKS(inode->i_sb))) == 0) {
5059 ret = ext4_expand_extra_isize(inode,
5060 sbi->s_want_extra_isize,
5061 iloc, handle);
5062 if (ret) {
5063 EXT4_I(inode)->i_state |= EXT4_STATE_NO_EXPAND;
5064 if (mnt_count !=
5065 le16_to_cpu(sbi->s_es->s_mnt_count)) {
5066 ext4_warning(inode->i_sb, __func__,
5067 "Unable to expand inode %lu. Delete"
5068 " some EAs or run e2fsck.",
5069 inode->i_ino);
5070 mnt_count =
5071 le16_to_cpu(sbi->s_es->s_mnt_count);
5076 if (!err)
5077 err = ext4_mark_iloc_dirty(handle, inode, &iloc);
5078 return err;
5082 * ext4_dirty_inode() is called from __mark_inode_dirty()
5084 * We're really interested in the case where a file is being extended.
5085 * i_size has been changed by generic_commit_write() and we thus need
5086 * to include the updated inode in the current transaction.
5088 * Also, DQUOT_ALLOC_SPACE() will always dirty the inode when blocks
5089 * are allocated to the file.
5091 * If the inode is marked synchronous, we don't honour that here - doing
5092 * so would cause a commit on atime updates, which we don't bother doing.
5093 * We handle synchronous inodes at the highest possible level.
5095 void ext4_dirty_inode(struct inode *inode)
5097 handle_t *current_handle = ext4_journal_current_handle();
5098 handle_t *handle;
5100 if (!ext4_handle_valid(current_handle)) {
5101 ext4_mark_inode_dirty(current_handle, inode);
5102 return;
5105 handle = ext4_journal_start(inode, 2);
5106 if (IS_ERR(handle))
5107 goto out;
5108 if (current_handle &&
5109 current_handle->h_transaction != handle->h_transaction) {
5110 /* This task has a transaction open against a different fs */
5111 printk(KERN_EMERG "%s: transactions do not match!\n",
5112 __func__);
5113 } else {
5114 jbd_debug(5, "marking dirty. outer handle=%p\n",
5115 current_handle);
5116 ext4_mark_inode_dirty(handle, inode);
5118 ext4_journal_stop(handle);
5119 out:
5120 return;
5123 #if 0
5125 * Bind an inode's backing buffer_head into this transaction, to prevent
5126 * it from being flushed to disk early. Unlike
5127 * ext4_reserve_inode_write, this leaves behind no bh reference and
5128 * returns no iloc structure, so the caller needs to repeat the iloc
5129 * lookup to mark the inode dirty later.
5131 static int ext4_pin_inode(handle_t *handle, struct inode *inode)
5133 struct ext4_iloc iloc;
5135 int err = 0;
5136 if (handle) {
5137 err = ext4_get_inode_loc(inode, &iloc);
5138 if (!err) {
5139 BUFFER_TRACE(iloc.bh, "get_write_access");
5140 err = jbd2_journal_get_write_access(handle, iloc.bh);
5141 if (!err)
5142 err = ext4_handle_dirty_metadata(handle,
5143 inode,
5144 iloc.bh);
5145 brelse(iloc.bh);
5148 ext4_std_error(inode->i_sb, err);
5149 return err;
5151 #endif
5153 int ext4_change_inode_journal_flag(struct inode *inode, int val)
5155 journal_t *journal;
5156 handle_t *handle;
5157 int err;
5160 * We have to be very careful here: changing a data block's
5161 * journaling status dynamically is dangerous. If we write a
5162 * data block to the journal, change the status and then delete
5163 * that block, we risk forgetting to revoke the old log record
5164 * from the journal and so a subsequent replay can corrupt data.
5165 * So, first we make sure that the journal is empty and that
5166 * nobody is changing anything.
5169 journal = EXT4_JOURNAL(inode);
5170 if (!journal)
5171 return 0;
5172 if (is_journal_aborted(journal))
5173 return -EROFS;
5175 jbd2_journal_lock_updates(journal);
5176 jbd2_journal_flush(journal);
5179 * OK, there are no updates running now, and all cached data is
5180 * synced to disk. We are now in a completely consistent state
5181 * which doesn't have anything in the journal, and we know that
5182 * no filesystem updates are running, so it is safe to modify
5183 * the inode's in-core data-journaling state flag now.
5186 if (val)
5187 EXT4_I(inode)->i_flags |= EXT4_JOURNAL_DATA_FL;
5188 else
5189 EXT4_I(inode)->i_flags &= ~EXT4_JOURNAL_DATA_FL;
5190 ext4_set_aops(inode);
5192 jbd2_journal_unlock_updates(journal);
5194 /* Finally we can mark the inode as dirty. */
5196 handle = ext4_journal_start(inode, 1);
5197 if (IS_ERR(handle))
5198 return PTR_ERR(handle);
5200 err = ext4_mark_inode_dirty(handle, inode);
5201 ext4_handle_sync(handle);
5202 ext4_journal_stop(handle);
5203 ext4_std_error(inode->i_sb, err);
5205 return err;
5208 static int ext4_bh_unmapped(handle_t *handle, struct buffer_head *bh)
5210 return !buffer_mapped(bh);
5213 int ext4_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
5215 struct page *page = vmf->page;
5216 loff_t size;
5217 unsigned long len;
5218 int ret = -EINVAL;
5219 void *fsdata;
5220 struct file *file = vma->vm_file;
5221 struct inode *inode = file->f_path.dentry->d_inode;
5222 struct address_space *mapping = inode->i_mapping;
5225 * Get i_alloc_sem to stop truncates messing with the inode. We cannot
5226 * get i_mutex because we are already holding mmap_sem.
5228 down_read(&inode->i_alloc_sem);
5229 size = i_size_read(inode);
5230 if (page->mapping != mapping || size <= page_offset(page)
5231 || !PageUptodate(page)) {
5232 /* page got truncated from under us? */
5233 goto out_unlock;
5235 ret = 0;
5236 if (PageMappedToDisk(page))
5237 goto out_unlock;
5239 if (page->index == size >> PAGE_CACHE_SHIFT)
5240 len = size & ~PAGE_CACHE_MASK;
5241 else
5242 len = PAGE_CACHE_SIZE;
5244 if (page_has_buffers(page)) {
5245 /* return if we have all the buffers mapped */
5246 if (!walk_page_buffers(NULL, page_buffers(page), 0, len, NULL,
5247 ext4_bh_unmapped))
5248 goto out_unlock;
5251 * OK, we need to fill the hole... Do write_begin write_end
5252 * to do block allocation/reservation.We are not holding
5253 * inode.i__mutex here. That allow * parallel write_begin,
5254 * write_end call. lock_page prevent this from happening
5255 * on the same page though
5257 ret = mapping->a_ops->write_begin(file, mapping, page_offset(page),
5258 len, AOP_FLAG_UNINTERRUPTIBLE, &page, &fsdata);
5259 if (ret < 0)
5260 goto out_unlock;
5261 ret = mapping->a_ops->write_end(file, mapping, page_offset(page),
5262 len, len, page, fsdata);
5263 if (ret < 0)
5264 goto out_unlock;
5265 ret = 0;
5266 out_unlock:
5267 if (ret)
5268 ret = VM_FAULT_SIGBUS;
5269 up_read(&inode->i_alloc_sem);
5270 return ret;