thinkpad-acpi: Fix procfs hotkey reset command
[linux-2.6/linux-acpi-2.6/ibm-acpi-2.6.git] / fs / ext4 / inode.c
blobb7f20b0bb0ee5a70fb506ada9f22eed6db4f902d
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/uio.h>
38 #include <linux/bio.h>
39 #include "ext4_jbd2.h"
40 #include "xattr.h"
41 #include "acl.h"
42 #include "ext4_extents.h"
44 #define MPAGE_DA_EXTENT_TAIL 0x01
46 static inline int ext4_begin_ordered_truncate(struct inode *inode,
47 loff_t new_size)
49 return jbd2_journal_begin_ordered_truncate(
50 EXT4_SB(inode->i_sb)->s_journal,
51 &EXT4_I(inode)->jinode,
52 new_size);
55 static void ext4_invalidatepage(struct page *page, unsigned long offset);
58 * Test whether an inode is a fast symlink.
60 static int ext4_inode_is_fast_symlink(struct inode *inode)
62 int ea_blocks = EXT4_I(inode)->i_file_acl ?
63 (inode->i_sb->s_blocksize >> 9) : 0;
65 return (S_ISLNK(inode->i_mode) && inode->i_blocks - ea_blocks == 0);
69 * The ext4 forget function must perform a revoke if we are freeing data
70 * which has been journaled. Metadata (eg. indirect blocks) must be
71 * revoked in all cases.
73 * "bh" may be NULL: a metadata block may have been freed from memory
74 * but there may still be a record of it in the journal, and that record
75 * still needs to be revoked.
77 int ext4_forget(handle_t *handle, int is_metadata, struct inode *inode,
78 struct buffer_head *bh, ext4_fsblk_t blocknr)
80 int err;
82 might_sleep();
84 BUFFER_TRACE(bh, "enter");
86 jbd_debug(4, "forgetting bh %p: is_metadata = %d, mode %o, "
87 "data mode %lx\n",
88 bh, is_metadata, inode->i_mode,
89 test_opt(inode->i_sb, DATA_FLAGS));
91 /* Never use the revoke function if we are doing full data
92 * journaling: there is no need to, and a V1 superblock won't
93 * support it. Otherwise, only skip the revoke on un-journaled
94 * data blocks. */
96 if (test_opt(inode->i_sb, DATA_FLAGS) == EXT4_MOUNT_JOURNAL_DATA ||
97 (!is_metadata && !ext4_should_journal_data(inode))) {
98 if (bh) {
99 BUFFER_TRACE(bh, "call jbd2_journal_forget");
100 return ext4_journal_forget(handle, bh);
102 return 0;
106 * data!=journal && (is_metadata || should_journal_data(inode))
108 BUFFER_TRACE(bh, "call ext4_journal_revoke");
109 err = ext4_journal_revoke(handle, blocknr, bh);
110 if (err)
111 ext4_abort(inode->i_sb, __func__,
112 "error %d when attempting revoke", err);
113 BUFFER_TRACE(bh, "exit");
114 return err;
118 * Work out how many blocks we need to proceed with the next chunk of a
119 * truncate transaction.
121 static unsigned long blocks_for_truncate(struct inode *inode)
123 ext4_lblk_t needed;
125 needed = inode->i_blocks >> (inode->i_sb->s_blocksize_bits - 9);
127 /* Give ourselves just enough room to cope with inodes in which
128 * i_blocks is corrupt: we've seen disk corruptions in the past
129 * which resulted in random data in an inode which looked enough
130 * like a regular file for ext4 to try to delete it. Things
131 * will go a bit crazy if that happens, but at least we should
132 * try not to panic the whole kernel. */
133 if (needed < 2)
134 needed = 2;
136 /* But we need to bound the transaction so we don't overflow the
137 * journal. */
138 if (needed > EXT4_MAX_TRANS_DATA)
139 needed = EXT4_MAX_TRANS_DATA;
141 return EXT4_DATA_TRANS_BLOCKS(inode->i_sb) + needed;
145 * Truncate transactions can be complex and absolutely huge. So we need to
146 * be able to restart the transaction at a conventient checkpoint to make
147 * sure we don't overflow the journal.
149 * start_transaction gets us a new handle for a truncate transaction,
150 * and extend_transaction tries to extend the existing one a bit. If
151 * extend fails, we need to propagate the failure up and restart the
152 * transaction in the top-level truncate loop. --sct
154 static handle_t *start_transaction(struct inode *inode)
156 handle_t *result;
158 result = ext4_journal_start(inode, blocks_for_truncate(inode));
159 if (!IS_ERR(result))
160 return result;
162 ext4_std_error(inode->i_sb, PTR_ERR(result));
163 return result;
167 * Try to extend this transaction for the purposes of truncation.
169 * Returns 0 if we managed to create more room. If we can't create more
170 * room, and the transaction must be restarted we return 1.
172 static int try_to_extend_transaction(handle_t *handle, struct inode *inode)
174 if (handle->h_buffer_credits > EXT4_RESERVE_TRANS_BLOCKS)
175 return 0;
176 if (!ext4_journal_extend(handle, blocks_for_truncate(inode)))
177 return 0;
178 return 1;
182 * Restart the transaction associated with *handle. This does a commit,
183 * so before we call here everything must be consistently dirtied against
184 * this transaction.
186 static int ext4_journal_test_restart(handle_t *handle, struct inode *inode)
188 jbd_debug(2, "restarting handle %p\n", handle);
189 return ext4_journal_restart(handle, blocks_for_truncate(inode));
193 * Called at the last iput() if i_nlink is zero.
195 void ext4_delete_inode(struct inode *inode)
197 handle_t *handle;
198 int err;
200 if (ext4_should_order_data(inode))
201 ext4_begin_ordered_truncate(inode, 0);
202 truncate_inode_pages(&inode->i_data, 0);
204 if (is_bad_inode(inode))
205 goto no_delete;
207 handle = ext4_journal_start(inode, blocks_for_truncate(inode)+3);
208 if (IS_ERR(handle)) {
209 ext4_std_error(inode->i_sb, PTR_ERR(handle));
211 * If we're going to skip the normal cleanup, we still need to
212 * make sure that the in-core orphan linked list is properly
213 * cleaned up.
215 ext4_orphan_del(NULL, inode);
216 goto no_delete;
219 if (IS_SYNC(inode))
220 handle->h_sync = 1;
221 inode->i_size = 0;
222 err = ext4_mark_inode_dirty(handle, inode);
223 if (err) {
224 ext4_warning(inode->i_sb, __func__,
225 "couldn't mark inode dirty (err %d)", err);
226 goto stop_handle;
228 if (inode->i_blocks)
229 ext4_truncate(inode);
232 * ext4_ext_truncate() doesn't reserve any slop when it
233 * restarts journal transactions; therefore there may not be
234 * enough credits left in the handle to remove the inode from
235 * the orphan list and set the dtime field.
237 if (handle->h_buffer_credits < 3) {
238 err = ext4_journal_extend(handle, 3);
239 if (err > 0)
240 err = ext4_journal_restart(handle, 3);
241 if (err != 0) {
242 ext4_warning(inode->i_sb, __func__,
243 "couldn't extend journal (err %d)", err);
244 stop_handle:
245 ext4_journal_stop(handle);
246 goto no_delete;
251 * Kill off the orphan record which ext4_truncate created.
252 * AKPM: I think this can be inside the above `if'.
253 * Note that ext4_orphan_del() has to be able to cope with the
254 * deletion of a non-existent orphan - this is because we don't
255 * know if ext4_truncate() actually created an orphan record.
256 * (Well, we could do this if we need to, but heck - it works)
258 ext4_orphan_del(handle, inode);
259 EXT4_I(inode)->i_dtime = get_seconds();
262 * One subtle ordering requirement: if anything has gone wrong
263 * (transaction abort, IO errors, whatever), then we can still
264 * do these next steps (the fs will already have been marked as
265 * having errors), but we can't free the inode if the mark_dirty
266 * fails.
268 if (ext4_mark_inode_dirty(handle, inode))
269 /* If that failed, just do the required in-core inode clear. */
270 clear_inode(inode);
271 else
272 ext4_free_inode(handle, inode);
273 ext4_journal_stop(handle);
274 return;
275 no_delete:
276 clear_inode(inode); /* We must guarantee clearing of inode... */
279 typedef struct {
280 __le32 *p;
281 __le32 key;
282 struct buffer_head *bh;
283 } Indirect;
285 static inline void add_chain(Indirect *p, struct buffer_head *bh, __le32 *v)
287 p->key = *(p->p = v);
288 p->bh = bh;
292 * ext4_block_to_path - parse the block number into array of offsets
293 * @inode: inode in question (we are only interested in its superblock)
294 * @i_block: block number to be parsed
295 * @offsets: array to store the offsets in
296 * @boundary: set this non-zero if the referred-to block is likely to be
297 * followed (on disk) by an indirect block.
299 * To store the locations of file's data ext4 uses a data structure common
300 * for UNIX filesystems - tree of pointers anchored in the inode, with
301 * data blocks at leaves and indirect blocks in intermediate nodes.
302 * This function translates the block number into path in that tree -
303 * return value is the path length and @offsets[n] is the offset of
304 * pointer to (n+1)th node in the nth one. If @block is out of range
305 * (negative or too large) warning is printed and zero returned.
307 * Note: function doesn't find node addresses, so no IO is needed. All
308 * we need to know is the capacity of indirect blocks (taken from the
309 * inode->i_sb).
313 * Portability note: the last comparison (check that we fit into triple
314 * indirect block) is spelled differently, because otherwise on an
315 * architecture with 32-bit longs and 8Kb pages we might get into trouble
316 * if our filesystem had 8Kb blocks. We might use long long, but that would
317 * kill us on x86. Oh, well, at least the sign propagation does not matter -
318 * i_block would have to be negative in the very beginning, so we would not
319 * get there at all.
322 static int ext4_block_to_path(struct inode *inode,
323 ext4_lblk_t i_block,
324 ext4_lblk_t offsets[4], int *boundary)
326 int ptrs = EXT4_ADDR_PER_BLOCK(inode->i_sb);
327 int ptrs_bits = EXT4_ADDR_PER_BLOCK_BITS(inode->i_sb);
328 const long direct_blocks = EXT4_NDIR_BLOCKS,
329 indirect_blocks = ptrs,
330 double_blocks = (1 << (ptrs_bits * 2));
331 int n = 0;
332 int final = 0;
334 if (i_block < 0) {
335 ext4_warning(inode->i_sb, "ext4_block_to_path", "block < 0");
336 } else if (i_block < direct_blocks) {
337 offsets[n++] = i_block;
338 final = direct_blocks;
339 } else if ((i_block -= direct_blocks) < indirect_blocks) {
340 offsets[n++] = EXT4_IND_BLOCK;
341 offsets[n++] = i_block;
342 final = ptrs;
343 } else if ((i_block -= indirect_blocks) < double_blocks) {
344 offsets[n++] = EXT4_DIND_BLOCK;
345 offsets[n++] = i_block >> ptrs_bits;
346 offsets[n++] = i_block & (ptrs - 1);
347 final = ptrs;
348 } else if (((i_block -= double_blocks) >> (ptrs_bits * 2)) < ptrs) {
349 offsets[n++] = EXT4_TIND_BLOCK;
350 offsets[n++] = i_block >> (ptrs_bits * 2);
351 offsets[n++] = (i_block >> ptrs_bits) & (ptrs - 1);
352 offsets[n++] = i_block & (ptrs - 1);
353 final = ptrs;
354 } else {
355 ext4_warning(inode->i_sb, "ext4_block_to_path",
356 "block %lu > max in inode %lu",
357 i_block + direct_blocks +
358 indirect_blocks + double_blocks, inode->i_ino);
360 if (boundary)
361 *boundary = final - 1 - (i_block & (ptrs - 1));
362 return n;
366 * ext4_get_branch - read the chain of indirect blocks leading to data
367 * @inode: inode in question
368 * @depth: depth of the chain (1 - direct pointer, etc.)
369 * @offsets: offsets of pointers in inode/indirect blocks
370 * @chain: place to store the result
371 * @err: here we store the error value
373 * Function fills the array of triples <key, p, bh> and returns %NULL
374 * if everything went OK or the pointer to the last filled triple
375 * (incomplete one) otherwise. Upon the return chain[i].key contains
376 * the number of (i+1)-th block in the chain (as it is stored in memory,
377 * i.e. little-endian 32-bit), chain[i].p contains the address of that
378 * number (it points into struct inode for i==0 and into the bh->b_data
379 * for i>0) and chain[i].bh points to the buffer_head of i-th indirect
380 * block for i>0 and NULL for i==0. In other words, it holds the block
381 * numbers of the chain, addresses they were taken from (and where we can
382 * verify that chain did not change) and buffer_heads hosting these
383 * numbers.
385 * Function stops when it stumbles upon zero pointer (absent block)
386 * (pointer to last triple returned, *@err == 0)
387 * or when it gets an IO error reading an indirect block
388 * (ditto, *@err == -EIO)
389 * or when it reads all @depth-1 indirect blocks successfully and finds
390 * the whole chain, all way to the data (returns %NULL, *err == 0).
392 * Need to be called with
393 * down_read(&EXT4_I(inode)->i_data_sem)
395 static Indirect *ext4_get_branch(struct inode *inode, int depth,
396 ext4_lblk_t *offsets,
397 Indirect chain[4], int *err)
399 struct super_block *sb = inode->i_sb;
400 Indirect *p = chain;
401 struct buffer_head *bh;
403 *err = 0;
404 /* i_data is not going away, no lock needed */
405 add_chain(chain, NULL, EXT4_I(inode)->i_data + *offsets);
406 if (!p->key)
407 goto no_block;
408 while (--depth) {
409 bh = sb_bread(sb, le32_to_cpu(p->key));
410 if (!bh)
411 goto failure;
412 add_chain(++p, bh, (__le32 *)bh->b_data + *++offsets);
413 /* Reader: end */
414 if (!p->key)
415 goto no_block;
417 return NULL;
419 failure:
420 *err = -EIO;
421 no_block:
422 return p;
426 * ext4_find_near - find a place for allocation with sufficient locality
427 * @inode: owner
428 * @ind: descriptor of indirect block.
430 * This function returns the preferred place for block allocation.
431 * It is used when heuristic for sequential allocation fails.
432 * Rules are:
433 * + if there is a block to the left of our position - allocate near it.
434 * + if pointer will live in indirect block - allocate near that block.
435 * + if pointer will live in inode - allocate in the same
436 * cylinder group.
438 * In the latter case we colour the starting block by the callers PID to
439 * prevent it from clashing with concurrent allocations for a different inode
440 * in the same block group. The PID is used here so that functionally related
441 * files will be close-by on-disk.
443 * Caller must make sure that @ind is valid and will stay that way.
445 static ext4_fsblk_t ext4_find_near(struct inode *inode, Indirect *ind)
447 struct ext4_inode_info *ei = EXT4_I(inode);
448 __le32 *start = ind->bh ? (__le32 *) ind->bh->b_data : ei->i_data;
449 __le32 *p;
450 ext4_fsblk_t bg_start;
451 ext4_fsblk_t last_block;
452 ext4_grpblk_t colour;
454 /* Try to find previous block */
455 for (p = ind->p - 1; p >= start; p--) {
456 if (*p)
457 return le32_to_cpu(*p);
460 /* No such thing, so let's try location of indirect block */
461 if (ind->bh)
462 return ind->bh->b_blocknr;
465 * It is going to be referred to from the inode itself? OK, just put it
466 * into the same cylinder group then.
468 bg_start = ext4_group_first_block_no(inode->i_sb, ei->i_block_group);
469 last_block = ext4_blocks_count(EXT4_SB(inode->i_sb)->s_es) - 1;
471 if (bg_start + EXT4_BLOCKS_PER_GROUP(inode->i_sb) <= last_block)
472 colour = (current->pid % 16) *
473 (EXT4_BLOCKS_PER_GROUP(inode->i_sb) / 16);
474 else
475 colour = (current->pid % 16) * ((last_block - bg_start) / 16);
476 return bg_start + colour;
480 * ext4_find_goal - find a preferred place for allocation.
481 * @inode: owner
482 * @block: block we want
483 * @partial: pointer to the last triple within a chain
485 * Normally this function find the preferred place for block allocation,
486 * returns it.
488 static ext4_fsblk_t ext4_find_goal(struct inode *inode, ext4_lblk_t block,
489 Indirect *partial)
492 * XXX need to get goal block from mballoc's data structures
495 return ext4_find_near(inode, partial);
499 * ext4_blks_to_allocate: Look up the block map and count the number
500 * of direct blocks need to be allocated for the given branch.
502 * @branch: chain of indirect blocks
503 * @k: number of blocks need for indirect blocks
504 * @blks: number of data blocks to be mapped.
505 * @blocks_to_boundary: the offset in the indirect block
507 * return the total number of blocks to be allocate, including the
508 * direct and indirect blocks.
510 static int ext4_blks_to_allocate(Indirect *branch, int k, unsigned long blks,
511 int blocks_to_boundary)
513 unsigned long count = 0;
516 * Simple case, [t,d]Indirect block(s) has not allocated yet
517 * then it's clear blocks on that path have not allocated
519 if (k > 0) {
520 /* right now we don't handle cross boundary allocation */
521 if (blks < blocks_to_boundary + 1)
522 count += blks;
523 else
524 count += blocks_to_boundary + 1;
525 return count;
528 count++;
529 while (count < blks && count <= blocks_to_boundary &&
530 le32_to_cpu(*(branch[0].p + count)) == 0) {
531 count++;
533 return count;
537 * ext4_alloc_blocks: multiple allocate blocks needed for a branch
538 * @indirect_blks: the number of blocks need to allocate for indirect
539 * blocks
541 * @new_blocks: on return it will store the new block numbers for
542 * the indirect blocks(if needed) and the first direct block,
543 * @blks: on return it will store the total number of allocated
544 * direct blocks
546 static int ext4_alloc_blocks(handle_t *handle, struct inode *inode,
547 ext4_lblk_t iblock, ext4_fsblk_t goal,
548 int indirect_blks, int blks,
549 ext4_fsblk_t new_blocks[4], int *err)
551 int target, i;
552 unsigned long count = 0, blk_allocated = 0;
553 int index = 0;
554 ext4_fsblk_t current_block = 0;
555 int ret = 0;
558 * Here we try to allocate the requested multiple blocks at once,
559 * on a best-effort basis.
560 * To build a branch, we should allocate blocks for
561 * the indirect blocks(if not allocated yet), and at least
562 * the first direct block of this branch. That's the
563 * minimum number of blocks need to allocate(required)
565 /* first we try to allocate the indirect blocks */
566 target = indirect_blks;
567 while (target > 0) {
568 count = target;
569 /* allocating blocks for indirect blocks and direct blocks */
570 current_block = ext4_new_meta_blocks(handle, inode,
571 goal, &count, err);
572 if (*err)
573 goto failed_out;
575 target -= count;
576 /* allocate blocks for indirect blocks */
577 while (index < indirect_blks && count) {
578 new_blocks[index++] = current_block++;
579 count--;
581 if (count > 0) {
583 * save the new block number
584 * for the first direct block
586 new_blocks[index] = current_block;
587 printk(KERN_INFO "%s returned more blocks than "
588 "requested\n", __func__);
589 WARN_ON(1);
590 break;
594 target = blks - count ;
595 blk_allocated = count;
596 if (!target)
597 goto allocated;
598 /* Now allocate data blocks */
599 count = target;
600 /* allocating blocks for data blocks */
601 current_block = ext4_new_blocks(handle, inode, iblock,
602 goal, &count, err);
603 if (*err && (target == blks)) {
605 * if the allocation failed and we didn't allocate
606 * any blocks before
608 goto failed_out;
610 if (!*err) {
611 if (target == blks) {
613 * save the new block number
614 * for the first direct block
616 new_blocks[index] = current_block;
618 blk_allocated += count;
620 allocated:
621 /* total number of blocks allocated for direct blocks */
622 ret = blk_allocated;
623 *err = 0;
624 return ret;
625 failed_out:
626 for (i = 0; i < index; i++)
627 ext4_free_blocks(handle, inode, new_blocks[i], 1, 0);
628 return ret;
632 * ext4_alloc_branch - allocate and set up a chain of blocks.
633 * @inode: owner
634 * @indirect_blks: number of allocated indirect blocks
635 * @blks: number of allocated direct blocks
636 * @offsets: offsets (in the blocks) to store the pointers to next.
637 * @branch: place to store the chain in.
639 * This function allocates blocks, zeroes out all but the last one,
640 * links them into chain and (if we are synchronous) writes them to disk.
641 * In other words, it prepares a branch that can be spliced onto the
642 * inode. It stores the information about that chain in the branch[], in
643 * the same format as ext4_get_branch() would do. We are calling it after
644 * we had read the existing part of chain and partial points to the last
645 * triple of that (one with zero ->key). Upon the exit we have the same
646 * picture as after the successful ext4_get_block(), except that in one
647 * place chain is disconnected - *branch->p is still zero (we did not
648 * set the last link), but branch->key contains the number that should
649 * be placed into *branch->p to fill that gap.
651 * If allocation fails we free all blocks we've allocated (and forget
652 * their buffer_heads) and return the error value the from failed
653 * ext4_alloc_block() (normally -ENOSPC). Otherwise we set the chain
654 * as described above and return 0.
656 static int ext4_alloc_branch(handle_t *handle, struct inode *inode,
657 ext4_lblk_t iblock, int indirect_blks,
658 int *blks, ext4_fsblk_t goal,
659 ext4_lblk_t *offsets, Indirect *branch)
661 int blocksize = inode->i_sb->s_blocksize;
662 int i, n = 0;
663 int err = 0;
664 struct buffer_head *bh;
665 int num;
666 ext4_fsblk_t new_blocks[4];
667 ext4_fsblk_t current_block;
669 num = ext4_alloc_blocks(handle, inode, iblock, goal, indirect_blks,
670 *blks, new_blocks, &err);
671 if (err)
672 return err;
674 branch[0].key = cpu_to_le32(new_blocks[0]);
676 * metadata blocks and data blocks are allocated.
678 for (n = 1; n <= indirect_blks; n++) {
680 * Get buffer_head for parent block, zero it out
681 * and set the pointer to new one, then send
682 * parent to disk.
684 bh = sb_getblk(inode->i_sb, new_blocks[n-1]);
685 branch[n].bh = bh;
686 lock_buffer(bh);
687 BUFFER_TRACE(bh, "call get_create_access");
688 err = ext4_journal_get_create_access(handle, bh);
689 if (err) {
690 unlock_buffer(bh);
691 brelse(bh);
692 goto failed;
695 memset(bh->b_data, 0, blocksize);
696 branch[n].p = (__le32 *) bh->b_data + offsets[n];
697 branch[n].key = cpu_to_le32(new_blocks[n]);
698 *branch[n].p = branch[n].key;
699 if (n == indirect_blks) {
700 current_block = new_blocks[n];
702 * End of chain, update the last new metablock of
703 * the chain to point to the new allocated
704 * data blocks numbers
706 for (i=1; i < num; i++)
707 *(branch[n].p + i) = cpu_to_le32(++current_block);
709 BUFFER_TRACE(bh, "marking uptodate");
710 set_buffer_uptodate(bh);
711 unlock_buffer(bh);
713 BUFFER_TRACE(bh, "call ext4_journal_dirty_metadata");
714 err = ext4_journal_dirty_metadata(handle, bh);
715 if (err)
716 goto failed;
718 *blks = num;
719 return err;
720 failed:
721 /* Allocation failed, free what we already allocated */
722 for (i = 1; i <= n ; i++) {
723 BUFFER_TRACE(branch[i].bh, "call jbd2_journal_forget");
724 ext4_journal_forget(handle, branch[i].bh);
726 for (i = 0; i < indirect_blks; i++)
727 ext4_free_blocks(handle, inode, new_blocks[i], 1, 0);
729 ext4_free_blocks(handle, inode, new_blocks[i], num, 0);
731 return err;
735 * ext4_splice_branch - splice the allocated branch onto inode.
736 * @inode: owner
737 * @block: (logical) number of block we are adding
738 * @chain: chain of indirect blocks (with a missing link - see
739 * ext4_alloc_branch)
740 * @where: location of missing link
741 * @num: number of indirect blocks we are adding
742 * @blks: number of direct blocks we are adding
744 * This function fills the missing link and does all housekeeping needed in
745 * inode (->i_blocks, etc.). In case of success we end up with the full
746 * chain to new block and return 0.
748 static int ext4_splice_branch(handle_t *handle, struct inode *inode,
749 ext4_lblk_t block, Indirect *where, int num, int blks)
751 int i;
752 int err = 0;
753 ext4_fsblk_t current_block;
756 * If we're splicing into a [td]indirect block (as opposed to the
757 * inode) then we need to get write access to the [td]indirect block
758 * before the splice.
760 if (where->bh) {
761 BUFFER_TRACE(where->bh, "get_write_access");
762 err = ext4_journal_get_write_access(handle, where->bh);
763 if (err)
764 goto err_out;
766 /* That's it */
768 *where->p = where->key;
771 * Update the host buffer_head or inode to point to more just allocated
772 * direct blocks blocks
774 if (num == 0 && blks > 1) {
775 current_block = le32_to_cpu(where->key) + 1;
776 for (i = 1; i < blks; i++)
777 *(where->p + i) = cpu_to_le32(current_block++);
780 /* We are done with atomic stuff, now do the rest of housekeeping */
782 inode->i_ctime = ext4_current_time(inode);
783 ext4_mark_inode_dirty(handle, inode);
785 /* had we spliced it onto indirect block? */
786 if (where->bh) {
788 * If we spliced it onto an indirect block, we haven't
789 * altered the inode. Note however that if it is being spliced
790 * onto an indirect block at the very end of the file (the
791 * file is growing) then we *will* alter the inode to reflect
792 * the new i_size. But that is not done here - it is done in
793 * generic_commit_write->__mark_inode_dirty->ext4_dirty_inode.
795 jbd_debug(5, "splicing indirect only\n");
796 BUFFER_TRACE(where->bh, "call ext4_journal_dirty_metadata");
797 err = ext4_journal_dirty_metadata(handle, where->bh);
798 if (err)
799 goto err_out;
800 } else {
802 * OK, we spliced it into the inode itself on a direct block.
803 * Inode was dirtied above.
805 jbd_debug(5, "splicing direct\n");
807 return err;
809 err_out:
810 for (i = 1; i <= num; i++) {
811 BUFFER_TRACE(where[i].bh, "call jbd2_journal_forget");
812 ext4_journal_forget(handle, where[i].bh);
813 ext4_free_blocks(handle, inode,
814 le32_to_cpu(where[i-1].key), 1, 0);
816 ext4_free_blocks(handle, inode, le32_to_cpu(where[num].key), blks, 0);
818 return err;
822 * Allocation strategy is simple: if we have to allocate something, we will
823 * have to go the whole way to leaf. So let's do it before attaching anything
824 * to tree, set linkage between the newborn blocks, write them if sync is
825 * required, recheck the path, free and repeat if check fails, otherwise
826 * set the last missing link (that will protect us from any truncate-generated
827 * removals - all blocks on the path are immune now) and possibly force the
828 * write on the parent block.
829 * That has a nice additional property: no special recovery from the failed
830 * allocations is needed - we simply release blocks and do not touch anything
831 * reachable from inode.
833 * `handle' can be NULL if create == 0.
835 * return > 0, # of blocks mapped or allocated.
836 * return = 0, if plain lookup failed.
837 * return < 0, error case.
840 * Need to be called with
841 * down_read(&EXT4_I(inode)->i_data_sem) if not allocating file system block
842 * (ie, create is zero). Otherwise down_write(&EXT4_I(inode)->i_data_sem)
844 int ext4_get_blocks_handle(handle_t *handle, struct inode *inode,
845 ext4_lblk_t iblock, unsigned long maxblocks,
846 struct buffer_head *bh_result,
847 int create, int extend_disksize)
849 int err = -EIO;
850 ext4_lblk_t offsets[4];
851 Indirect chain[4];
852 Indirect *partial;
853 ext4_fsblk_t goal;
854 int indirect_blks;
855 int blocks_to_boundary = 0;
856 int depth;
857 struct ext4_inode_info *ei = EXT4_I(inode);
858 int count = 0;
859 ext4_fsblk_t first_block = 0;
860 loff_t disksize;
863 J_ASSERT(!(EXT4_I(inode)->i_flags & EXT4_EXTENTS_FL));
864 J_ASSERT(handle != NULL || create == 0);
865 depth = ext4_block_to_path(inode, iblock, offsets,
866 &blocks_to_boundary);
868 if (depth == 0)
869 goto out;
871 partial = ext4_get_branch(inode, depth, offsets, chain, &err);
873 /* Simplest case - block found, no allocation needed */
874 if (!partial) {
875 first_block = le32_to_cpu(chain[depth - 1].key);
876 clear_buffer_new(bh_result);
877 count++;
878 /*map more blocks*/
879 while (count < maxblocks && count <= blocks_to_boundary) {
880 ext4_fsblk_t blk;
882 blk = le32_to_cpu(*(chain[depth-1].p + count));
884 if (blk == first_block + count)
885 count++;
886 else
887 break;
889 goto got_it;
892 /* Next simple case - plain lookup or failed read of indirect block */
893 if (!create || err == -EIO)
894 goto cleanup;
897 * Okay, we need to do block allocation.
899 goal = ext4_find_goal(inode, iblock, partial);
901 /* the number of blocks need to allocate for [d,t]indirect blocks */
902 indirect_blks = (chain + depth) - partial - 1;
905 * Next look up the indirect map to count the totoal number of
906 * direct blocks to allocate for this branch.
908 count = ext4_blks_to_allocate(partial, indirect_blks,
909 maxblocks, blocks_to_boundary);
911 * Block out ext4_truncate while we alter the tree
913 err = ext4_alloc_branch(handle, inode, iblock, indirect_blks,
914 &count, goal,
915 offsets + (partial - chain), partial);
918 * The ext4_splice_branch call will free and forget any buffers
919 * on the new chain if there is a failure, but that risks using
920 * up transaction credits, especially for bitmaps where the
921 * credits cannot be returned. Can we handle this somehow? We
922 * may need to return -EAGAIN upwards in the worst case. --sct
924 if (!err)
925 err = ext4_splice_branch(handle, inode, iblock,
926 partial, indirect_blks, count);
928 * i_disksize growing is protected by i_data_sem. Don't forget to
929 * protect it if you're about to implement concurrent
930 * ext4_get_block() -bzzz
932 if (!err && extend_disksize) {
933 disksize = ((loff_t) iblock + count) << inode->i_blkbits;
934 if (disksize > i_size_read(inode))
935 disksize = i_size_read(inode);
936 if (disksize > ei->i_disksize)
937 ei->i_disksize = disksize;
939 if (err)
940 goto cleanup;
942 set_buffer_new(bh_result);
943 got_it:
944 map_bh(bh_result, inode->i_sb, le32_to_cpu(chain[depth-1].key));
945 if (count > blocks_to_boundary)
946 set_buffer_boundary(bh_result);
947 err = count;
948 /* Clean up and exit */
949 partial = chain + depth - 1; /* the whole chain */
950 cleanup:
951 while (partial > chain) {
952 BUFFER_TRACE(partial->bh, "call brelse");
953 brelse(partial->bh);
954 partial--;
956 BUFFER_TRACE(bh_result, "returned");
957 out:
958 return err;
962 * Calculate the number of metadata blocks need to reserve
963 * to allocate @blocks for non extent file based file
965 static int ext4_indirect_calc_metadata_amount(struct inode *inode, int blocks)
967 int icap = EXT4_ADDR_PER_BLOCK(inode->i_sb);
968 int ind_blks, dind_blks, tind_blks;
970 /* number of new indirect blocks needed */
971 ind_blks = (blocks + icap - 1) / icap;
973 dind_blks = (ind_blks + icap - 1) / icap;
975 tind_blks = 1;
977 return ind_blks + dind_blks + tind_blks;
981 * Calculate the number of metadata blocks need to reserve
982 * to allocate given number of blocks
984 static int ext4_calc_metadata_amount(struct inode *inode, int blocks)
986 if (!blocks)
987 return 0;
989 if (EXT4_I(inode)->i_flags & EXT4_EXTENTS_FL)
990 return ext4_ext_calc_metadata_amount(inode, blocks);
992 return ext4_indirect_calc_metadata_amount(inode, blocks);
995 static void ext4_da_update_reserve_space(struct inode *inode, int used)
997 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
998 int total, mdb, mdb_free;
1000 spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
1001 /* recalculate the number of metablocks still need to be reserved */
1002 total = EXT4_I(inode)->i_reserved_data_blocks - used;
1003 mdb = ext4_calc_metadata_amount(inode, total);
1005 /* figure out how many metablocks to release */
1006 BUG_ON(mdb > EXT4_I(inode)->i_reserved_meta_blocks);
1007 mdb_free = EXT4_I(inode)->i_reserved_meta_blocks - mdb;
1009 if (mdb_free) {
1010 /* Account for allocated meta_blocks */
1011 mdb_free -= EXT4_I(inode)->i_allocated_meta_blocks;
1013 /* update fs dirty blocks counter */
1014 percpu_counter_sub(&sbi->s_dirtyblocks_counter, mdb_free);
1015 EXT4_I(inode)->i_allocated_meta_blocks = 0;
1016 EXT4_I(inode)->i_reserved_meta_blocks = mdb;
1019 /* update per-inode reservations */
1020 BUG_ON(used > EXT4_I(inode)->i_reserved_data_blocks);
1021 EXT4_I(inode)->i_reserved_data_blocks -= used;
1023 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
1027 * The ext4_get_blocks_wrap() function try to look up the requested blocks,
1028 * and returns if the blocks are already mapped.
1030 * Otherwise it takes the write lock of the i_data_sem and allocate blocks
1031 * and store the allocated blocks in the result buffer head and mark it
1032 * mapped.
1034 * If file type is extents based, it will call ext4_ext_get_blocks(),
1035 * Otherwise, call with ext4_get_blocks_handle() to handle indirect mapping
1036 * based files
1038 * On success, it returns the number of blocks being mapped or allocate.
1039 * if create==0 and the blocks are pre-allocated and uninitialized block,
1040 * the result buffer head is unmapped. If the create ==1, it will make sure
1041 * the buffer head is mapped.
1043 * It returns 0 if plain look up failed (blocks have not been allocated), in
1044 * that casem, buffer head is unmapped
1046 * It returns the error in case of allocation failure.
1048 int ext4_get_blocks_wrap(handle_t *handle, struct inode *inode, sector_t block,
1049 unsigned long max_blocks, struct buffer_head *bh,
1050 int create, int extend_disksize, int flag)
1052 int retval;
1054 clear_buffer_mapped(bh);
1057 * Try to see if we can get the block without requesting
1058 * for new file system block.
1060 down_read((&EXT4_I(inode)->i_data_sem));
1061 if (EXT4_I(inode)->i_flags & EXT4_EXTENTS_FL) {
1062 retval = ext4_ext_get_blocks(handle, inode, block, max_blocks,
1063 bh, 0, 0);
1064 } else {
1065 retval = ext4_get_blocks_handle(handle,
1066 inode, block, max_blocks, bh, 0, 0);
1068 up_read((&EXT4_I(inode)->i_data_sem));
1070 /* If it is only a block(s) look up */
1071 if (!create)
1072 return retval;
1075 * Returns if the blocks have already allocated
1077 * Note that if blocks have been preallocated
1078 * ext4_ext_get_block() returns th create = 0
1079 * with buffer head unmapped.
1081 if (retval > 0 && buffer_mapped(bh))
1082 return retval;
1085 * New blocks allocate and/or writing to uninitialized extent
1086 * will possibly result in updating i_data, so we take
1087 * the write lock of i_data_sem, and call get_blocks()
1088 * with create == 1 flag.
1090 down_write((&EXT4_I(inode)->i_data_sem));
1093 * if the caller is from delayed allocation writeout path
1094 * we have already reserved fs blocks for allocation
1095 * let the underlying get_block() function know to
1096 * avoid double accounting
1098 if (flag)
1099 EXT4_I(inode)->i_delalloc_reserved_flag = 1;
1101 * We need to check for EXT4 here because migrate
1102 * could have changed the inode type in between
1104 if (EXT4_I(inode)->i_flags & EXT4_EXTENTS_FL) {
1105 retval = ext4_ext_get_blocks(handle, inode, block, max_blocks,
1106 bh, create, extend_disksize);
1107 } else {
1108 retval = ext4_get_blocks_handle(handle, inode, block,
1109 max_blocks, bh, create, extend_disksize);
1111 if (retval > 0 && buffer_new(bh)) {
1113 * We allocated new blocks which will result in
1114 * i_data's format changing. Force the migrate
1115 * to fail by clearing migrate flags
1117 EXT4_I(inode)->i_flags = EXT4_I(inode)->i_flags &
1118 ~EXT4_EXT_MIGRATE;
1122 if (flag) {
1123 EXT4_I(inode)->i_delalloc_reserved_flag = 0;
1125 * Update reserved blocks/metadata blocks
1126 * after successful block allocation
1127 * which were deferred till now
1129 if ((retval > 0) && buffer_delay(bh))
1130 ext4_da_update_reserve_space(inode, retval);
1133 up_write((&EXT4_I(inode)->i_data_sem));
1134 return retval;
1137 /* Maximum number of blocks we map for direct IO at once. */
1138 #define DIO_MAX_BLOCKS 4096
1140 int ext4_get_block(struct inode *inode, sector_t iblock,
1141 struct buffer_head *bh_result, int create)
1143 handle_t *handle = ext4_journal_current_handle();
1144 int ret = 0, started = 0;
1145 unsigned max_blocks = bh_result->b_size >> inode->i_blkbits;
1146 int dio_credits;
1148 if (create && !handle) {
1149 /* Direct IO write... */
1150 if (max_blocks > DIO_MAX_BLOCKS)
1151 max_blocks = DIO_MAX_BLOCKS;
1152 dio_credits = ext4_chunk_trans_blocks(inode, max_blocks);
1153 handle = ext4_journal_start(inode, dio_credits);
1154 if (IS_ERR(handle)) {
1155 ret = PTR_ERR(handle);
1156 goto out;
1158 started = 1;
1161 ret = ext4_get_blocks_wrap(handle, inode, iblock,
1162 max_blocks, bh_result, create, 0, 0);
1163 if (ret > 0) {
1164 bh_result->b_size = (ret << inode->i_blkbits);
1165 ret = 0;
1167 if (started)
1168 ext4_journal_stop(handle);
1169 out:
1170 return ret;
1174 * `handle' can be NULL if create is zero
1176 struct buffer_head *ext4_getblk(handle_t *handle, struct inode *inode,
1177 ext4_lblk_t block, int create, int *errp)
1179 struct buffer_head dummy;
1180 int fatal = 0, err;
1182 J_ASSERT(handle != NULL || create == 0);
1184 dummy.b_state = 0;
1185 dummy.b_blocknr = -1000;
1186 buffer_trace_init(&dummy.b_history);
1187 err = ext4_get_blocks_wrap(handle, inode, block, 1,
1188 &dummy, create, 1, 0);
1190 * ext4_get_blocks_handle() returns number of blocks
1191 * mapped. 0 in case of a HOLE.
1193 if (err > 0) {
1194 if (err > 1)
1195 WARN_ON(1);
1196 err = 0;
1198 *errp = err;
1199 if (!err && buffer_mapped(&dummy)) {
1200 struct buffer_head *bh;
1201 bh = sb_getblk(inode->i_sb, dummy.b_blocknr);
1202 if (!bh) {
1203 *errp = -EIO;
1204 goto err;
1206 if (buffer_new(&dummy)) {
1207 J_ASSERT(create != 0);
1208 J_ASSERT(handle != NULL);
1211 * Now that we do not always journal data, we should
1212 * keep in mind whether this should always journal the
1213 * new buffer as metadata. For now, regular file
1214 * writes use ext4_get_block instead, so it's not a
1215 * problem.
1217 lock_buffer(bh);
1218 BUFFER_TRACE(bh, "call get_create_access");
1219 fatal = ext4_journal_get_create_access(handle, bh);
1220 if (!fatal && !buffer_uptodate(bh)) {
1221 memset(bh->b_data, 0, inode->i_sb->s_blocksize);
1222 set_buffer_uptodate(bh);
1224 unlock_buffer(bh);
1225 BUFFER_TRACE(bh, "call ext4_journal_dirty_metadata");
1226 err = ext4_journal_dirty_metadata(handle, bh);
1227 if (!fatal)
1228 fatal = err;
1229 } else {
1230 BUFFER_TRACE(bh, "not a new buffer");
1232 if (fatal) {
1233 *errp = fatal;
1234 brelse(bh);
1235 bh = NULL;
1237 return bh;
1239 err:
1240 return NULL;
1243 struct buffer_head *ext4_bread(handle_t *handle, struct inode *inode,
1244 ext4_lblk_t block, int create, int *err)
1246 struct buffer_head *bh;
1248 bh = ext4_getblk(handle, inode, block, create, err);
1249 if (!bh)
1250 return bh;
1251 if (buffer_uptodate(bh))
1252 return bh;
1253 ll_rw_block(READ_META, 1, &bh);
1254 wait_on_buffer(bh);
1255 if (buffer_uptodate(bh))
1256 return bh;
1257 put_bh(bh);
1258 *err = -EIO;
1259 return NULL;
1262 static int walk_page_buffers(handle_t *handle,
1263 struct buffer_head *head,
1264 unsigned from,
1265 unsigned to,
1266 int *partial,
1267 int (*fn)(handle_t *handle,
1268 struct buffer_head *bh))
1270 struct buffer_head *bh;
1271 unsigned block_start, block_end;
1272 unsigned blocksize = head->b_size;
1273 int err, ret = 0;
1274 struct buffer_head *next;
1276 for (bh = head, block_start = 0;
1277 ret == 0 && (bh != head || !block_start);
1278 block_start = block_end, bh = next)
1280 next = bh->b_this_page;
1281 block_end = block_start + blocksize;
1282 if (block_end <= from || block_start >= to) {
1283 if (partial && !buffer_uptodate(bh))
1284 *partial = 1;
1285 continue;
1287 err = (*fn)(handle, bh);
1288 if (!ret)
1289 ret = err;
1291 return ret;
1295 * To preserve ordering, it is essential that the hole instantiation and
1296 * the data write be encapsulated in a single transaction. We cannot
1297 * close off a transaction and start a new one between the ext4_get_block()
1298 * and the commit_write(). So doing the jbd2_journal_start at the start of
1299 * prepare_write() is the right place.
1301 * Also, this function can nest inside ext4_writepage() ->
1302 * block_write_full_page(). In that case, we *know* that ext4_writepage()
1303 * has generated enough buffer credits to do the whole page. So we won't
1304 * block on the journal in that case, which is good, because the caller may
1305 * be PF_MEMALLOC.
1307 * By accident, ext4 can be reentered when a transaction is open via
1308 * quota file writes. If we were to commit the transaction while thus
1309 * reentered, there can be a deadlock - we would be holding a quota
1310 * lock, and the commit would never complete if another thread had a
1311 * transaction open and was blocking on the quota lock - a ranking
1312 * violation.
1314 * So what we do is to rely on the fact that jbd2_journal_stop/journal_start
1315 * will _not_ run commit under these circumstances because handle->h_ref
1316 * is elevated. We'll still have enough credits for the tiny quotafile
1317 * write.
1319 static int do_journal_get_write_access(handle_t *handle,
1320 struct buffer_head *bh)
1322 if (!buffer_mapped(bh) || buffer_freed(bh))
1323 return 0;
1324 return ext4_journal_get_write_access(handle, bh);
1327 static int ext4_write_begin(struct file *file, struct address_space *mapping,
1328 loff_t pos, unsigned len, unsigned flags,
1329 struct page **pagep, void **fsdata)
1331 struct inode *inode = mapping->host;
1332 int ret, needed_blocks = ext4_writepage_trans_blocks(inode);
1333 handle_t *handle;
1334 int retries = 0;
1335 struct page *page;
1336 pgoff_t index;
1337 unsigned from, to;
1339 index = pos >> PAGE_CACHE_SHIFT;
1340 from = pos & (PAGE_CACHE_SIZE - 1);
1341 to = from + len;
1343 retry:
1344 handle = ext4_journal_start(inode, needed_blocks);
1345 if (IS_ERR(handle)) {
1346 ret = PTR_ERR(handle);
1347 goto out;
1350 /* We cannot recurse into the filesystem as the transaction is already
1351 * started */
1352 flags |= AOP_FLAG_NOFS;
1354 page = grab_cache_page_write_begin(mapping, index, flags);
1355 if (!page) {
1356 ext4_journal_stop(handle);
1357 ret = -ENOMEM;
1358 goto out;
1360 *pagep = page;
1362 ret = block_write_begin(file, mapping, pos, len, flags, pagep, fsdata,
1363 ext4_get_block);
1365 if (!ret && ext4_should_journal_data(inode)) {
1366 ret = walk_page_buffers(handle, page_buffers(page),
1367 from, to, NULL, do_journal_get_write_access);
1370 if (ret) {
1371 unlock_page(page);
1372 ext4_journal_stop(handle);
1373 page_cache_release(page);
1375 * block_write_begin may have instantiated a few blocks
1376 * outside i_size. Trim these off again. Don't need
1377 * i_size_read because we hold i_mutex.
1379 if (pos + len > inode->i_size)
1380 vmtruncate(inode, inode->i_size);
1383 if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
1384 goto retry;
1385 out:
1386 return ret;
1389 /* For write_end() in data=journal mode */
1390 static int write_end_fn(handle_t *handle, struct buffer_head *bh)
1392 if (!buffer_mapped(bh) || buffer_freed(bh))
1393 return 0;
1394 set_buffer_uptodate(bh);
1395 return ext4_journal_dirty_metadata(handle, bh);
1399 * We need to pick up the new inode size which generic_commit_write gave us
1400 * `file' can be NULL - eg, when called from page_symlink().
1402 * ext4 never places buffers on inode->i_mapping->private_list. metadata
1403 * buffers are managed internally.
1405 static int ext4_ordered_write_end(struct file *file,
1406 struct address_space *mapping,
1407 loff_t pos, unsigned len, unsigned copied,
1408 struct page *page, void *fsdata)
1410 handle_t *handle = ext4_journal_current_handle();
1411 struct inode *inode = mapping->host;
1412 int ret = 0, ret2;
1414 ret = ext4_jbd2_file_inode(handle, inode);
1416 if (ret == 0) {
1417 loff_t new_i_size;
1419 new_i_size = pos + copied;
1420 if (new_i_size > EXT4_I(inode)->i_disksize) {
1421 ext4_update_i_disksize(inode, new_i_size);
1422 /* We need to mark inode dirty even if
1423 * new_i_size is less that inode->i_size
1424 * bu greater than i_disksize.(hint delalloc)
1426 ext4_mark_inode_dirty(handle, inode);
1429 ret2 = generic_write_end(file, mapping, pos, len, copied,
1430 page, fsdata);
1431 copied = ret2;
1432 if (ret2 < 0)
1433 ret = ret2;
1435 ret2 = ext4_journal_stop(handle);
1436 if (!ret)
1437 ret = ret2;
1439 return ret ? ret : copied;
1442 static int ext4_writeback_write_end(struct file *file,
1443 struct address_space *mapping,
1444 loff_t pos, unsigned len, unsigned copied,
1445 struct page *page, void *fsdata)
1447 handle_t *handle = ext4_journal_current_handle();
1448 struct inode *inode = mapping->host;
1449 int ret = 0, ret2;
1450 loff_t new_i_size;
1452 new_i_size = pos + copied;
1453 if (new_i_size > EXT4_I(inode)->i_disksize) {
1454 ext4_update_i_disksize(inode, new_i_size);
1455 /* We need to mark inode dirty even if
1456 * new_i_size is less that inode->i_size
1457 * bu greater than i_disksize.(hint delalloc)
1459 ext4_mark_inode_dirty(handle, inode);
1462 ret2 = generic_write_end(file, mapping, pos, len, copied,
1463 page, fsdata);
1464 copied = ret2;
1465 if (ret2 < 0)
1466 ret = ret2;
1468 ret2 = ext4_journal_stop(handle);
1469 if (!ret)
1470 ret = ret2;
1472 return ret ? ret : copied;
1475 static int ext4_journalled_write_end(struct file *file,
1476 struct address_space *mapping,
1477 loff_t pos, unsigned len, unsigned copied,
1478 struct page *page, void *fsdata)
1480 handle_t *handle = ext4_journal_current_handle();
1481 struct inode *inode = mapping->host;
1482 int ret = 0, ret2;
1483 int partial = 0;
1484 unsigned from, to;
1485 loff_t new_i_size;
1487 from = pos & (PAGE_CACHE_SIZE - 1);
1488 to = from + len;
1490 if (copied < len) {
1491 if (!PageUptodate(page))
1492 copied = 0;
1493 page_zero_new_buffers(page, from+copied, to);
1496 ret = walk_page_buffers(handle, page_buffers(page), from,
1497 to, &partial, write_end_fn);
1498 if (!partial)
1499 SetPageUptodate(page);
1500 new_i_size = pos + copied;
1501 if (new_i_size > inode->i_size)
1502 i_size_write(inode, pos+copied);
1503 EXT4_I(inode)->i_state |= EXT4_STATE_JDATA;
1504 if (new_i_size > EXT4_I(inode)->i_disksize) {
1505 ext4_update_i_disksize(inode, new_i_size);
1506 ret2 = ext4_mark_inode_dirty(handle, inode);
1507 if (!ret)
1508 ret = ret2;
1511 unlock_page(page);
1512 ret2 = ext4_journal_stop(handle);
1513 if (!ret)
1514 ret = ret2;
1515 page_cache_release(page);
1517 return ret ? ret : copied;
1520 static int ext4_da_reserve_space(struct inode *inode, int nrblocks)
1522 int retries = 0;
1523 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1524 unsigned long md_needed, mdblocks, total = 0;
1527 * recalculate the amount of metadata blocks to reserve
1528 * in order to allocate nrblocks
1529 * worse case is one extent per block
1531 repeat:
1532 spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
1533 total = EXT4_I(inode)->i_reserved_data_blocks + nrblocks;
1534 mdblocks = ext4_calc_metadata_amount(inode, total);
1535 BUG_ON(mdblocks < EXT4_I(inode)->i_reserved_meta_blocks);
1537 md_needed = mdblocks - EXT4_I(inode)->i_reserved_meta_blocks;
1538 total = md_needed + nrblocks;
1540 if (ext4_claim_free_blocks(sbi, total)) {
1541 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
1542 if (ext4_should_retry_alloc(inode->i_sb, &retries)) {
1543 yield();
1544 goto repeat;
1546 return -ENOSPC;
1548 EXT4_I(inode)->i_reserved_data_blocks += nrblocks;
1549 EXT4_I(inode)->i_reserved_meta_blocks = mdblocks;
1551 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
1552 return 0; /* success */
1555 static void ext4_da_release_space(struct inode *inode, int to_free)
1557 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1558 int total, mdb, mdb_free, release;
1560 if (!to_free)
1561 return; /* Nothing to release, exit */
1563 spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
1565 if (!EXT4_I(inode)->i_reserved_data_blocks) {
1567 * if there is no reserved blocks, but we try to free some
1568 * then the counter is messed up somewhere.
1569 * but since this function is called from invalidate
1570 * page, it's harmless to return without any action
1572 printk(KERN_INFO "ext4 delalloc try to release %d reserved "
1573 "blocks for inode %lu, but there is no reserved "
1574 "data blocks\n", to_free, inode->i_ino);
1575 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
1576 return;
1579 /* recalculate the number of metablocks still need to be reserved */
1580 total = EXT4_I(inode)->i_reserved_data_blocks - to_free;
1581 mdb = ext4_calc_metadata_amount(inode, total);
1583 /* figure out how many metablocks to release */
1584 BUG_ON(mdb > EXT4_I(inode)->i_reserved_meta_blocks);
1585 mdb_free = EXT4_I(inode)->i_reserved_meta_blocks - mdb;
1587 release = to_free + mdb_free;
1589 /* update fs dirty blocks counter for truncate case */
1590 percpu_counter_sub(&sbi->s_dirtyblocks_counter, release);
1592 /* update per-inode reservations */
1593 BUG_ON(to_free > EXT4_I(inode)->i_reserved_data_blocks);
1594 EXT4_I(inode)->i_reserved_data_blocks -= to_free;
1596 BUG_ON(mdb > EXT4_I(inode)->i_reserved_meta_blocks);
1597 EXT4_I(inode)->i_reserved_meta_blocks = mdb;
1598 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
1601 static void ext4_da_page_release_reservation(struct page *page,
1602 unsigned long offset)
1604 int to_release = 0;
1605 struct buffer_head *head, *bh;
1606 unsigned int curr_off = 0;
1608 head = page_buffers(page);
1609 bh = head;
1610 do {
1611 unsigned int next_off = curr_off + bh->b_size;
1613 if ((offset <= curr_off) && (buffer_delay(bh))) {
1614 to_release++;
1615 clear_buffer_delay(bh);
1617 curr_off = next_off;
1618 } while ((bh = bh->b_this_page) != head);
1619 ext4_da_release_space(page->mapping->host, to_release);
1623 * Delayed allocation stuff
1626 struct mpage_da_data {
1627 struct inode *inode;
1628 struct buffer_head lbh; /* extent of blocks */
1629 unsigned long first_page, next_page; /* extent of pages */
1630 get_block_t *get_block;
1631 struct writeback_control *wbc;
1632 int io_done;
1633 long pages_written;
1634 int retval;
1638 * mpage_da_submit_io - walks through extent of pages and try to write
1639 * them with writepage() call back
1641 * @mpd->inode: inode
1642 * @mpd->first_page: first page of the extent
1643 * @mpd->next_page: page after the last page of the extent
1644 * @mpd->get_block: the filesystem's block mapper function
1646 * By the time mpage_da_submit_io() is called we expect all blocks
1647 * to be allocated. this may be wrong if allocation failed.
1649 * As pages are already locked by write_cache_pages(), we can't use it
1651 static int mpage_da_submit_io(struct mpage_da_data *mpd)
1653 long pages_skipped;
1654 struct pagevec pvec;
1655 unsigned long index, end;
1656 int ret = 0, err, nr_pages, i;
1657 struct inode *inode = mpd->inode;
1658 struct address_space *mapping = inode->i_mapping;
1660 BUG_ON(mpd->next_page <= mpd->first_page);
1662 * We need to start from the first_page to the next_page - 1
1663 * to make sure we also write the mapped dirty buffer_heads.
1664 * If we look at mpd->lbh.b_blocknr we would only be looking
1665 * at the currently mapped buffer_heads.
1667 index = mpd->first_page;
1668 end = mpd->next_page - 1;
1670 pagevec_init(&pvec, 0);
1671 while (index <= end) {
1672 nr_pages = pagevec_lookup(&pvec, mapping, index, PAGEVEC_SIZE);
1673 if (nr_pages == 0)
1674 break;
1675 for (i = 0; i < nr_pages; i++) {
1676 struct page *page = pvec.pages[i];
1678 index = page->index;
1679 if (index > end)
1680 break;
1681 index++;
1683 BUG_ON(!PageLocked(page));
1684 BUG_ON(PageWriteback(page));
1686 pages_skipped = mpd->wbc->pages_skipped;
1687 err = mapping->a_ops->writepage(page, mpd->wbc);
1688 if (!err && (pages_skipped == mpd->wbc->pages_skipped))
1690 * have successfully written the page
1691 * without skipping the same
1693 mpd->pages_written++;
1695 * In error case, we have to continue because
1696 * remaining pages are still locked
1697 * XXX: unlock and re-dirty them?
1699 if (ret == 0)
1700 ret = err;
1702 pagevec_release(&pvec);
1704 return ret;
1708 * mpage_put_bnr_to_bhs - walk blocks and assign them actual numbers
1710 * @mpd->inode - inode to walk through
1711 * @exbh->b_blocknr - first block on a disk
1712 * @exbh->b_size - amount of space in bytes
1713 * @logical - first logical block to start assignment with
1715 * the function goes through all passed space and put actual disk
1716 * block numbers into buffer heads, dropping BH_Delay
1718 static void mpage_put_bnr_to_bhs(struct mpage_da_data *mpd, sector_t logical,
1719 struct buffer_head *exbh)
1721 struct inode *inode = mpd->inode;
1722 struct address_space *mapping = inode->i_mapping;
1723 int blocks = exbh->b_size >> inode->i_blkbits;
1724 sector_t pblock = exbh->b_blocknr, cur_logical;
1725 struct buffer_head *head, *bh;
1726 pgoff_t index, end;
1727 struct pagevec pvec;
1728 int nr_pages, i;
1730 index = logical >> (PAGE_CACHE_SHIFT - inode->i_blkbits);
1731 end = (logical + blocks - 1) >> (PAGE_CACHE_SHIFT - inode->i_blkbits);
1732 cur_logical = index << (PAGE_CACHE_SHIFT - inode->i_blkbits);
1734 pagevec_init(&pvec, 0);
1736 while (index <= end) {
1737 /* XXX: optimize tail */
1738 nr_pages = pagevec_lookup(&pvec, mapping, index, PAGEVEC_SIZE);
1739 if (nr_pages == 0)
1740 break;
1741 for (i = 0; i < nr_pages; i++) {
1742 struct page *page = pvec.pages[i];
1744 index = page->index;
1745 if (index > end)
1746 break;
1747 index++;
1749 BUG_ON(!PageLocked(page));
1750 BUG_ON(PageWriteback(page));
1751 BUG_ON(!page_has_buffers(page));
1753 bh = page_buffers(page);
1754 head = bh;
1756 /* skip blocks out of the range */
1757 do {
1758 if (cur_logical >= logical)
1759 break;
1760 cur_logical++;
1761 } while ((bh = bh->b_this_page) != head);
1763 do {
1764 if (cur_logical >= logical + blocks)
1765 break;
1766 if (buffer_delay(bh)) {
1767 bh->b_blocknr = pblock;
1768 clear_buffer_delay(bh);
1769 bh->b_bdev = inode->i_sb->s_bdev;
1770 } else if (buffer_unwritten(bh)) {
1771 bh->b_blocknr = pblock;
1772 clear_buffer_unwritten(bh);
1773 set_buffer_mapped(bh);
1774 set_buffer_new(bh);
1775 bh->b_bdev = inode->i_sb->s_bdev;
1776 } else if (buffer_mapped(bh))
1777 BUG_ON(bh->b_blocknr != pblock);
1779 cur_logical++;
1780 pblock++;
1781 } while ((bh = bh->b_this_page) != head);
1783 pagevec_release(&pvec);
1789 * __unmap_underlying_blocks - just a helper function to unmap
1790 * set of blocks described by @bh
1792 static inline void __unmap_underlying_blocks(struct inode *inode,
1793 struct buffer_head *bh)
1795 struct block_device *bdev = inode->i_sb->s_bdev;
1796 int blocks, i;
1798 blocks = bh->b_size >> inode->i_blkbits;
1799 for (i = 0; i < blocks; i++)
1800 unmap_underlying_metadata(bdev, bh->b_blocknr + i);
1803 static void ext4_da_block_invalidatepages(struct mpage_da_data *mpd,
1804 sector_t logical, long blk_cnt)
1806 int nr_pages, i;
1807 pgoff_t index, end;
1808 struct pagevec pvec;
1809 struct inode *inode = mpd->inode;
1810 struct address_space *mapping = inode->i_mapping;
1812 index = logical >> (PAGE_CACHE_SHIFT - inode->i_blkbits);
1813 end = (logical + blk_cnt - 1) >>
1814 (PAGE_CACHE_SHIFT - inode->i_blkbits);
1815 while (index <= end) {
1816 nr_pages = pagevec_lookup(&pvec, mapping, index, PAGEVEC_SIZE);
1817 if (nr_pages == 0)
1818 break;
1819 for (i = 0; i < nr_pages; i++) {
1820 struct page *page = pvec.pages[i];
1821 index = page->index;
1822 if (index > end)
1823 break;
1824 index++;
1826 BUG_ON(!PageLocked(page));
1827 BUG_ON(PageWriteback(page));
1828 block_invalidatepage(page, 0);
1829 ClearPageUptodate(page);
1830 unlock_page(page);
1833 return;
1836 static void ext4_print_free_blocks(struct inode *inode)
1838 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1839 printk(KERN_EMERG "Total free blocks count %lld\n",
1840 ext4_count_free_blocks(inode->i_sb));
1841 printk(KERN_EMERG "Free/Dirty block details\n");
1842 printk(KERN_EMERG "free_blocks=%lld\n",
1843 percpu_counter_sum(&sbi->s_freeblocks_counter));
1844 printk(KERN_EMERG "dirty_blocks=%lld\n",
1845 percpu_counter_sum(&sbi->s_dirtyblocks_counter));
1846 printk(KERN_EMERG "Block reservation details\n");
1847 printk(KERN_EMERG "i_reserved_data_blocks=%lu\n",
1848 EXT4_I(inode)->i_reserved_data_blocks);
1849 printk(KERN_EMERG "i_reserved_meta_blocks=%lu\n",
1850 EXT4_I(inode)->i_reserved_meta_blocks);
1851 return;
1855 * mpage_da_map_blocks - go through given space
1857 * @mpd->lbh - bh describing space
1858 * @mpd->get_block - the filesystem's block mapper function
1860 * The function skips space we know is already mapped to disk blocks.
1863 static int mpage_da_map_blocks(struct mpage_da_data *mpd)
1865 int err = 0;
1866 struct buffer_head new;
1867 struct buffer_head *lbh = &mpd->lbh;
1868 sector_t next;
1871 * We consider only non-mapped and non-allocated blocks
1873 if (buffer_mapped(lbh) && !buffer_delay(lbh))
1874 return 0;
1875 new.b_state = lbh->b_state;
1876 new.b_blocknr = 0;
1877 new.b_size = lbh->b_size;
1878 next = lbh->b_blocknr;
1880 * If we didn't accumulate anything
1881 * to write simply return
1883 if (!new.b_size)
1884 return 0;
1885 err = mpd->get_block(mpd->inode, next, &new, 1);
1886 if (err) {
1888 /* If get block returns with error
1889 * we simply return. Later writepage
1890 * will redirty the page and writepages
1891 * will find the dirty page again
1893 if (err == -EAGAIN)
1894 return 0;
1896 if (err == -ENOSPC &&
1897 ext4_count_free_blocks(mpd->inode->i_sb)) {
1898 mpd->retval = err;
1899 return 0;
1903 * get block failure will cause us
1904 * to loop in writepages. Because
1905 * a_ops->writepage won't be able to
1906 * make progress. The page will be redirtied
1907 * by writepage and writepages will again
1908 * try to write the same.
1910 printk(KERN_EMERG "%s block allocation failed for inode %lu "
1911 "at logical offset %llu with max blocks "
1912 "%zd with error %d\n",
1913 __func__, mpd->inode->i_ino,
1914 (unsigned long long)next,
1915 lbh->b_size >> mpd->inode->i_blkbits, err);
1916 printk(KERN_EMERG "This should not happen.!! "
1917 "Data will be lost\n");
1918 if (err == -ENOSPC) {
1919 ext4_print_free_blocks(mpd->inode);
1921 /* invlaidate all the pages */
1922 ext4_da_block_invalidatepages(mpd, next,
1923 lbh->b_size >> mpd->inode->i_blkbits);
1924 return err;
1926 BUG_ON(new.b_size == 0);
1928 if (buffer_new(&new))
1929 __unmap_underlying_blocks(mpd->inode, &new);
1932 * If blocks are delayed marked, we need to
1933 * put actual blocknr and drop delayed bit
1935 if (buffer_delay(lbh) || buffer_unwritten(lbh))
1936 mpage_put_bnr_to_bhs(mpd, next, &new);
1938 return 0;
1941 #define BH_FLAGS ((1 << BH_Uptodate) | (1 << BH_Mapped) | \
1942 (1 << BH_Delay) | (1 << BH_Unwritten))
1945 * mpage_add_bh_to_extent - try to add one more block to extent of blocks
1947 * @mpd->lbh - extent of blocks
1948 * @logical - logical number of the block in the file
1949 * @bh - bh of the block (used to access block's state)
1951 * the function is used to collect contig. blocks in same state
1953 static void mpage_add_bh_to_extent(struct mpage_da_data *mpd,
1954 sector_t logical, struct buffer_head *bh)
1956 sector_t next;
1957 size_t b_size = bh->b_size;
1958 struct buffer_head *lbh = &mpd->lbh;
1959 int nrblocks = lbh->b_size >> mpd->inode->i_blkbits;
1961 /* check if thereserved journal credits might overflow */
1962 if (!(EXT4_I(mpd->inode)->i_flags & EXT4_EXTENTS_FL)) {
1963 if (nrblocks >= EXT4_MAX_TRANS_DATA) {
1965 * With non-extent format we are limited by the journal
1966 * credit available. Total credit needed to insert
1967 * nrblocks contiguous blocks is dependent on the
1968 * nrblocks. So limit nrblocks.
1970 goto flush_it;
1971 } else if ((nrblocks + (b_size >> mpd->inode->i_blkbits)) >
1972 EXT4_MAX_TRANS_DATA) {
1974 * Adding the new buffer_head would make it cross the
1975 * allowed limit for which we have journal credit
1976 * reserved. So limit the new bh->b_size
1978 b_size = (EXT4_MAX_TRANS_DATA - nrblocks) <<
1979 mpd->inode->i_blkbits;
1980 /* we will do mpage_da_submit_io in the next loop */
1984 * First block in the extent
1986 if (lbh->b_size == 0) {
1987 lbh->b_blocknr = logical;
1988 lbh->b_size = b_size;
1989 lbh->b_state = bh->b_state & BH_FLAGS;
1990 return;
1993 next = lbh->b_blocknr + nrblocks;
1995 * Can we merge the block to our big extent?
1997 if (logical == next && (bh->b_state & BH_FLAGS) == lbh->b_state) {
1998 lbh->b_size += b_size;
1999 return;
2002 flush_it:
2004 * We couldn't merge the block to our extent, so we
2005 * need to flush current extent and start new one
2007 if (mpage_da_map_blocks(mpd) == 0)
2008 mpage_da_submit_io(mpd);
2009 mpd->io_done = 1;
2010 return;
2014 * __mpage_da_writepage - finds extent of pages and blocks
2016 * @page: page to consider
2017 * @wbc: not used, we just follow rules
2018 * @data: context
2020 * The function finds extents of pages and scan them for all blocks.
2022 static int __mpage_da_writepage(struct page *page,
2023 struct writeback_control *wbc, void *data)
2025 struct mpage_da_data *mpd = data;
2026 struct inode *inode = mpd->inode;
2027 struct buffer_head *bh, *head, fake;
2028 sector_t logical;
2030 if (mpd->io_done) {
2032 * Rest of the page in the page_vec
2033 * redirty then and skip then. We will
2034 * try to to write them again after
2035 * starting a new transaction
2037 redirty_page_for_writepage(wbc, page);
2038 unlock_page(page);
2039 return MPAGE_DA_EXTENT_TAIL;
2042 * Can we merge this page to current extent?
2044 if (mpd->next_page != page->index) {
2046 * Nope, we can't. So, we map non-allocated blocks
2047 * and start IO on them using writepage()
2049 if (mpd->next_page != mpd->first_page) {
2050 if (mpage_da_map_blocks(mpd) == 0)
2051 mpage_da_submit_io(mpd);
2053 * skip rest of the page in the page_vec
2055 mpd->io_done = 1;
2056 redirty_page_for_writepage(wbc, page);
2057 unlock_page(page);
2058 return MPAGE_DA_EXTENT_TAIL;
2062 * Start next extent of pages ...
2064 mpd->first_page = page->index;
2067 * ... and blocks
2069 mpd->lbh.b_size = 0;
2070 mpd->lbh.b_state = 0;
2071 mpd->lbh.b_blocknr = 0;
2074 mpd->next_page = page->index + 1;
2075 logical = (sector_t) page->index <<
2076 (PAGE_CACHE_SHIFT - inode->i_blkbits);
2078 if (!page_has_buffers(page)) {
2080 * There is no attached buffer heads yet (mmap?)
2081 * we treat the page asfull of dirty blocks
2083 bh = &fake;
2084 bh->b_size = PAGE_CACHE_SIZE;
2085 bh->b_state = 0;
2086 set_buffer_dirty(bh);
2087 set_buffer_uptodate(bh);
2088 mpage_add_bh_to_extent(mpd, logical, bh);
2089 if (mpd->io_done)
2090 return MPAGE_DA_EXTENT_TAIL;
2091 } else {
2093 * Page with regular buffer heads, just add all dirty ones
2095 head = page_buffers(page);
2096 bh = head;
2097 do {
2098 BUG_ON(buffer_locked(bh));
2100 * We need to try to allocate
2101 * unmapped blocks in the same page.
2102 * Otherwise we won't make progress
2103 * with the page in ext4_da_writepage
2105 if (buffer_dirty(bh) &&
2106 (!buffer_mapped(bh) || buffer_delay(bh))) {
2107 mpage_add_bh_to_extent(mpd, logical, bh);
2108 if (mpd->io_done)
2109 return MPAGE_DA_EXTENT_TAIL;
2110 } else if (buffer_dirty(bh) && (buffer_mapped(bh))) {
2112 * mapped dirty buffer. We need to update
2113 * the b_state because we look at
2114 * b_state in mpage_da_map_blocks. We don't
2115 * update b_size because if we find an
2116 * unmapped buffer_head later we need to
2117 * use the b_state flag of that buffer_head.
2119 if (mpd->lbh.b_size == 0)
2120 mpd->lbh.b_state =
2121 bh->b_state & BH_FLAGS;
2123 logical++;
2124 } while ((bh = bh->b_this_page) != head);
2127 return 0;
2131 * mpage_da_writepages - walk the list of dirty pages of the given
2132 * address space, allocates non-allocated blocks, maps newly-allocated
2133 * blocks to existing bhs and issue IO them
2135 * @mapping: address space structure to write
2136 * @wbc: subtract the number of written pages from *@wbc->nr_to_write
2137 * @get_block: the filesystem's block mapper function.
2139 * This is a library function, which implements the writepages()
2140 * address_space_operation.
2142 static int mpage_da_writepages(struct address_space *mapping,
2143 struct writeback_control *wbc,
2144 struct mpage_da_data *mpd)
2146 int ret;
2148 if (!mpd->get_block)
2149 return generic_writepages(mapping, wbc);
2151 mpd->lbh.b_size = 0;
2152 mpd->lbh.b_state = 0;
2153 mpd->lbh.b_blocknr = 0;
2154 mpd->first_page = 0;
2155 mpd->next_page = 0;
2156 mpd->io_done = 0;
2157 mpd->pages_written = 0;
2158 mpd->retval = 0;
2160 ret = write_cache_pages(mapping, wbc, __mpage_da_writepage, mpd);
2162 * Handle last extent of pages
2164 if (!mpd->io_done && mpd->next_page != mpd->first_page) {
2165 if (mpage_da_map_blocks(mpd) == 0)
2166 mpage_da_submit_io(mpd);
2168 mpd->io_done = 1;
2169 ret = MPAGE_DA_EXTENT_TAIL;
2171 wbc->nr_to_write -= mpd->pages_written;
2172 return ret;
2176 * this is a special callback for ->write_begin() only
2177 * it's intention is to return mapped block or reserve space
2179 static int ext4_da_get_block_prep(struct inode *inode, sector_t iblock,
2180 struct buffer_head *bh_result, int create)
2182 int ret = 0;
2184 BUG_ON(create == 0);
2185 BUG_ON(bh_result->b_size != inode->i_sb->s_blocksize);
2188 * first, we need to know whether the block is allocated already
2189 * preallocated blocks are unmapped but should treated
2190 * the same as allocated blocks.
2192 ret = ext4_get_blocks_wrap(NULL, inode, iblock, 1, bh_result, 0, 0, 0);
2193 if ((ret == 0) && !buffer_delay(bh_result)) {
2194 /* the block isn't (pre)allocated yet, let's reserve space */
2196 * XXX: __block_prepare_write() unmaps passed block,
2197 * is it OK?
2199 ret = ext4_da_reserve_space(inode, 1);
2200 if (ret)
2201 /* not enough space to reserve */
2202 return ret;
2204 map_bh(bh_result, inode->i_sb, 0);
2205 set_buffer_new(bh_result);
2206 set_buffer_delay(bh_result);
2207 } else if (ret > 0) {
2208 bh_result->b_size = (ret << inode->i_blkbits);
2209 ret = 0;
2212 return ret;
2214 #define EXT4_DELALLOC_RSVED 1
2215 static int ext4_da_get_block_write(struct inode *inode, sector_t iblock,
2216 struct buffer_head *bh_result, int create)
2218 int ret;
2219 unsigned max_blocks = bh_result->b_size >> inode->i_blkbits;
2220 loff_t disksize = EXT4_I(inode)->i_disksize;
2221 handle_t *handle = NULL;
2223 handle = ext4_journal_current_handle();
2224 BUG_ON(!handle);
2225 ret = ext4_get_blocks_wrap(handle, inode, iblock, max_blocks,
2226 bh_result, create, 0, EXT4_DELALLOC_RSVED);
2227 if (ret > 0) {
2229 bh_result->b_size = (ret << inode->i_blkbits);
2231 if (ext4_should_order_data(inode)) {
2232 int retval;
2233 retval = ext4_jbd2_file_inode(handle, inode);
2234 if (retval)
2236 * Failed to add inode for ordered
2237 * mode. Don't update file size
2239 return retval;
2243 * Update on-disk size along with block allocation
2244 * we don't use 'extend_disksize' as size may change
2245 * within already allocated block -bzzz
2247 disksize = ((loff_t) iblock + ret) << inode->i_blkbits;
2248 if (disksize > i_size_read(inode))
2249 disksize = i_size_read(inode);
2250 if (disksize > EXT4_I(inode)->i_disksize) {
2251 ext4_update_i_disksize(inode, disksize);
2252 ret = ext4_mark_inode_dirty(handle, inode);
2253 return ret;
2255 ret = 0;
2257 return ret;
2260 static int ext4_bh_unmapped_or_delay(handle_t *handle, struct buffer_head *bh)
2263 * unmapped buffer is possible for holes.
2264 * delay buffer is possible with delayed allocation
2266 return ((!buffer_mapped(bh) || buffer_delay(bh)) && buffer_dirty(bh));
2269 static int ext4_normal_get_block_write(struct inode *inode, sector_t iblock,
2270 struct buffer_head *bh_result, int create)
2272 int ret = 0;
2273 unsigned max_blocks = bh_result->b_size >> inode->i_blkbits;
2276 * we don't want to do block allocation in writepage
2277 * so call get_block_wrap with create = 0
2279 ret = ext4_get_blocks_wrap(NULL, inode, iblock, max_blocks,
2280 bh_result, 0, 0, 0);
2281 if (ret > 0) {
2282 bh_result->b_size = (ret << inode->i_blkbits);
2283 ret = 0;
2285 return ret;
2289 * get called vi ext4_da_writepages after taking page lock (have journal handle)
2290 * get called via journal_submit_inode_data_buffers (no journal handle)
2291 * get called via shrink_page_list via pdflush (no journal handle)
2292 * or grab_page_cache when doing write_begin (have journal handle)
2294 static int ext4_da_writepage(struct page *page,
2295 struct writeback_control *wbc)
2297 int ret = 0;
2298 loff_t size;
2299 unsigned long len;
2300 struct buffer_head *page_bufs;
2301 struct inode *inode = page->mapping->host;
2303 size = i_size_read(inode);
2304 if (page->index == size >> PAGE_CACHE_SHIFT)
2305 len = size & ~PAGE_CACHE_MASK;
2306 else
2307 len = PAGE_CACHE_SIZE;
2309 if (page_has_buffers(page)) {
2310 page_bufs = page_buffers(page);
2311 if (walk_page_buffers(NULL, page_bufs, 0, len, NULL,
2312 ext4_bh_unmapped_or_delay)) {
2314 * We don't want to do block allocation
2315 * So redirty the page and return
2316 * We may reach here when we do a journal commit
2317 * via journal_submit_inode_data_buffers.
2318 * If we don't have mapping block we just ignore
2319 * them. We can also reach here via shrink_page_list
2321 redirty_page_for_writepage(wbc, page);
2322 unlock_page(page);
2323 return 0;
2325 } else {
2327 * The test for page_has_buffers() is subtle:
2328 * We know the page is dirty but it lost buffers. That means
2329 * that at some moment in time after write_begin()/write_end()
2330 * has been called all buffers have been clean and thus they
2331 * must have been written at least once. So they are all
2332 * mapped and we can happily proceed with mapping them
2333 * and writing the page.
2335 * Try to initialize the buffer_heads and check whether
2336 * all are mapped and non delay. We don't want to
2337 * do block allocation here.
2339 ret = block_prepare_write(page, 0, PAGE_CACHE_SIZE,
2340 ext4_normal_get_block_write);
2341 if (!ret) {
2342 page_bufs = page_buffers(page);
2343 /* check whether all are mapped and non delay */
2344 if (walk_page_buffers(NULL, page_bufs, 0, len, NULL,
2345 ext4_bh_unmapped_or_delay)) {
2346 redirty_page_for_writepage(wbc, page);
2347 unlock_page(page);
2348 return 0;
2350 } else {
2352 * We can't do block allocation here
2353 * so just redity the page and unlock
2354 * and return
2356 redirty_page_for_writepage(wbc, page);
2357 unlock_page(page);
2358 return 0;
2360 /* now mark the buffer_heads as dirty and uptodate */
2361 block_commit_write(page, 0, PAGE_CACHE_SIZE);
2364 if (test_opt(inode->i_sb, NOBH) && ext4_should_writeback_data(inode))
2365 ret = nobh_writepage(page, ext4_normal_get_block_write, wbc);
2366 else
2367 ret = block_write_full_page(page,
2368 ext4_normal_get_block_write,
2369 wbc);
2371 return ret;
2375 * This is called via ext4_da_writepages() to
2376 * calulate the total number of credits to reserve to fit
2377 * a single extent allocation into a single transaction,
2378 * ext4_da_writpeages() will loop calling this before
2379 * the block allocation.
2382 static int ext4_da_writepages_trans_blocks(struct inode *inode)
2384 int max_blocks = EXT4_I(inode)->i_reserved_data_blocks;
2387 * With non-extent format the journal credit needed to
2388 * insert nrblocks contiguous block is dependent on
2389 * number of contiguous block. So we will limit
2390 * number of contiguous block to a sane value
2392 if (!(inode->i_flags & EXT4_EXTENTS_FL) &&
2393 (max_blocks > EXT4_MAX_TRANS_DATA))
2394 max_blocks = EXT4_MAX_TRANS_DATA;
2396 return ext4_chunk_trans_blocks(inode, max_blocks);
2399 static int ext4_da_writepages(struct address_space *mapping,
2400 struct writeback_control *wbc)
2402 pgoff_t index;
2403 int range_whole = 0;
2404 handle_t *handle = NULL;
2405 struct mpage_da_data mpd;
2406 struct inode *inode = mapping->host;
2407 int no_nrwrite_index_update;
2408 long pages_written = 0, pages_skipped;
2409 int range_cyclic, cycled = 1, io_done = 0;
2410 int needed_blocks, ret = 0, nr_to_writebump = 0;
2411 struct ext4_sb_info *sbi = EXT4_SB(mapping->host->i_sb);
2414 * No pages to write? This is mainly a kludge to avoid starting
2415 * a transaction for special inodes like journal inode on last iput()
2416 * because that could violate lock ordering on umount
2418 if (!mapping->nrpages || !mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
2419 return 0;
2422 * If the filesystem has aborted, it is read-only, so return
2423 * right away instead of dumping stack traces later on that
2424 * will obscure the real source of the problem. We test
2425 * EXT4_MOUNT_ABORT instead of sb->s_flag's MS_RDONLY because
2426 * the latter could be true if the filesystem is mounted
2427 * read-only, and in that case, ext4_da_writepages should
2428 * *never* be called, so if that ever happens, we would want
2429 * the stack trace.
2431 if (unlikely(sbi->s_mount_opt & EXT4_MOUNT_ABORT))
2432 return -EROFS;
2435 * Make sure nr_to_write is >= sbi->s_mb_stream_request
2436 * This make sure small files blocks are allocated in
2437 * single attempt. This ensure that small files
2438 * get less fragmented.
2440 if (wbc->nr_to_write < sbi->s_mb_stream_request) {
2441 nr_to_writebump = sbi->s_mb_stream_request - wbc->nr_to_write;
2442 wbc->nr_to_write = sbi->s_mb_stream_request;
2444 if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
2445 range_whole = 1;
2447 range_cyclic = wbc->range_cyclic;
2448 if (wbc->range_cyclic) {
2449 index = mapping->writeback_index;
2450 if (index)
2451 cycled = 0;
2452 wbc->range_start = index << PAGE_CACHE_SHIFT;
2453 wbc->range_end = LLONG_MAX;
2454 wbc->range_cyclic = 0;
2455 } else
2456 index = wbc->range_start >> PAGE_CACHE_SHIFT;
2458 mpd.wbc = wbc;
2459 mpd.inode = mapping->host;
2462 * we don't want write_cache_pages to update
2463 * nr_to_write and writeback_index
2465 no_nrwrite_index_update = wbc->no_nrwrite_index_update;
2466 wbc->no_nrwrite_index_update = 1;
2467 pages_skipped = wbc->pages_skipped;
2469 retry:
2470 while (!ret && wbc->nr_to_write > 0) {
2473 * we insert one extent at a time. So we need
2474 * credit needed for single extent allocation.
2475 * journalled mode is currently not supported
2476 * by delalloc
2478 BUG_ON(ext4_should_journal_data(inode));
2479 needed_blocks = ext4_da_writepages_trans_blocks(inode);
2481 /* start a new transaction*/
2482 handle = ext4_journal_start(inode, needed_blocks);
2483 if (IS_ERR(handle)) {
2484 ret = PTR_ERR(handle);
2485 printk(KERN_CRIT "%s: jbd2_start: "
2486 "%ld pages, ino %lu; err %d\n", __func__,
2487 wbc->nr_to_write, inode->i_ino, ret);
2488 dump_stack();
2489 goto out_writepages;
2491 mpd.get_block = ext4_da_get_block_write;
2492 ret = mpage_da_writepages(mapping, wbc, &mpd);
2494 ext4_journal_stop(handle);
2496 if (mpd.retval == -ENOSPC) {
2497 /* commit the transaction which would
2498 * free blocks released in the transaction
2499 * and try again
2501 jbd2_journal_force_commit_nested(sbi->s_journal);
2502 wbc->pages_skipped = pages_skipped;
2503 ret = 0;
2504 } else if (ret == MPAGE_DA_EXTENT_TAIL) {
2506 * got one extent now try with
2507 * rest of the pages
2509 pages_written += mpd.pages_written;
2510 wbc->pages_skipped = pages_skipped;
2511 ret = 0;
2512 io_done = 1;
2513 } else if (wbc->nr_to_write)
2515 * There is no more writeout needed
2516 * or we requested for a noblocking writeout
2517 * and we found the device congested
2519 break;
2521 if (!io_done && !cycled) {
2522 cycled = 1;
2523 index = 0;
2524 wbc->range_start = index << PAGE_CACHE_SHIFT;
2525 wbc->range_end = mapping->writeback_index - 1;
2526 goto retry;
2528 if (pages_skipped != wbc->pages_skipped)
2529 printk(KERN_EMERG "This should not happen leaving %s "
2530 "with nr_to_write = %ld ret = %d\n",
2531 __func__, wbc->nr_to_write, ret);
2533 /* Update index */
2534 index += pages_written;
2535 wbc->range_cyclic = range_cyclic;
2536 if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
2538 * set the writeback_index so that range_cyclic
2539 * mode will write it back later
2541 mapping->writeback_index = index;
2543 out_writepages:
2544 if (!no_nrwrite_index_update)
2545 wbc->no_nrwrite_index_update = 0;
2546 wbc->nr_to_write -= nr_to_writebump;
2547 return ret;
2550 #define FALL_BACK_TO_NONDELALLOC 1
2551 static int ext4_nonda_switch(struct super_block *sb)
2553 s64 free_blocks, dirty_blocks;
2554 struct ext4_sb_info *sbi = EXT4_SB(sb);
2557 * switch to non delalloc mode if we are running low
2558 * on free block. The free block accounting via percpu
2559 * counters can get slightly wrong with FBC_BATCH getting
2560 * accumulated on each CPU without updating global counters
2561 * Delalloc need an accurate free block accounting. So switch
2562 * to non delalloc when we are near to error range.
2564 free_blocks = percpu_counter_read_positive(&sbi->s_freeblocks_counter);
2565 dirty_blocks = percpu_counter_read_positive(&sbi->s_dirtyblocks_counter);
2566 if (2 * free_blocks < 3 * dirty_blocks ||
2567 free_blocks < (dirty_blocks + EXT4_FREEBLOCKS_WATERMARK)) {
2569 * free block count is less that 150% of dirty blocks
2570 * or free blocks is less that watermark
2572 return 1;
2574 return 0;
2577 static int ext4_da_write_begin(struct file *file, struct address_space *mapping,
2578 loff_t pos, unsigned len, unsigned flags,
2579 struct page **pagep, void **fsdata)
2581 int ret, retries = 0;
2582 struct page *page;
2583 pgoff_t index;
2584 unsigned from, to;
2585 struct inode *inode = mapping->host;
2586 handle_t *handle;
2588 index = pos >> PAGE_CACHE_SHIFT;
2589 from = pos & (PAGE_CACHE_SIZE - 1);
2590 to = from + len;
2592 if (ext4_nonda_switch(inode->i_sb)) {
2593 *fsdata = (void *)FALL_BACK_TO_NONDELALLOC;
2594 return ext4_write_begin(file, mapping, pos,
2595 len, flags, pagep, fsdata);
2597 *fsdata = (void *)0;
2598 retry:
2600 * With delayed allocation, we don't log the i_disksize update
2601 * if there is delayed block allocation. But we still need
2602 * to journalling the i_disksize update if writes to the end
2603 * of file which has an already mapped buffer.
2605 handle = ext4_journal_start(inode, 1);
2606 if (IS_ERR(handle)) {
2607 ret = PTR_ERR(handle);
2608 goto out;
2610 /* We cannot recurse into the filesystem as the transaction is already
2611 * started */
2612 flags |= AOP_FLAG_NOFS;
2614 page = grab_cache_page_write_begin(mapping, index, flags);
2615 if (!page) {
2616 ext4_journal_stop(handle);
2617 ret = -ENOMEM;
2618 goto out;
2620 *pagep = page;
2622 ret = block_write_begin(file, mapping, pos, len, flags, pagep, fsdata,
2623 ext4_da_get_block_prep);
2624 if (ret < 0) {
2625 unlock_page(page);
2626 ext4_journal_stop(handle);
2627 page_cache_release(page);
2629 * block_write_begin may have instantiated a few blocks
2630 * outside i_size. Trim these off again. Don't need
2631 * i_size_read because we hold i_mutex.
2633 if (pos + len > inode->i_size)
2634 vmtruncate(inode, inode->i_size);
2637 if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
2638 goto retry;
2639 out:
2640 return ret;
2644 * Check if we should update i_disksize
2645 * when write to the end of file but not require block allocation
2647 static int ext4_da_should_update_i_disksize(struct page *page,
2648 unsigned long offset)
2650 struct buffer_head *bh;
2651 struct inode *inode = page->mapping->host;
2652 unsigned int idx;
2653 int i;
2655 bh = page_buffers(page);
2656 idx = offset >> inode->i_blkbits;
2658 for (i = 0; i < idx; i++)
2659 bh = bh->b_this_page;
2661 if (!buffer_mapped(bh) || (buffer_delay(bh)))
2662 return 0;
2663 return 1;
2666 static int ext4_da_write_end(struct file *file,
2667 struct address_space *mapping,
2668 loff_t pos, unsigned len, unsigned copied,
2669 struct page *page, void *fsdata)
2671 struct inode *inode = mapping->host;
2672 int ret = 0, ret2;
2673 handle_t *handle = ext4_journal_current_handle();
2674 loff_t new_i_size;
2675 unsigned long start, end;
2676 int write_mode = (int)(unsigned long)fsdata;
2678 if (write_mode == FALL_BACK_TO_NONDELALLOC) {
2679 if (ext4_should_order_data(inode)) {
2680 return ext4_ordered_write_end(file, mapping, pos,
2681 len, copied, page, fsdata);
2682 } else if (ext4_should_writeback_data(inode)) {
2683 return ext4_writeback_write_end(file, mapping, pos,
2684 len, copied, page, fsdata);
2685 } else {
2686 BUG();
2690 start = pos & (PAGE_CACHE_SIZE - 1);
2691 end = start + copied - 1;
2694 * generic_write_end() will run mark_inode_dirty() if i_size
2695 * changes. So let's piggyback the i_disksize mark_inode_dirty
2696 * into that.
2699 new_i_size = pos + copied;
2700 if (new_i_size > EXT4_I(inode)->i_disksize) {
2701 if (ext4_da_should_update_i_disksize(page, end)) {
2702 down_write(&EXT4_I(inode)->i_data_sem);
2703 if (new_i_size > EXT4_I(inode)->i_disksize) {
2705 * Updating i_disksize when extending file
2706 * without needing block allocation
2708 if (ext4_should_order_data(inode))
2709 ret = ext4_jbd2_file_inode(handle,
2710 inode);
2712 EXT4_I(inode)->i_disksize = new_i_size;
2714 up_write(&EXT4_I(inode)->i_data_sem);
2715 /* We need to mark inode dirty even if
2716 * new_i_size is less that inode->i_size
2717 * bu greater than i_disksize.(hint delalloc)
2719 ext4_mark_inode_dirty(handle, inode);
2722 ret2 = generic_write_end(file, mapping, pos, len, copied,
2723 page, fsdata);
2724 copied = ret2;
2725 if (ret2 < 0)
2726 ret = ret2;
2727 ret2 = ext4_journal_stop(handle);
2728 if (!ret)
2729 ret = ret2;
2731 return ret ? ret : copied;
2734 static void ext4_da_invalidatepage(struct page *page, unsigned long offset)
2737 * Drop reserved blocks
2739 BUG_ON(!PageLocked(page));
2740 if (!page_has_buffers(page))
2741 goto out;
2743 ext4_da_page_release_reservation(page, offset);
2745 out:
2746 ext4_invalidatepage(page, offset);
2748 return;
2753 * bmap() is special. It gets used by applications such as lilo and by
2754 * the swapper to find the on-disk block of a specific piece of data.
2756 * Naturally, this is dangerous if the block concerned is still in the
2757 * journal. If somebody makes a swapfile on an ext4 data-journaling
2758 * filesystem and enables swap, then they may get a nasty shock when the
2759 * data getting swapped to that swapfile suddenly gets overwritten by
2760 * the original zero's written out previously to the journal and
2761 * awaiting writeback in the kernel's buffer cache.
2763 * So, if we see any bmap calls here on a modified, data-journaled file,
2764 * take extra steps to flush any blocks which might be in the cache.
2766 static sector_t ext4_bmap(struct address_space *mapping, sector_t block)
2768 struct inode *inode = mapping->host;
2769 journal_t *journal;
2770 int err;
2772 if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY) &&
2773 test_opt(inode->i_sb, DELALLOC)) {
2775 * With delalloc we want to sync the file
2776 * so that we can make sure we allocate
2777 * blocks for file
2779 filemap_write_and_wait(mapping);
2782 if (EXT4_I(inode)->i_state & EXT4_STATE_JDATA) {
2784 * This is a REALLY heavyweight approach, but the use of
2785 * bmap on dirty files is expected to be extremely rare:
2786 * only if we run lilo or swapon on a freshly made file
2787 * do we expect this to happen.
2789 * (bmap requires CAP_SYS_RAWIO so this does not
2790 * represent an unprivileged user DOS attack --- we'd be
2791 * in trouble if mortal users could trigger this path at
2792 * will.)
2794 * NB. EXT4_STATE_JDATA is not set on files other than
2795 * regular files. If somebody wants to bmap a directory
2796 * or symlink and gets confused because the buffer
2797 * hasn't yet been flushed to disk, they deserve
2798 * everything they get.
2801 EXT4_I(inode)->i_state &= ~EXT4_STATE_JDATA;
2802 journal = EXT4_JOURNAL(inode);
2803 jbd2_journal_lock_updates(journal);
2804 err = jbd2_journal_flush(journal);
2805 jbd2_journal_unlock_updates(journal);
2807 if (err)
2808 return 0;
2811 return generic_block_bmap(mapping, block, ext4_get_block);
2814 static int bget_one(handle_t *handle, struct buffer_head *bh)
2816 get_bh(bh);
2817 return 0;
2820 static int bput_one(handle_t *handle, struct buffer_head *bh)
2822 put_bh(bh);
2823 return 0;
2827 * Note that we don't need to start a transaction unless we're journaling data
2828 * because we should have holes filled from ext4_page_mkwrite(). We even don't
2829 * need to file the inode to the transaction's list in ordered mode because if
2830 * we are writing back data added by write(), the inode is already there and if
2831 * we are writing back data modified via mmap(), noone guarantees in which
2832 * transaction the data will hit the disk. In case we are journaling data, we
2833 * cannot start transaction directly because transaction start ranks above page
2834 * lock so we have to do some magic.
2836 * In all journaling modes block_write_full_page() will start the I/O.
2838 * Problem:
2840 * ext4_writepage() -> kmalloc() -> __alloc_pages() -> page_launder() ->
2841 * ext4_writepage()
2843 * Similar for:
2845 * ext4_file_write() -> generic_file_write() -> __alloc_pages() -> ...
2847 * Same applies to ext4_get_block(). We will deadlock on various things like
2848 * lock_journal and i_data_sem
2850 * Setting PF_MEMALLOC here doesn't work - too many internal memory
2851 * allocations fail.
2853 * 16May01: If we're reentered then journal_current_handle() will be
2854 * non-zero. We simply *return*.
2856 * 1 July 2001: @@@ FIXME:
2857 * In journalled data mode, a data buffer may be metadata against the
2858 * current transaction. But the same file is part of a shared mapping
2859 * and someone does a writepage() on it.
2861 * We will move the buffer onto the async_data list, but *after* it has
2862 * been dirtied. So there's a small window where we have dirty data on
2863 * BJ_Metadata.
2865 * Note that this only applies to the last partial page in the file. The
2866 * bit which block_write_full_page() uses prepare/commit for. (That's
2867 * broken code anyway: it's wrong for msync()).
2869 * It's a rare case: affects the final partial page, for journalled data
2870 * where the file is subject to bith write() and writepage() in the same
2871 * transction. To fix it we'll need a custom block_write_full_page().
2872 * We'll probably need that anyway for journalling writepage() output.
2874 * We don't honour synchronous mounts for writepage(). That would be
2875 * disastrous. Any write() or metadata operation will sync the fs for
2876 * us.
2879 static int __ext4_normal_writepage(struct page *page,
2880 struct writeback_control *wbc)
2882 struct inode *inode = page->mapping->host;
2884 if (test_opt(inode->i_sb, NOBH))
2885 return nobh_writepage(page,
2886 ext4_normal_get_block_write, wbc);
2887 else
2888 return block_write_full_page(page,
2889 ext4_normal_get_block_write,
2890 wbc);
2893 static int ext4_normal_writepage(struct page *page,
2894 struct writeback_control *wbc)
2896 struct inode *inode = page->mapping->host;
2897 loff_t size = i_size_read(inode);
2898 loff_t len;
2900 J_ASSERT(PageLocked(page));
2901 if (page->index == size >> PAGE_CACHE_SHIFT)
2902 len = size & ~PAGE_CACHE_MASK;
2903 else
2904 len = PAGE_CACHE_SIZE;
2906 if (page_has_buffers(page)) {
2907 /* if page has buffers it should all be mapped
2908 * and allocated. If there are not buffers attached
2909 * to the page we know the page is dirty but it lost
2910 * buffers. That means that at some moment in time
2911 * after write_begin() / write_end() has been called
2912 * all buffers have been clean and thus they must have been
2913 * written at least once. So they are all mapped and we can
2914 * happily proceed with mapping them and writing the page.
2916 BUG_ON(walk_page_buffers(NULL, page_buffers(page), 0, len, NULL,
2917 ext4_bh_unmapped_or_delay));
2920 if (!ext4_journal_current_handle())
2921 return __ext4_normal_writepage(page, wbc);
2923 redirty_page_for_writepage(wbc, page);
2924 unlock_page(page);
2925 return 0;
2928 static int __ext4_journalled_writepage(struct page *page,
2929 struct writeback_control *wbc)
2931 struct address_space *mapping = page->mapping;
2932 struct inode *inode = mapping->host;
2933 struct buffer_head *page_bufs;
2934 handle_t *handle = NULL;
2935 int ret = 0;
2936 int err;
2938 ret = block_prepare_write(page, 0, PAGE_CACHE_SIZE,
2939 ext4_normal_get_block_write);
2940 if (ret != 0)
2941 goto out_unlock;
2943 page_bufs = page_buffers(page);
2944 walk_page_buffers(handle, page_bufs, 0, PAGE_CACHE_SIZE, NULL,
2945 bget_one);
2946 /* As soon as we unlock the page, it can go away, but we have
2947 * references to buffers so we are safe */
2948 unlock_page(page);
2950 handle = ext4_journal_start(inode, ext4_writepage_trans_blocks(inode));
2951 if (IS_ERR(handle)) {
2952 ret = PTR_ERR(handle);
2953 goto out;
2956 ret = walk_page_buffers(handle, page_bufs, 0,
2957 PAGE_CACHE_SIZE, NULL, do_journal_get_write_access);
2959 err = walk_page_buffers(handle, page_bufs, 0,
2960 PAGE_CACHE_SIZE, NULL, write_end_fn);
2961 if (ret == 0)
2962 ret = err;
2963 err = ext4_journal_stop(handle);
2964 if (!ret)
2965 ret = err;
2967 walk_page_buffers(handle, page_bufs, 0,
2968 PAGE_CACHE_SIZE, NULL, bput_one);
2969 EXT4_I(inode)->i_state |= EXT4_STATE_JDATA;
2970 goto out;
2972 out_unlock:
2973 unlock_page(page);
2974 out:
2975 return ret;
2978 static int ext4_journalled_writepage(struct page *page,
2979 struct writeback_control *wbc)
2981 struct inode *inode = page->mapping->host;
2982 loff_t size = i_size_read(inode);
2983 loff_t len;
2985 J_ASSERT(PageLocked(page));
2986 if (page->index == size >> PAGE_CACHE_SHIFT)
2987 len = size & ~PAGE_CACHE_MASK;
2988 else
2989 len = PAGE_CACHE_SIZE;
2991 if (page_has_buffers(page)) {
2992 /* if page has buffers it should all be mapped
2993 * and allocated. If there are not buffers attached
2994 * to the page we know the page is dirty but it lost
2995 * buffers. That means that at some moment in time
2996 * after write_begin() / write_end() has been called
2997 * all buffers have been clean and thus they must have been
2998 * written at least once. So they are all mapped and we can
2999 * happily proceed with mapping them and writing the page.
3001 BUG_ON(walk_page_buffers(NULL, page_buffers(page), 0, len, NULL,
3002 ext4_bh_unmapped_or_delay));
3005 if (ext4_journal_current_handle())
3006 goto no_write;
3008 if (PageChecked(page)) {
3010 * It's mmapped pagecache. Add buffers and journal it. There
3011 * doesn't seem much point in redirtying the page here.
3013 ClearPageChecked(page);
3014 return __ext4_journalled_writepage(page, wbc);
3015 } else {
3017 * It may be a page full of checkpoint-mode buffers. We don't
3018 * really know unless we go poke around in the buffer_heads.
3019 * But block_write_full_page will do the right thing.
3021 return block_write_full_page(page,
3022 ext4_normal_get_block_write,
3023 wbc);
3025 no_write:
3026 redirty_page_for_writepage(wbc, page);
3027 unlock_page(page);
3028 return 0;
3031 static int ext4_readpage(struct file *file, struct page *page)
3033 return mpage_readpage(page, ext4_get_block);
3036 static int
3037 ext4_readpages(struct file *file, struct address_space *mapping,
3038 struct list_head *pages, unsigned nr_pages)
3040 return mpage_readpages(mapping, pages, nr_pages, ext4_get_block);
3043 static void ext4_invalidatepage(struct page *page, unsigned long offset)
3045 journal_t *journal = EXT4_JOURNAL(page->mapping->host);
3048 * If it's a full truncate we just forget about the pending dirtying
3050 if (offset == 0)
3051 ClearPageChecked(page);
3053 jbd2_journal_invalidatepage(journal, page, offset);
3056 static int ext4_releasepage(struct page *page, gfp_t wait)
3058 journal_t *journal = EXT4_JOURNAL(page->mapping->host);
3060 WARN_ON(PageChecked(page));
3061 if (!page_has_buffers(page))
3062 return 0;
3063 return jbd2_journal_try_to_free_buffers(journal, page, wait);
3067 * If the O_DIRECT write will extend the file then add this inode to the
3068 * orphan list. So recovery will truncate it back to the original size
3069 * if the machine crashes during the write.
3071 * If the O_DIRECT write is intantiating holes inside i_size and the machine
3072 * crashes then stale disk data _may_ be exposed inside the file. But current
3073 * VFS code falls back into buffered path in that case so we are safe.
3075 static ssize_t ext4_direct_IO(int rw, struct kiocb *iocb,
3076 const struct iovec *iov, loff_t offset,
3077 unsigned long nr_segs)
3079 struct file *file = iocb->ki_filp;
3080 struct inode *inode = file->f_mapping->host;
3081 struct ext4_inode_info *ei = EXT4_I(inode);
3082 handle_t *handle;
3083 ssize_t ret;
3084 int orphan = 0;
3085 size_t count = iov_length(iov, nr_segs);
3087 if (rw == WRITE) {
3088 loff_t final_size = offset + count;
3090 if (final_size > inode->i_size) {
3091 /* Credits for sb + inode write */
3092 handle = ext4_journal_start(inode, 2);
3093 if (IS_ERR(handle)) {
3094 ret = PTR_ERR(handle);
3095 goto out;
3097 ret = ext4_orphan_add(handle, inode);
3098 if (ret) {
3099 ext4_journal_stop(handle);
3100 goto out;
3102 orphan = 1;
3103 ei->i_disksize = inode->i_size;
3104 ext4_journal_stop(handle);
3108 ret = blockdev_direct_IO(rw, iocb, inode, inode->i_sb->s_bdev, iov,
3109 offset, nr_segs,
3110 ext4_get_block, NULL);
3112 if (orphan) {
3113 int err;
3115 /* Credits for sb + inode write */
3116 handle = ext4_journal_start(inode, 2);
3117 if (IS_ERR(handle)) {
3118 /* This is really bad luck. We've written the data
3119 * but cannot extend i_size. Bail out and pretend
3120 * the write failed... */
3121 ret = PTR_ERR(handle);
3122 goto out;
3124 if (inode->i_nlink)
3125 ext4_orphan_del(handle, inode);
3126 if (ret > 0) {
3127 loff_t end = offset + ret;
3128 if (end > inode->i_size) {
3129 ei->i_disksize = end;
3130 i_size_write(inode, end);
3132 * We're going to return a positive `ret'
3133 * here due to non-zero-length I/O, so there's
3134 * no way of reporting error returns from
3135 * ext4_mark_inode_dirty() to userspace. So
3136 * ignore it.
3138 ext4_mark_inode_dirty(handle, inode);
3141 err = ext4_journal_stop(handle);
3142 if (ret == 0)
3143 ret = err;
3145 out:
3146 return ret;
3150 * Pages can be marked dirty completely asynchronously from ext4's journalling
3151 * activity. By filemap_sync_pte(), try_to_unmap_one(), etc. We cannot do
3152 * much here because ->set_page_dirty is called under VFS locks. The page is
3153 * not necessarily locked.
3155 * We cannot just dirty the page and leave attached buffers clean, because the
3156 * buffers' dirty state is "definitive". We cannot just set the buffers dirty
3157 * or jbddirty because all the journalling code will explode.
3159 * So what we do is to mark the page "pending dirty" and next time writepage
3160 * is called, propagate that into the buffers appropriately.
3162 static int ext4_journalled_set_page_dirty(struct page *page)
3164 SetPageChecked(page);
3165 return __set_page_dirty_nobuffers(page);
3168 static const struct address_space_operations ext4_ordered_aops = {
3169 .readpage = ext4_readpage,
3170 .readpages = ext4_readpages,
3171 .writepage = ext4_normal_writepage,
3172 .sync_page = block_sync_page,
3173 .write_begin = ext4_write_begin,
3174 .write_end = ext4_ordered_write_end,
3175 .bmap = ext4_bmap,
3176 .invalidatepage = ext4_invalidatepage,
3177 .releasepage = ext4_releasepage,
3178 .direct_IO = ext4_direct_IO,
3179 .migratepage = buffer_migrate_page,
3180 .is_partially_uptodate = block_is_partially_uptodate,
3183 static const struct address_space_operations ext4_writeback_aops = {
3184 .readpage = ext4_readpage,
3185 .readpages = ext4_readpages,
3186 .writepage = ext4_normal_writepage,
3187 .sync_page = block_sync_page,
3188 .write_begin = ext4_write_begin,
3189 .write_end = ext4_writeback_write_end,
3190 .bmap = ext4_bmap,
3191 .invalidatepage = ext4_invalidatepage,
3192 .releasepage = ext4_releasepage,
3193 .direct_IO = ext4_direct_IO,
3194 .migratepage = buffer_migrate_page,
3195 .is_partially_uptodate = block_is_partially_uptodate,
3198 static const struct address_space_operations ext4_journalled_aops = {
3199 .readpage = ext4_readpage,
3200 .readpages = ext4_readpages,
3201 .writepage = ext4_journalled_writepage,
3202 .sync_page = block_sync_page,
3203 .write_begin = ext4_write_begin,
3204 .write_end = ext4_journalled_write_end,
3205 .set_page_dirty = ext4_journalled_set_page_dirty,
3206 .bmap = ext4_bmap,
3207 .invalidatepage = ext4_invalidatepage,
3208 .releasepage = ext4_releasepage,
3209 .is_partially_uptodate = block_is_partially_uptodate,
3212 static const struct address_space_operations ext4_da_aops = {
3213 .readpage = ext4_readpage,
3214 .readpages = ext4_readpages,
3215 .writepage = ext4_da_writepage,
3216 .writepages = ext4_da_writepages,
3217 .sync_page = block_sync_page,
3218 .write_begin = ext4_da_write_begin,
3219 .write_end = ext4_da_write_end,
3220 .bmap = ext4_bmap,
3221 .invalidatepage = ext4_da_invalidatepage,
3222 .releasepage = ext4_releasepage,
3223 .direct_IO = ext4_direct_IO,
3224 .migratepage = buffer_migrate_page,
3225 .is_partially_uptodate = block_is_partially_uptodate,
3228 void ext4_set_aops(struct inode *inode)
3230 if (ext4_should_order_data(inode) &&
3231 test_opt(inode->i_sb, DELALLOC))
3232 inode->i_mapping->a_ops = &ext4_da_aops;
3233 else if (ext4_should_order_data(inode))
3234 inode->i_mapping->a_ops = &ext4_ordered_aops;
3235 else if (ext4_should_writeback_data(inode) &&
3236 test_opt(inode->i_sb, DELALLOC))
3237 inode->i_mapping->a_ops = &ext4_da_aops;
3238 else if (ext4_should_writeback_data(inode))
3239 inode->i_mapping->a_ops = &ext4_writeback_aops;
3240 else
3241 inode->i_mapping->a_ops = &ext4_journalled_aops;
3245 * ext4_block_truncate_page() zeroes out a mapping from file offset `from'
3246 * up to the end of the block which corresponds to `from'.
3247 * This required during truncate. We need to physically zero the tail end
3248 * of that block so it doesn't yield old data if the file is later grown.
3250 int ext4_block_truncate_page(handle_t *handle,
3251 struct address_space *mapping, loff_t from)
3253 ext4_fsblk_t index = from >> PAGE_CACHE_SHIFT;
3254 unsigned offset = from & (PAGE_CACHE_SIZE-1);
3255 unsigned blocksize, length, pos;
3256 ext4_lblk_t iblock;
3257 struct inode *inode = mapping->host;
3258 struct buffer_head *bh;
3259 struct page *page;
3260 int err = 0;
3262 page = grab_cache_page(mapping, from >> PAGE_CACHE_SHIFT);
3263 if (!page)
3264 return -EINVAL;
3266 blocksize = inode->i_sb->s_blocksize;
3267 length = blocksize - (offset & (blocksize - 1));
3268 iblock = index << (PAGE_CACHE_SHIFT - inode->i_sb->s_blocksize_bits);
3271 * For "nobh" option, we can only work if we don't need to
3272 * read-in the page - otherwise we create buffers to do the IO.
3274 if (!page_has_buffers(page) && test_opt(inode->i_sb, NOBH) &&
3275 ext4_should_writeback_data(inode) && PageUptodate(page)) {
3276 zero_user(page, offset, length);
3277 set_page_dirty(page);
3278 goto unlock;
3281 if (!page_has_buffers(page))
3282 create_empty_buffers(page, blocksize, 0);
3284 /* Find the buffer that contains "offset" */
3285 bh = page_buffers(page);
3286 pos = blocksize;
3287 while (offset >= pos) {
3288 bh = bh->b_this_page;
3289 iblock++;
3290 pos += blocksize;
3293 err = 0;
3294 if (buffer_freed(bh)) {
3295 BUFFER_TRACE(bh, "freed: skip");
3296 goto unlock;
3299 if (!buffer_mapped(bh)) {
3300 BUFFER_TRACE(bh, "unmapped");
3301 ext4_get_block(inode, iblock, bh, 0);
3302 /* unmapped? It's a hole - nothing to do */
3303 if (!buffer_mapped(bh)) {
3304 BUFFER_TRACE(bh, "still unmapped");
3305 goto unlock;
3309 /* Ok, it's mapped. Make sure it's up-to-date */
3310 if (PageUptodate(page))
3311 set_buffer_uptodate(bh);
3313 if (!buffer_uptodate(bh)) {
3314 err = -EIO;
3315 ll_rw_block(READ, 1, &bh);
3316 wait_on_buffer(bh);
3317 /* Uhhuh. Read error. Complain and punt. */
3318 if (!buffer_uptodate(bh))
3319 goto unlock;
3322 if (ext4_should_journal_data(inode)) {
3323 BUFFER_TRACE(bh, "get write access");
3324 err = ext4_journal_get_write_access(handle, bh);
3325 if (err)
3326 goto unlock;
3329 zero_user(page, offset, length);
3331 BUFFER_TRACE(bh, "zeroed end of block");
3333 err = 0;
3334 if (ext4_should_journal_data(inode)) {
3335 err = ext4_journal_dirty_metadata(handle, bh);
3336 } else {
3337 if (ext4_should_order_data(inode))
3338 err = ext4_jbd2_file_inode(handle, inode);
3339 mark_buffer_dirty(bh);
3342 unlock:
3343 unlock_page(page);
3344 page_cache_release(page);
3345 return err;
3349 * Probably it should be a library function... search for first non-zero word
3350 * or memcmp with zero_page, whatever is better for particular architecture.
3351 * Linus?
3353 static inline int all_zeroes(__le32 *p, __le32 *q)
3355 while (p < q)
3356 if (*p++)
3357 return 0;
3358 return 1;
3362 * ext4_find_shared - find the indirect blocks for partial truncation.
3363 * @inode: inode in question
3364 * @depth: depth of the affected branch
3365 * @offsets: offsets of pointers in that branch (see ext4_block_to_path)
3366 * @chain: place to store the pointers to partial indirect blocks
3367 * @top: place to the (detached) top of branch
3369 * This is a helper function used by ext4_truncate().
3371 * When we do truncate() we may have to clean the ends of several
3372 * indirect blocks but leave the blocks themselves alive. Block is
3373 * partially truncated if some data below the new i_size is refered
3374 * from it (and it is on the path to the first completely truncated
3375 * data block, indeed). We have to free the top of that path along
3376 * with everything to the right of the path. Since no allocation
3377 * past the truncation point is possible until ext4_truncate()
3378 * finishes, we may safely do the latter, but top of branch may
3379 * require special attention - pageout below the truncation point
3380 * might try to populate it.
3382 * We atomically detach the top of branch from the tree, store the
3383 * block number of its root in *@top, pointers to buffer_heads of
3384 * partially truncated blocks - in @chain[].bh and pointers to
3385 * their last elements that should not be removed - in
3386 * @chain[].p. Return value is the pointer to last filled element
3387 * of @chain.
3389 * The work left to caller to do the actual freeing of subtrees:
3390 * a) free the subtree starting from *@top
3391 * b) free the subtrees whose roots are stored in
3392 * (@chain[i].p+1 .. end of @chain[i].bh->b_data)
3393 * c) free the subtrees growing from the inode past the @chain[0].
3394 * (no partially truncated stuff there). */
3396 static Indirect *ext4_find_shared(struct inode *inode, int depth,
3397 ext4_lblk_t offsets[4], Indirect chain[4], __le32 *top)
3399 Indirect *partial, *p;
3400 int k, err;
3402 *top = 0;
3403 /* Make k index the deepest non-null offest + 1 */
3404 for (k = depth; k > 1 && !offsets[k-1]; k--)
3406 partial = ext4_get_branch(inode, k, offsets, chain, &err);
3407 /* Writer: pointers */
3408 if (!partial)
3409 partial = chain + k-1;
3411 * If the branch acquired continuation since we've looked at it -
3412 * fine, it should all survive and (new) top doesn't belong to us.
3414 if (!partial->key && *partial->p)
3415 /* Writer: end */
3416 goto no_top;
3417 for (p = partial; (p > chain) && all_zeroes((__le32 *) p->bh->b_data, p->p); p--)
3420 * OK, we've found the last block that must survive. The rest of our
3421 * branch should be detached before unlocking. However, if that rest
3422 * of branch is all ours and does not grow immediately from the inode
3423 * it's easier to cheat and just decrement partial->p.
3425 if (p == chain + k - 1 && p > chain) {
3426 p->p--;
3427 } else {
3428 *top = *p->p;
3429 /* Nope, don't do this in ext4. Must leave the tree intact */
3430 #if 0
3431 *p->p = 0;
3432 #endif
3434 /* Writer: end */
3436 while (partial > p) {
3437 brelse(partial->bh);
3438 partial--;
3440 no_top:
3441 return partial;
3445 * Zero a number of block pointers in either an inode or an indirect block.
3446 * If we restart the transaction we must again get write access to the
3447 * indirect block for further modification.
3449 * We release `count' blocks on disk, but (last - first) may be greater
3450 * than `count' because there can be holes in there.
3452 static void ext4_clear_blocks(handle_t *handle, struct inode *inode,
3453 struct buffer_head *bh, ext4_fsblk_t block_to_free,
3454 unsigned long count, __le32 *first, __le32 *last)
3456 __le32 *p;
3457 if (try_to_extend_transaction(handle, inode)) {
3458 if (bh) {
3459 BUFFER_TRACE(bh, "call ext4_journal_dirty_metadata");
3460 ext4_journal_dirty_metadata(handle, bh);
3462 ext4_mark_inode_dirty(handle, inode);
3463 ext4_journal_test_restart(handle, inode);
3464 if (bh) {
3465 BUFFER_TRACE(bh, "retaking write access");
3466 ext4_journal_get_write_access(handle, bh);
3471 * Any buffers which are on the journal will be in memory. We find
3472 * them on the hash table so jbd2_journal_revoke() will run jbd2_journal_forget()
3473 * on them. We've already detached each block from the file, so
3474 * bforget() in jbd2_journal_forget() should be safe.
3476 * AKPM: turn on bforget in jbd2_journal_forget()!!!
3478 for (p = first; p < last; p++) {
3479 u32 nr = le32_to_cpu(*p);
3480 if (nr) {
3481 struct buffer_head *tbh;
3483 *p = 0;
3484 tbh = sb_find_get_block(inode->i_sb, nr);
3485 ext4_forget(handle, 0, inode, tbh, nr);
3489 ext4_free_blocks(handle, inode, block_to_free, count, 0);
3493 * ext4_free_data - free a list of data blocks
3494 * @handle: handle for this transaction
3495 * @inode: inode we are dealing with
3496 * @this_bh: indirect buffer_head which contains *@first and *@last
3497 * @first: array of block numbers
3498 * @last: points immediately past the end of array
3500 * We are freeing all blocks refered from that array (numbers are stored as
3501 * little-endian 32-bit) and updating @inode->i_blocks appropriately.
3503 * We accumulate contiguous runs of blocks to free. Conveniently, if these
3504 * blocks are contiguous then releasing them at one time will only affect one
3505 * or two bitmap blocks (+ group descriptor(s) and superblock) and we won't
3506 * actually use a lot of journal space.
3508 * @this_bh will be %NULL if @first and @last point into the inode's direct
3509 * block pointers.
3511 static void ext4_free_data(handle_t *handle, struct inode *inode,
3512 struct buffer_head *this_bh,
3513 __le32 *first, __le32 *last)
3515 ext4_fsblk_t block_to_free = 0; /* Starting block # of a run */
3516 unsigned long count = 0; /* Number of blocks in the run */
3517 __le32 *block_to_free_p = NULL; /* Pointer into inode/ind
3518 corresponding to
3519 block_to_free */
3520 ext4_fsblk_t nr; /* Current block # */
3521 __le32 *p; /* Pointer into inode/ind
3522 for current block */
3523 int err;
3525 if (this_bh) { /* For indirect block */
3526 BUFFER_TRACE(this_bh, "get_write_access");
3527 err = ext4_journal_get_write_access(handle, this_bh);
3528 /* Important: if we can't update the indirect pointers
3529 * to the blocks, we can't free them. */
3530 if (err)
3531 return;
3534 for (p = first; p < last; p++) {
3535 nr = le32_to_cpu(*p);
3536 if (nr) {
3537 /* accumulate blocks to free if they're contiguous */
3538 if (count == 0) {
3539 block_to_free = nr;
3540 block_to_free_p = p;
3541 count = 1;
3542 } else if (nr == block_to_free + count) {
3543 count++;
3544 } else {
3545 ext4_clear_blocks(handle, inode, this_bh,
3546 block_to_free,
3547 count, block_to_free_p, p);
3548 block_to_free = nr;
3549 block_to_free_p = p;
3550 count = 1;
3555 if (count > 0)
3556 ext4_clear_blocks(handle, inode, this_bh, block_to_free,
3557 count, block_to_free_p, p);
3559 if (this_bh) {
3560 BUFFER_TRACE(this_bh, "call ext4_journal_dirty_metadata");
3563 * The buffer head should have an attached journal head at this
3564 * point. However, if the data is corrupted and an indirect
3565 * block pointed to itself, it would have been detached when
3566 * the block was cleared. Check for this instead of OOPSing.
3568 if (bh2jh(this_bh))
3569 ext4_journal_dirty_metadata(handle, this_bh);
3570 else
3571 ext4_error(inode->i_sb, __func__,
3572 "circular indirect block detected, "
3573 "inode=%lu, block=%llu",
3574 inode->i_ino,
3575 (unsigned long long) this_bh->b_blocknr);
3580 * ext4_free_branches - free an array of branches
3581 * @handle: JBD handle for this transaction
3582 * @inode: inode we are dealing with
3583 * @parent_bh: the buffer_head which contains *@first and *@last
3584 * @first: array of block numbers
3585 * @last: pointer immediately past the end of array
3586 * @depth: depth of the branches to free
3588 * We are freeing all blocks refered from these branches (numbers are
3589 * stored as little-endian 32-bit) and updating @inode->i_blocks
3590 * appropriately.
3592 static void ext4_free_branches(handle_t *handle, struct inode *inode,
3593 struct buffer_head *parent_bh,
3594 __le32 *first, __le32 *last, int depth)
3596 ext4_fsblk_t nr;
3597 __le32 *p;
3599 if (is_handle_aborted(handle))
3600 return;
3602 if (depth--) {
3603 struct buffer_head *bh;
3604 int addr_per_block = EXT4_ADDR_PER_BLOCK(inode->i_sb);
3605 p = last;
3606 while (--p >= first) {
3607 nr = le32_to_cpu(*p);
3608 if (!nr)
3609 continue; /* A hole */
3611 /* Go read the buffer for the next level down */
3612 bh = sb_bread(inode->i_sb, nr);
3615 * A read failure? Report error and clear slot
3616 * (should be rare).
3618 if (!bh) {
3619 ext4_error(inode->i_sb, "ext4_free_branches",
3620 "Read failure, inode=%lu, block=%llu",
3621 inode->i_ino, nr);
3622 continue;
3625 /* This zaps the entire block. Bottom up. */
3626 BUFFER_TRACE(bh, "free child branches");
3627 ext4_free_branches(handle, inode, bh,
3628 (__le32 *) bh->b_data,
3629 (__le32 *) bh->b_data + addr_per_block,
3630 depth);
3633 * We've probably journalled the indirect block several
3634 * times during the truncate. But it's no longer
3635 * needed and we now drop it from the transaction via
3636 * jbd2_journal_revoke().
3638 * That's easy if it's exclusively part of this
3639 * transaction. But if it's part of the committing
3640 * transaction then jbd2_journal_forget() will simply
3641 * brelse() it. That means that if the underlying
3642 * block is reallocated in ext4_get_block(),
3643 * unmap_underlying_metadata() will find this block
3644 * and will try to get rid of it. damn, damn.
3646 * If this block has already been committed to the
3647 * journal, a revoke record will be written. And
3648 * revoke records must be emitted *before* clearing
3649 * this block's bit in the bitmaps.
3651 ext4_forget(handle, 1, inode, bh, bh->b_blocknr);
3654 * Everything below this this pointer has been
3655 * released. Now let this top-of-subtree go.
3657 * We want the freeing of this indirect block to be
3658 * atomic in the journal with the updating of the
3659 * bitmap block which owns it. So make some room in
3660 * the journal.
3662 * We zero the parent pointer *after* freeing its
3663 * pointee in the bitmaps, so if extend_transaction()
3664 * for some reason fails to put the bitmap changes and
3665 * the release into the same transaction, recovery
3666 * will merely complain about releasing a free block,
3667 * rather than leaking blocks.
3669 if (is_handle_aborted(handle))
3670 return;
3671 if (try_to_extend_transaction(handle, inode)) {
3672 ext4_mark_inode_dirty(handle, inode);
3673 ext4_journal_test_restart(handle, inode);
3676 ext4_free_blocks(handle, inode, nr, 1, 1);
3678 if (parent_bh) {
3680 * The block which we have just freed is
3681 * pointed to by an indirect block: journal it
3683 BUFFER_TRACE(parent_bh, "get_write_access");
3684 if (!ext4_journal_get_write_access(handle,
3685 parent_bh)){
3686 *p = 0;
3687 BUFFER_TRACE(parent_bh,
3688 "call ext4_journal_dirty_metadata");
3689 ext4_journal_dirty_metadata(handle,
3690 parent_bh);
3694 } else {
3695 /* We have reached the bottom of the tree. */
3696 BUFFER_TRACE(parent_bh, "free data blocks");
3697 ext4_free_data(handle, inode, parent_bh, first, last);
3701 int ext4_can_truncate(struct inode *inode)
3703 if (IS_APPEND(inode) || IS_IMMUTABLE(inode))
3704 return 0;
3705 if (S_ISREG(inode->i_mode))
3706 return 1;
3707 if (S_ISDIR(inode->i_mode))
3708 return 1;
3709 if (S_ISLNK(inode->i_mode))
3710 return !ext4_inode_is_fast_symlink(inode);
3711 return 0;
3715 * ext4_truncate()
3717 * We block out ext4_get_block() block instantiations across the entire
3718 * transaction, and VFS/VM ensures that ext4_truncate() cannot run
3719 * simultaneously on behalf of the same inode.
3721 * As we work through the truncate and commmit bits of it to the journal there
3722 * is one core, guiding principle: the file's tree must always be consistent on
3723 * disk. We must be able to restart the truncate after a crash.
3725 * The file's tree may be transiently inconsistent in memory (although it
3726 * probably isn't), but whenever we close off and commit a journal transaction,
3727 * the contents of (the filesystem + the journal) must be consistent and
3728 * restartable. It's pretty simple, really: bottom up, right to left (although
3729 * left-to-right works OK too).
3731 * Note that at recovery time, journal replay occurs *before* the restart of
3732 * truncate against the orphan inode list.
3734 * The committed inode has the new, desired i_size (which is the same as
3735 * i_disksize in this case). After a crash, ext4_orphan_cleanup() will see
3736 * that this inode's truncate did not complete and it will again call
3737 * ext4_truncate() to have another go. So there will be instantiated blocks
3738 * to the right of the truncation point in a crashed ext4 filesystem. But
3739 * that's fine - as long as they are linked from the inode, the post-crash
3740 * ext4_truncate() run will find them and release them.
3742 void ext4_truncate(struct inode *inode)
3744 handle_t *handle;
3745 struct ext4_inode_info *ei = EXT4_I(inode);
3746 __le32 *i_data = ei->i_data;
3747 int addr_per_block = EXT4_ADDR_PER_BLOCK(inode->i_sb);
3748 struct address_space *mapping = inode->i_mapping;
3749 ext4_lblk_t offsets[4];
3750 Indirect chain[4];
3751 Indirect *partial;
3752 __le32 nr = 0;
3753 int n;
3754 ext4_lblk_t last_block;
3755 unsigned blocksize = inode->i_sb->s_blocksize;
3757 if (!ext4_can_truncate(inode))
3758 return;
3760 if (EXT4_I(inode)->i_flags & EXT4_EXTENTS_FL) {
3761 ext4_ext_truncate(inode);
3762 return;
3765 handle = start_transaction(inode);
3766 if (IS_ERR(handle))
3767 return; /* AKPM: return what? */
3769 last_block = (inode->i_size + blocksize-1)
3770 >> EXT4_BLOCK_SIZE_BITS(inode->i_sb);
3772 if (inode->i_size & (blocksize - 1))
3773 if (ext4_block_truncate_page(handle, mapping, inode->i_size))
3774 goto out_stop;
3776 n = ext4_block_to_path(inode, last_block, offsets, NULL);
3777 if (n == 0)
3778 goto out_stop; /* error */
3781 * OK. This truncate is going to happen. We add the inode to the
3782 * orphan list, so that if this truncate spans multiple transactions,
3783 * and we crash, we will resume the truncate when the filesystem
3784 * recovers. It also marks the inode dirty, to catch the new size.
3786 * Implication: the file must always be in a sane, consistent
3787 * truncatable state while each transaction commits.
3789 if (ext4_orphan_add(handle, inode))
3790 goto out_stop;
3793 * From here we block out all ext4_get_block() callers who want to
3794 * modify the block allocation tree.
3796 down_write(&ei->i_data_sem);
3798 ext4_discard_preallocations(inode);
3801 * The orphan list entry will now protect us from any crash which
3802 * occurs before the truncate completes, so it is now safe to propagate
3803 * the new, shorter inode size (held for now in i_size) into the
3804 * on-disk inode. We do this via i_disksize, which is the value which
3805 * ext4 *really* writes onto the disk inode.
3807 ei->i_disksize = inode->i_size;
3809 if (n == 1) { /* direct blocks */
3810 ext4_free_data(handle, inode, NULL, i_data+offsets[0],
3811 i_data + EXT4_NDIR_BLOCKS);
3812 goto do_indirects;
3815 partial = ext4_find_shared(inode, n, offsets, chain, &nr);
3816 /* Kill the top of shared branch (not detached) */
3817 if (nr) {
3818 if (partial == chain) {
3819 /* Shared branch grows from the inode */
3820 ext4_free_branches(handle, inode, NULL,
3821 &nr, &nr+1, (chain+n-1) - partial);
3822 *partial->p = 0;
3824 * We mark the inode dirty prior to restart,
3825 * and prior to stop. No need for it here.
3827 } else {
3828 /* Shared branch grows from an indirect block */
3829 BUFFER_TRACE(partial->bh, "get_write_access");
3830 ext4_free_branches(handle, inode, partial->bh,
3831 partial->p,
3832 partial->p+1, (chain+n-1) - partial);
3835 /* Clear the ends of indirect blocks on the shared branch */
3836 while (partial > chain) {
3837 ext4_free_branches(handle, inode, partial->bh, partial->p + 1,
3838 (__le32*)partial->bh->b_data+addr_per_block,
3839 (chain+n-1) - partial);
3840 BUFFER_TRACE(partial->bh, "call brelse");
3841 brelse (partial->bh);
3842 partial--;
3844 do_indirects:
3845 /* Kill the remaining (whole) subtrees */
3846 switch (offsets[0]) {
3847 default:
3848 nr = i_data[EXT4_IND_BLOCK];
3849 if (nr) {
3850 ext4_free_branches(handle, inode, NULL, &nr, &nr+1, 1);
3851 i_data[EXT4_IND_BLOCK] = 0;
3853 case EXT4_IND_BLOCK:
3854 nr = i_data[EXT4_DIND_BLOCK];
3855 if (nr) {
3856 ext4_free_branches(handle, inode, NULL, &nr, &nr+1, 2);
3857 i_data[EXT4_DIND_BLOCK] = 0;
3859 case EXT4_DIND_BLOCK:
3860 nr = i_data[EXT4_TIND_BLOCK];
3861 if (nr) {
3862 ext4_free_branches(handle, inode, NULL, &nr, &nr+1, 3);
3863 i_data[EXT4_TIND_BLOCK] = 0;
3865 case EXT4_TIND_BLOCK:
3869 up_write(&ei->i_data_sem);
3870 inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
3871 ext4_mark_inode_dirty(handle, inode);
3874 * In a multi-transaction truncate, we only make the final transaction
3875 * synchronous
3877 if (IS_SYNC(inode))
3878 handle->h_sync = 1;
3879 out_stop:
3881 * If this was a simple ftruncate(), and the file will remain alive
3882 * then we need to clear up the orphan record which we created above.
3883 * However, if this was a real unlink then we were called by
3884 * ext4_delete_inode(), and we allow that function to clean up the
3885 * orphan info for us.
3887 if (inode->i_nlink)
3888 ext4_orphan_del(handle, inode);
3890 ext4_journal_stop(handle);
3894 * ext4_get_inode_loc returns with an extra refcount against the inode's
3895 * underlying buffer_head on success. If 'in_mem' is true, we have all
3896 * data in memory that is needed to recreate the on-disk version of this
3897 * inode.
3899 static int __ext4_get_inode_loc(struct inode *inode,
3900 struct ext4_iloc *iloc, int in_mem)
3902 struct ext4_group_desc *gdp;
3903 struct buffer_head *bh;
3904 struct super_block *sb = inode->i_sb;
3905 ext4_fsblk_t block;
3906 int inodes_per_block, inode_offset;
3908 iloc->bh = 0;
3909 if (!ext4_valid_inum(sb, inode->i_ino))
3910 return -EIO;
3912 iloc->block_group = (inode->i_ino - 1) / EXT4_INODES_PER_GROUP(sb);
3913 gdp = ext4_get_group_desc(sb, iloc->block_group, NULL);
3914 if (!gdp)
3915 return -EIO;
3918 * Figure out the offset within the block group inode table
3920 inodes_per_block = (EXT4_BLOCK_SIZE(sb) / EXT4_INODE_SIZE(sb));
3921 inode_offset = ((inode->i_ino - 1) %
3922 EXT4_INODES_PER_GROUP(sb));
3923 block = ext4_inode_table(sb, gdp) + (inode_offset / inodes_per_block);
3924 iloc->offset = (inode_offset % inodes_per_block) * EXT4_INODE_SIZE(sb);
3926 bh = sb_getblk(sb, block);
3927 if (!bh) {
3928 ext4_error(sb, "ext4_get_inode_loc", "unable to read "
3929 "inode block - inode=%lu, block=%llu",
3930 inode->i_ino, block);
3931 return -EIO;
3933 if (!buffer_uptodate(bh)) {
3934 lock_buffer(bh);
3937 * If the buffer has the write error flag, we have failed
3938 * to write out another inode in the same block. In this
3939 * case, we don't have to read the block because we may
3940 * read the old inode data successfully.
3942 if (buffer_write_io_error(bh) && !buffer_uptodate(bh))
3943 set_buffer_uptodate(bh);
3945 if (buffer_uptodate(bh)) {
3946 /* someone brought it uptodate while we waited */
3947 unlock_buffer(bh);
3948 goto has_buffer;
3952 * If we have all information of the inode in memory and this
3953 * is the only valid inode in the block, we need not read the
3954 * block.
3956 if (in_mem) {
3957 struct buffer_head *bitmap_bh;
3958 int i, start;
3960 start = inode_offset & ~(inodes_per_block - 1);
3962 /* Is the inode bitmap in cache? */
3963 bitmap_bh = sb_getblk(sb, ext4_inode_bitmap(sb, gdp));
3964 if (!bitmap_bh)
3965 goto make_io;
3968 * If the inode bitmap isn't in cache then the
3969 * optimisation may end up performing two reads instead
3970 * of one, so skip it.
3972 if (!buffer_uptodate(bitmap_bh)) {
3973 brelse(bitmap_bh);
3974 goto make_io;
3976 for (i = start; i < start + inodes_per_block; i++) {
3977 if (i == inode_offset)
3978 continue;
3979 if (ext4_test_bit(i, bitmap_bh->b_data))
3980 break;
3982 brelse(bitmap_bh);
3983 if (i == start + inodes_per_block) {
3984 /* all other inodes are free, so skip I/O */
3985 memset(bh->b_data, 0, bh->b_size);
3986 set_buffer_uptodate(bh);
3987 unlock_buffer(bh);
3988 goto has_buffer;
3992 make_io:
3994 * If we need to do any I/O, try to pre-readahead extra
3995 * blocks from the inode table.
3997 if (EXT4_SB(sb)->s_inode_readahead_blks) {
3998 ext4_fsblk_t b, end, table;
3999 unsigned num;
4001 table = ext4_inode_table(sb, gdp);
4002 /* Make sure s_inode_readahead_blks is a power of 2 */
4003 while (EXT4_SB(sb)->s_inode_readahead_blks &
4004 (EXT4_SB(sb)->s_inode_readahead_blks-1))
4005 EXT4_SB(sb)->s_inode_readahead_blks =
4006 (EXT4_SB(sb)->s_inode_readahead_blks &
4007 (EXT4_SB(sb)->s_inode_readahead_blks-1));
4008 b = block & ~(EXT4_SB(sb)->s_inode_readahead_blks-1);
4009 if (table > b)
4010 b = table;
4011 end = b + EXT4_SB(sb)->s_inode_readahead_blks;
4012 num = EXT4_INODES_PER_GROUP(sb);
4013 if (EXT4_HAS_RO_COMPAT_FEATURE(sb,
4014 EXT4_FEATURE_RO_COMPAT_GDT_CSUM))
4015 num -= le16_to_cpu(gdp->bg_itable_unused);
4016 table += num / inodes_per_block;
4017 if (end > table)
4018 end = table;
4019 while (b <= end)
4020 sb_breadahead(sb, b++);
4024 * There are other valid inodes in the buffer, this inode
4025 * has in-inode xattrs, or we don't have this inode in memory.
4026 * Read the block from disk.
4028 get_bh(bh);
4029 bh->b_end_io = end_buffer_read_sync;
4030 submit_bh(READ_META, bh);
4031 wait_on_buffer(bh);
4032 if (!buffer_uptodate(bh)) {
4033 ext4_error(sb, __func__,
4034 "unable to read inode block - inode=%lu, "
4035 "block=%llu", inode->i_ino, block);
4036 brelse(bh);
4037 return -EIO;
4040 has_buffer:
4041 iloc->bh = bh;
4042 return 0;
4045 int ext4_get_inode_loc(struct inode *inode, struct ext4_iloc *iloc)
4047 /* We have all inode data except xattrs in memory here. */
4048 return __ext4_get_inode_loc(inode, iloc,
4049 !(EXT4_I(inode)->i_state & EXT4_STATE_XATTR));
4052 void ext4_set_inode_flags(struct inode *inode)
4054 unsigned int flags = EXT4_I(inode)->i_flags;
4056 inode->i_flags &= ~(S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME|S_DIRSYNC);
4057 if (flags & EXT4_SYNC_FL)
4058 inode->i_flags |= S_SYNC;
4059 if (flags & EXT4_APPEND_FL)
4060 inode->i_flags |= S_APPEND;
4061 if (flags & EXT4_IMMUTABLE_FL)
4062 inode->i_flags |= S_IMMUTABLE;
4063 if (flags & EXT4_NOATIME_FL)
4064 inode->i_flags |= S_NOATIME;
4065 if (flags & EXT4_DIRSYNC_FL)
4066 inode->i_flags |= S_DIRSYNC;
4069 /* Propagate flags from i_flags to EXT4_I(inode)->i_flags */
4070 void ext4_get_inode_flags(struct ext4_inode_info *ei)
4072 unsigned int flags = ei->vfs_inode.i_flags;
4074 ei->i_flags &= ~(EXT4_SYNC_FL|EXT4_APPEND_FL|
4075 EXT4_IMMUTABLE_FL|EXT4_NOATIME_FL|EXT4_DIRSYNC_FL);
4076 if (flags & S_SYNC)
4077 ei->i_flags |= EXT4_SYNC_FL;
4078 if (flags & S_APPEND)
4079 ei->i_flags |= EXT4_APPEND_FL;
4080 if (flags & S_IMMUTABLE)
4081 ei->i_flags |= EXT4_IMMUTABLE_FL;
4082 if (flags & S_NOATIME)
4083 ei->i_flags |= EXT4_NOATIME_FL;
4084 if (flags & S_DIRSYNC)
4085 ei->i_flags |= EXT4_DIRSYNC_FL;
4087 static blkcnt_t ext4_inode_blocks(struct ext4_inode *raw_inode,
4088 struct ext4_inode_info *ei)
4090 blkcnt_t i_blocks ;
4091 struct inode *inode = &(ei->vfs_inode);
4092 struct super_block *sb = inode->i_sb;
4094 if (EXT4_HAS_RO_COMPAT_FEATURE(sb,
4095 EXT4_FEATURE_RO_COMPAT_HUGE_FILE)) {
4096 /* we are using combined 48 bit field */
4097 i_blocks = ((u64)le16_to_cpu(raw_inode->i_blocks_high)) << 32 |
4098 le32_to_cpu(raw_inode->i_blocks_lo);
4099 if (ei->i_flags & EXT4_HUGE_FILE_FL) {
4100 /* i_blocks represent file system block size */
4101 return i_blocks << (inode->i_blkbits - 9);
4102 } else {
4103 return i_blocks;
4105 } else {
4106 return le32_to_cpu(raw_inode->i_blocks_lo);
4110 struct inode *ext4_iget(struct super_block *sb, unsigned long ino)
4112 struct ext4_iloc iloc;
4113 struct ext4_inode *raw_inode;
4114 struct ext4_inode_info *ei;
4115 struct buffer_head *bh;
4116 struct inode *inode;
4117 long ret;
4118 int block;
4120 inode = iget_locked(sb, ino);
4121 if (!inode)
4122 return ERR_PTR(-ENOMEM);
4123 if (!(inode->i_state & I_NEW))
4124 return inode;
4126 ei = EXT4_I(inode);
4127 #ifdef CONFIG_EXT4_FS_POSIX_ACL
4128 ei->i_acl = EXT4_ACL_NOT_CACHED;
4129 ei->i_default_acl = EXT4_ACL_NOT_CACHED;
4130 #endif
4132 ret = __ext4_get_inode_loc(inode, &iloc, 0);
4133 if (ret < 0)
4134 goto bad_inode;
4135 bh = iloc.bh;
4136 raw_inode = ext4_raw_inode(&iloc);
4137 inode->i_mode = le16_to_cpu(raw_inode->i_mode);
4138 inode->i_uid = (uid_t)le16_to_cpu(raw_inode->i_uid_low);
4139 inode->i_gid = (gid_t)le16_to_cpu(raw_inode->i_gid_low);
4140 if (!(test_opt(inode->i_sb, NO_UID32))) {
4141 inode->i_uid |= le16_to_cpu(raw_inode->i_uid_high) << 16;
4142 inode->i_gid |= le16_to_cpu(raw_inode->i_gid_high) << 16;
4144 inode->i_nlink = le16_to_cpu(raw_inode->i_links_count);
4146 ei->i_state = 0;
4147 ei->i_dir_start_lookup = 0;
4148 ei->i_dtime = le32_to_cpu(raw_inode->i_dtime);
4149 /* We now have enough fields to check if the inode was active or not.
4150 * This is needed because nfsd might try to access dead inodes
4151 * the test is that same one that e2fsck uses
4152 * NeilBrown 1999oct15
4154 if (inode->i_nlink == 0) {
4155 if (inode->i_mode == 0 ||
4156 !(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_ORPHAN_FS)) {
4157 /* this inode is deleted */
4158 brelse(bh);
4159 ret = -ESTALE;
4160 goto bad_inode;
4162 /* The only unlinked inodes we let through here have
4163 * valid i_mode and are being read by the orphan
4164 * recovery code: that's fine, we're about to complete
4165 * the process of deleting those. */
4167 ei->i_flags = le32_to_cpu(raw_inode->i_flags);
4168 inode->i_blocks = ext4_inode_blocks(raw_inode, ei);
4169 ei->i_file_acl = le32_to_cpu(raw_inode->i_file_acl_lo);
4170 if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
4171 cpu_to_le32(EXT4_OS_HURD)) {
4172 ei->i_file_acl |=
4173 ((__u64)le16_to_cpu(raw_inode->i_file_acl_high)) << 32;
4175 inode->i_size = ext4_isize(raw_inode);
4176 ei->i_disksize = inode->i_size;
4177 inode->i_generation = le32_to_cpu(raw_inode->i_generation);
4178 ei->i_block_group = iloc.block_group;
4180 * NOTE! The in-memory inode i_data array is in little-endian order
4181 * even on big-endian machines: we do NOT byteswap the block numbers!
4183 for (block = 0; block < EXT4_N_BLOCKS; block++)
4184 ei->i_data[block] = raw_inode->i_block[block];
4185 INIT_LIST_HEAD(&ei->i_orphan);
4187 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4188 ei->i_extra_isize = le16_to_cpu(raw_inode->i_extra_isize);
4189 if (EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize >
4190 EXT4_INODE_SIZE(inode->i_sb)) {
4191 brelse(bh);
4192 ret = -EIO;
4193 goto bad_inode;
4195 if (ei->i_extra_isize == 0) {
4196 /* The extra space is currently unused. Use it. */
4197 ei->i_extra_isize = sizeof(struct ext4_inode) -
4198 EXT4_GOOD_OLD_INODE_SIZE;
4199 } else {
4200 __le32 *magic = (void *)raw_inode +
4201 EXT4_GOOD_OLD_INODE_SIZE +
4202 ei->i_extra_isize;
4203 if (*magic == cpu_to_le32(EXT4_XATTR_MAGIC))
4204 ei->i_state |= EXT4_STATE_XATTR;
4206 } else
4207 ei->i_extra_isize = 0;
4209 EXT4_INODE_GET_XTIME(i_ctime, inode, raw_inode);
4210 EXT4_INODE_GET_XTIME(i_mtime, inode, raw_inode);
4211 EXT4_INODE_GET_XTIME(i_atime, inode, raw_inode);
4212 EXT4_EINODE_GET_XTIME(i_crtime, ei, raw_inode);
4214 inode->i_version = le32_to_cpu(raw_inode->i_disk_version);
4215 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4216 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
4217 inode->i_version |=
4218 (__u64)(le32_to_cpu(raw_inode->i_version_hi)) << 32;
4221 if (S_ISREG(inode->i_mode)) {
4222 inode->i_op = &ext4_file_inode_operations;
4223 inode->i_fop = &ext4_file_operations;
4224 ext4_set_aops(inode);
4225 } else if (S_ISDIR(inode->i_mode)) {
4226 inode->i_op = &ext4_dir_inode_operations;
4227 inode->i_fop = &ext4_dir_operations;
4228 } else if (S_ISLNK(inode->i_mode)) {
4229 if (ext4_inode_is_fast_symlink(inode))
4230 inode->i_op = &ext4_fast_symlink_inode_operations;
4231 else {
4232 inode->i_op = &ext4_symlink_inode_operations;
4233 ext4_set_aops(inode);
4235 } else {
4236 inode->i_op = &ext4_special_inode_operations;
4237 if (raw_inode->i_block[0])
4238 init_special_inode(inode, inode->i_mode,
4239 old_decode_dev(le32_to_cpu(raw_inode->i_block[0])));
4240 else
4241 init_special_inode(inode, inode->i_mode,
4242 new_decode_dev(le32_to_cpu(raw_inode->i_block[1])));
4244 brelse(iloc.bh);
4245 ext4_set_inode_flags(inode);
4246 unlock_new_inode(inode);
4247 return inode;
4249 bad_inode:
4250 iget_failed(inode);
4251 return ERR_PTR(ret);
4254 static int ext4_inode_blocks_set(handle_t *handle,
4255 struct ext4_inode *raw_inode,
4256 struct ext4_inode_info *ei)
4258 struct inode *inode = &(ei->vfs_inode);
4259 u64 i_blocks = inode->i_blocks;
4260 struct super_block *sb = inode->i_sb;
4262 if (i_blocks <= ~0U) {
4264 * i_blocks can be represnted in a 32 bit variable
4265 * as multiple of 512 bytes
4267 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
4268 raw_inode->i_blocks_high = 0;
4269 ei->i_flags &= ~EXT4_HUGE_FILE_FL;
4270 return 0;
4272 if (!EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_HUGE_FILE))
4273 return -EFBIG;
4275 if (i_blocks <= 0xffffffffffffULL) {
4277 * i_blocks can be represented in a 48 bit variable
4278 * as multiple of 512 bytes
4280 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
4281 raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
4282 ei->i_flags &= ~EXT4_HUGE_FILE_FL;
4283 } else {
4284 ei->i_flags |= EXT4_HUGE_FILE_FL;
4285 /* i_block is stored in file system block size */
4286 i_blocks = i_blocks >> (inode->i_blkbits - 9);
4287 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
4288 raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
4290 return 0;
4294 * Post the struct inode info into an on-disk inode location in the
4295 * buffer-cache. This gobbles the caller's reference to the
4296 * buffer_head in the inode location struct.
4298 * The caller must have write access to iloc->bh.
4300 static int ext4_do_update_inode(handle_t *handle,
4301 struct inode *inode,
4302 struct ext4_iloc *iloc)
4304 struct ext4_inode *raw_inode = ext4_raw_inode(iloc);
4305 struct ext4_inode_info *ei = EXT4_I(inode);
4306 struct buffer_head *bh = iloc->bh;
4307 int err = 0, rc, block;
4309 /* For fields not not tracking in the in-memory inode,
4310 * initialise them to zero for new inodes. */
4311 if (ei->i_state & EXT4_STATE_NEW)
4312 memset(raw_inode, 0, EXT4_SB(inode->i_sb)->s_inode_size);
4314 ext4_get_inode_flags(ei);
4315 raw_inode->i_mode = cpu_to_le16(inode->i_mode);
4316 if (!(test_opt(inode->i_sb, NO_UID32))) {
4317 raw_inode->i_uid_low = cpu_to_le16(low_16_bits(inode->i_uid));
4318 raw_inode->i_gid_low = cpu_to_le16(low_16_bits(inode->i_gid));
4320 * Fix up interoperability with old kernels. Otherwise, old inodes get
4321 * re-used with the upper 16 bits of the uid/gid intact
4323 if (!ei->i_dtime) {
4324 raw_inode->i_uid_high =
4325 cpu_to_le16(high_16_bits(inode->i_uid));
4326 raw_inode->i_gid_high =
4327 cpu_to_le16(high_16_bits(inode->i_gid));
4328 } else {
4329 raw_inode->i_uid_high = 0;
4330 raw_inode->i_gid_high = 0;
4332 } else {
4333 raw_inode->i_uid_low =
4334 cpu_to_le16(fs_high2lowuid(inode->i_uid));
4335 raw_inode->i_gid_low =
4336 cpu_to_le16(fs_high2lowgid(inode->i_gid));
4337 raw_inode->i_uid_high = 0;
4338 raw_inode->i_gid_high = 0;
4340 raw_inode->i_links_count = cpu_to_le16(inode->i_nlink);
4342 EXT4_INODE_SET_XTIME(i_ctime, inode, raw_inode);
4343 EXT4_INODE_SET_XTIME(i_mtime, inode, raw_inode);
4344 EXT4_INODE_SET_XTIME(i_atime, inode, raw_inode);
4345 EXT4_EINODE_SET_XTIME(i_crtime, ei, raw_inode);
4347 if (ext4_inode_blocks_set(handle, raw_inode, ei))
4348 goto out_brelse;
4349 raw_inode->i_dtime = cpu_to_le32(ei->i_dtime);
4350 /* clear the migrate flag in the raw_inode */
4351 raw_inode->i_flags = cpu_to_le32(ei->i_flags & ~EXT4_EXT_MIGRATE);
4352 if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
4353 cpu_to_le32(EXT4_OS_HURD))
4354 raw_inode->i_file_acl_high =
4355 cpu_to_le16(ei->i_file_acl >> 32);
4356 raw_inode->i_file_acl_lo = cpu_to_le32(ei->i_file_acl);
4357 ext4_isize_set(raw_inode, ei->i_disksize);
4358 if (ei->i_disksize > 0x7fffffffULL) {
4359 struct super_block *sb = inode->i_sb;
4360 if (!EXT4_HAS_RO_COMPAT_FEATURE(sb,
4361 EXT4_FEATURE_RO_COMPAT_LARGE_FILE) ||
4362 EXT4_SB(sb)->s_es->s_rev_level ==
4363 cpu_to_le32(EXT4_GOOD_OLD_REV)) {
4364 /* If this is the first large file
4365 * created, add a flag to the superblock.
4367 err = ext4_journal_get_write_access(handle,
4368 EXT4_SB(sb)->s_sbh);
4369 if (err)
4370 goto out_brelse;
4371 ext4_update_dynamic_rev(sb);
4372 EXT4_SET_RO_COMPAT_FEATURE(sb,
4373 EXT4_FEATURE_RO_COMPAT_LARGE_FILE);
4374 sb->s_dirt = 1;
4375 handle->h_sync = 1;
4376 err = ext4_journal_dirty_metadata(handle,
4377 EXT4_SB(sb)->s_sbh);
4380 raw_inode->i_generation = cpu_to_le32(inode->i_generation);
4381 if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) {
4382 if (old_valid_dev(inode->i_rdev)) {
4383 raw_inode->i_block[0] =
4384 cpu_to_le32(old_encode_dev(inode->i_rdev));
4385 raw_inode->i_block[1] = 0;
4386 } else {
4387 raw_inode->i_block[0] = 0;
4388 raw_inode->i_block[1] =
4389 cpu_to_le32(new_encode_dev(inode->i_rdev));
4390 raw_inode->i_block[2] = 0;
4392 } else for (block = 0; block < EXT4_N_BLOCKS; block++)
4393 raw_inode->i_block[block] = ei->i_data[block];
4395 raw_inode->i_disk_version = cpu_to_le32(inode->i_version);
4396 if (ei->i_extra_isize) {
4397 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
4398 raw_inode->i_version_hi =
4399 cpu_to_le32(inode->i_version >> 32);
4400 raw_inode->i_extra_isize = cpu_to_le16(ei->i_extra_isize);
4404 BUFFER_TRACE(bh, "call ext4_journal_dirty_metadata");
4405 rc = ext4_journal_dirty_metadata(handle, bh);
4406 if (!err)
4407 err = rc;
4408 ei->i_state &= ~EXT4_STATE_NEW;
4410 out_brelse:
4411 brelse(bh);
4412 ext4_std_error(inode->i_sb, err);
4413 return err;
4417 * ext4_write_inode()
4419 * We are called from a few places:
4421 * - Within generic_file_write() for O_SYNC files.
4422 * Here, there will be no transaction running. We wait for any running
4423 * trasnaction to commit.
4425 * - Within sys_sync(), kupdate and such.
4426 * We wait on commit, if tol to.
4428 * - Within prune_icache() (PF_MEMALLOC == true)
4429 * Here we simply return. We can't afford to block kswapd on the
4430 * journal commit.
4432 * In all cases it is actually safe for us to return without doing anything,
4433 * because the inode has been copied into a raw inode buffer in
4434 * ext4_mark_inode_dirty(). This is a correctness thing for O_SYNC and for
4435 * knfsd.
4437 * Note that we are absolutely dependent upon all inode dirtiers doing the
4438 * right thing: they *must* call mark_inode_dirty() after dirtying info in
4439 * which we are interested.
4441 * It would be a bug for them to not do this. The code:
4443 * mark_inode_dirty(inode)
4444 * stuff();
4445 * inode->i_size = expr;
4447 * is in error because a kswapd-driven write_inode() could occur while
4448 * `stuff()' is running, and the new i_size will be lost. Plus the inode
4449 * will no longer be on the superblock's dirty inode list.
4451 int ext4_write_inode(struct inode *inode, int wait)
4453 if (current->flags & PF_MEMALLOC)
4454 return 0;
4456 if (ext4_journal_current_handle()) {
4457 jbd_debug(1, "called recursively, non-PF_MEMALLOC!\n");
4458 dump_stack();
4459 return -EIO;
4462 if (!wait)
4463 return 0;
4465 return ext4_force_commit(inode->i_sb);
4469 * ext4_setattr()
4471 * Called from notify_change.
4473 * We want to trap VFS attempts to truncate the file as soon as
4474 * possible. In particular, we want to make sure that when the VFS
4475 * shrinks i_size, we put the inode on the orphan list and modify
4476 * i_disksize immediately, so that during the subsequent flushing of
4477 * dirty pages and freeing of disk blocks, we can guarantee that any
4478 * commit will leave the blocks being flushed in an unused state on
4479 * disk. (On recovery, the inode will get truncated and the blocks will
4480 * be freed, so we have a strong guarantee that no future commit will
4481 * leave these blocks visible to the user.)
4483 * Another thing we have to assure is that if we are in ordered mode
4484 * and inode is still attached to the committing transaction, we must
4485 * we start writeout of all the dirty pages which are being truncated.
4486 * This way we are sure that all the data written in the previous
4487 * transaction are already on disk (truncate waits for pages under
4488 * writeback).
4490 * Called with inode->i_mutex down.
4492 int ext4_setattr(struct dentry *dentry, struct iattr *attr)
4494 struct inode *inode = dentry->d_inode;
4495 int error, rc = 0;
4496 const unsigned int ia_valid = attr->ia_valid;
4498 error = inode_change_ok(inode, attr);
4499 if (error)
4500 return error;
4502 if ((ia_valid & ATTR_UID && attr->ia_uid != inode->i_uid) ||
4503 (ia_valid & ATTR_GID && attr->ia_gid != inode->i_gid)) {
4504 handle_t *handle;
4506 /* (user+group)*(old+new) structure, inode write (sb,
4507 * inode block, ? - but truncate inode update has it) */
4508 handle = ext4_journal_start(inode, 2*(EXT4_QUOTA_INIT_BLOCKS(inode->i_sb)+
4509 EXT4_QUOTA_DEL_BLOCKS(inode->i_sb))+3);
4510 if (IS_ERR(handle)) {
4511 error = PTR_ERR(handle);
4512 goto err_out;
4514 error = DQUOT_TRANSFER(inode, attr) ? -EDQUOT : 0;
4515 if (error) {
4516 ext4_journal_stop(handle);
4517 return error;
4519 /* Update corresponding info in inode so that everything is in
4520 * one transaction */
4521 if (attr->ia_valid & ATTR_UID)
4522 inode->i_uid = attr->ia_uid;
4523 if (attr->ia_valid & ATTR_GID)
4524 inode->i_gid = attr->ia_gid;
4525 error = ext4_mark_inode_dirty(handle, inode);
4526 ext4_journal_stop(handle);
4529 if (attr->ia_valid & ATTR_SIZE) {
4530 if (!(EXT4_I(inode)->i_flags & EXT4_EXTENTS_FL)) {
4531 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4533 if (attr->ia_size > sbi->s_bitmap_maxbytes) {
4534 error = -EFBIG;
4535 goto err_out;
4540 if (S_ISREG(inode->i_mode) &&
4541 attr->ia_valid & ATTR_SIZE && attr->ia_size < inode->i_size) {
4542 handle_t *handle;
4544 handle = ext4_journal_start(inode, 3);
4545 if (IS_ERR(handle)) {
4546 error = PTR_ERR(handle);
4547 goto err_out;
4550 error = ext4_orphan_add(handle, inode);
4551 EXT4_I(inode)->i_disksize = attr->ia_size;
4552 rc = ext4_mark_inode_dirty(handle, inode);
4553 if (!error)
4554 error = rc;
4555 ext4_journal_stop(handle);
4557 if (ext4_should_order_data(inode)) {
4558 error = ext4_begin_ordered_truncate(inode,
4559 attr->ia_size);
4560 if (error) {
4561 /* Do as much error cleanup as possible */
4562 handle = ext4_journal_start(inode, 3);
4563 if (IS_ERR(handle)) {
4564 ext4_orphan_del(NULL, inode);
4565 goto err_out;
4567 ext4_orphan_del(handle, inode);
4568 ext4_journal_stop(handle);
4569 goto err_out;
4574 rc = inode_setattr(inode, attr);
4576 /* If inode_setattr's call to ext4_truncate failed to get a
4577 * transaction handle at all, we need to clean up the in-core
4578 * orphan list manually. */
4579 if (inode->i_nlink)
4580 ext4_orphan_del(NULL, inode);
4582 if (!rc && (ia_valid & ATTR_MODE))
4583 rc = ext4_acl_chmod(inode);
4585 err_out:
4586 ext4_std_error(inode->i_sb, error);
4587 if (!error)
4588 error = rc;
4589 return error;
4592 int ext4_getattr(struct vfsmount *mnt, struct dentry *dentry,
4593 struct kstat *stat)
4595 struct inode *inode;
4596 unsigned long delalloc_blocks;
4598 inode = dentry->d_inode;
4599 generic_fillattr(inode, stat);
4602 * We can't update i_blocks if the block allocation is delayed
4603 * otherwise in the case of system crash before the real block
4604 * allocation is done, we will have i_blocks inconsistent with
4605 * on-disk file blocks.
4606 * We always keep i_blocks updated together with real
4607 * allocation. But to not confuse with user, stat
4608 * will return the blocks that include the delayed allocation
4609 * blocks for this file.
4611 spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
4612 delalloc_blocks = EXT4_I(inode)->i_reserved_data_blocks;
4613 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
4615 stat->blocks += (delalloc_blocks << inode->i_sb->s_blocksize_bits)>>9;
4616 return 0;
4619 static int ext4_indirect_trans_blocks(struct inode *inode, int nrblocks,
4620 int chunk)
4622 int indirects;
4624 /* if nrblocks are contiguous */
4625 if (chunk) {
4627 * With N contiguous data blocks, it need at most
4628 * N/EXT4_ADDR_PER_BLOCK(inode->i_sb) indirect blocks
4629 * 2 dindirect blocks
4630 * 1 tindirect block
4632 indirects = nrblocks / EXT4_ADDR_PER_BLOCK(inode->i_sb);
4633 return indirects + 3;
4636 * if nrblocks are not contiguous, worse case, each block touch
4637 * a indirect block, and each indirect block touch a double indirect
4638 * block, plus a triple indirect block
4640 indirects = nrblocks * 2 + 1;
4641 return indirects;
4644 static int ext4_index_trans_blocks(struct inode *inode, int nrblocks, int chunk)
4646 if (!(EXT4_I(inode)->i_flags & EXT4_EXTENTS_FL))
4647 return ext4_indirect_trans_blocks(inode, nrblocks, chunk);
4648 return ext4_ext_index_trans_blocks(inode, nrblocks, chunk);
4652 * Account for index blocks, block groups bitmaps and block group
4653 * descriptor blocks if modify datablocks and index blocks
4654 * worse case, the indexs blocks spread over different block groups
4656 * If datablocks are discontiguous, they are possible to spread over
4657 * different block groups too. If they are contiugous, with flexbg,
4658 * they could still across block group boundary.
4660 * Also account for superblock, inode, quota and xattr blocks
4662 int ext4_meta_trans_blocks(struct inode *inode, int nrblocks, int chunk)
4664 int groups, gdpblocks;
4665 int idxblocks;
4666 int ret = 0;
4669 * How many index blocks need to touch to modify nrblocks?
4670 * The "Chunk" flag indicating whether the nrblocks is
4671 * physically contiguous on disk
4673 * For Direct IO and fallocate, they calls get_block to allocate
4674 * one single extent at a time, so they could set the "Chunk" flag
4676 idxblocks = ext4_index_trans_blocks(inode, nrblocks, chunk);
4678 ret = idxblocks;
4681 * Now let's see how many group bitmaps and group descriptors need
4682 * to account
4684 groups = idxblocks;
4685 if (chunk)
4686 groups += 1;
4687 else
4688 groups += nrblocks;
4690 gdpblocks = groups;
4691 if (groups > EXT4_SB(inode->i_sb)->s_groups_count)
4692 groups = EXT4_SB(inode->i_sb)->s_groups_count;
4693 if (groups > EXT4_SB(inode->i_sb)->s_gdb_count)
4694 gdpblocks = EXT4_SB(inode->i_sb)->s_gdb_count;
4696 /* bitmaps and block group descriptor blocks */
4697 ret += groups + gdpblocks;
4699 /* Blocks for super block, inode, quota and xattr blocks */
4700 ret += EXT4_META_TRANS_BLOCKS(inode->i_sb);
4702 return ret;
4706 * Calulate the total number of credits to reserve to fit
4707 * the modification of a single pages into a single transaction,
4708 * which may include multiple chunks of block allocations.
4710 * This could be called via ext4_write_begin()
4712 * We need to consider the worse case, when
4713 * one new block per extent.
4715 int ext4_writepage_trans_blocks(struct inode *inode)
4717 int bpp = ext4_journal_blocks_per_page(inode);
4718 int ret;
4720 ret = ext4_meta_trans_blocks(inode, bpp, 0);
4722 /* Account for data blocks for journalled mode */
4723 if (ext4_should_journal_data(inode))
4724 ret += bpp;
4725 return ret;
4729 * Calculate the journal credits for a chunk of data modification.
4731 * This is called from DIO, fallocate or whoever calling
4732 * ext4_get_blocks_wrap() to map/allocate a chunk of contigous disk blocks.
4734 * journal buffers for data blocks are not included here, as DIO
4735 * and fallocate do no need to journal data buffers.
4737 int ext4_chunk_trans_blocks(struct inode *inode, int nrblocks)
4739 return ext4_meta_trans_blocks(inode, nrblocks, 1);
4743 * The caller must have previously called ext4_reserve_inode_write().
4744 * Give this, we know that the caller already has write access to iloc->bh.
4746 int ext4_mark_iloc_dirty(handle_t *handle,
4747 struct inode *inode, struct ext4_iloc *iloc)
4749 int err = 0;
4751 if (test_opt(inode->i_sb, I_VERSION))
4752 inode_inc_iversion(inode);
4754 /* the do_update_inode consumes one bh->b_count */
4755 get_bh(iloc->bh);
4757 /* ext4_do_update_inode() does jbd2_journal_dirty_metadata */
4758 err = ext4_do_update_inode(handle, inode, iloc);
4759 put_bh(iloc->bh);
4760 return err;
4764 * On success, We end up with an outstanding reference count against
4765 * iloc->bh. This _must_ be cleaned up later.
4769 ext4_reserve_inode_write(handle_t *handle, struct inode *inode,
4770 struct ext4_iloc *iloc)
4772 int err = 0;
4773 if (handle) {
4774 err = ext4_get_inode_loc(inode, iloc);
4775 if (!err) {
4776 BUFFER_TRACE(iloc->bh, "get_write_access");
4777 err = ext4_journal_get_write_access(handle, iloc->bh);
4778 if (err) {
4779 brelse(iloc->bh);
4780 iloc->bh = NULL;
4784 ext4_std_error(inode->i_sb, err);
4785 return err;
4789 * Expand an inode by new_extra_isize bytes.
4790 * Returns 0 on success or negative error number on failure.
4792 static int ext4_expand_extra_isize(struct inode *inode,
4793 unsigned int new_extra_isize,
4794 struct ext4_iloc iloc,
4795 handle_t *handle)
4797 struct ext4_inode *raw_inode;
4798 struct ext4_xattr_ibody_header *header;
4799 struct ext4_xattr_entry *entry;
4801 if (EXT4_I(inode)->i_extra_isize >= new_extra_isize)
4802 return 0;
4804 raw_inode = ext4_raw_inode(&iloc);
4806 header = IHDR(inode, raw_inode);
4807 entry = IFIRST(header);
4809 /* No extended attributes present */
4810 if (!(EXT4_I(inode)->i_state & EXT4_STATE_XATTR) ||
4811 header->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC)) {
4812 memset((void *)raw_inode + EXT4_GOOD_OLD_INODE_SIZE, 0,
4813 new_extra_isize);
4814 EXT4_I(inode)->i_extra_isize = new_extra_isize;
4815 return 0;
4818 /* try to expand with EAs present */
4819 return ext4_expand_extra_isize_ea(inode, new_extra_isize,
4820 raw_inode, handle);
4824 * What we do here is to mark the in-core inode as clean with respect to inode
4825 * dirtiness (it may still be data-dirty).
4826 * This means that the in-core inode may be reaped by prune_icache
4827 * without having to perform any I/O. This is a very good thing,
4828 * because *any* task may call prune_icache - even ones which
4829 * have a transaction open against a different journal.
4831 * Is this cheating? Not really. Sure, we haven't written the
4832 * inode out, but prune_icache isn't a user-visible syncing function.
4833 * Whenever the user wants stuff synced (sys_sync, sys_msync, sys_fsync)
4834 * we start and wait on commits.
4836 * Is this efficient/effective? Well, we're being nice to the system
4837 * by cleaning up our inodes proactively so they can be reaped
4838 * without I/O. But we are potentially leaving up to five seconds'
4839 * worth of inodes floating about which prune_icache wants us to
4840 * write out. One way to fix that would be to get prune_icache()
4841 * to do a write_super() to free up some memory. It has the desired
4842 * effect.
4844 int ext4_mark_inode_dirty(handle_t *handle, struct inode *inode)
4846 struct ext4_iloc iloc;
4847 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4848 static unsigned int mnt_count;
4849 int err, ret;
4851 might_sleep();
4852 err = ext4_reserve_inode_write(handle, inode, &iloc);
4853 if (EXT4_I(inode)->i_extra_isize < sbi->s_want_extra_isize &&
4854 !(EXT4_I(inode)->i_state & EXT4_STATE_NO_EXPAND)) {
4856 * We need extra buffer credits since we may write into EA block
4857 * with this same handle. If journal_extend fails, then it will
4858 * only result in a minor loss of functionality for that inode.
4859 * If this is felt to be critical, then e2fsck should be run to
4860 * force a large enough s_min_extra_isize.
4862 if ((jbd2_journal_extend(handle,
4863 EXT4_DATA_TRANS_BLOCKS(inode->i_sb))) == 0) {
4864 ret = ext4_expand_extra_isize(inode,
4865 sbi->s_want_extra_isize,
4866 iloc, handle);
4867 if (ret) {
4868 EXT4_I(inode)->i_state |= EXT4_STATE_NO_EXPAND;
4869 if (mnt_count !=
4870 le16_to_cpu(sbi->s_es->s_mnt_count)) {
4871 ext4_warning(inode->i_sb, __func__,
4872 "Unable to expand inode %lu. Delete"
4873 " some EAs or run e2fsck.",
4874 inode->i_ino);
4875 mnt_count =
4876 le16_to_cpu(sbi->s_es->s_mnt_count);
4881 if (!err)
4882 err = ext4_mark_iloc_dirty(handle, inode, &iloc);
4883 return err;
4887 * ext4_dirty_inode() is called from __mark_inode_dirty()
4889 * We're really interested in the case where a file is being extended.
4890 * i_size has been changed by generic_commit_write() and we thus need
4891 * to include the updated inode in the current transaction.
4893 * Also, DQUOT_ALLOC_SPACE() will always dirty the inode when blocks
4894 * are allocated to the file.
4896 * If the inode is marked synchronous, we don't honour that here - doing
4897 * so would cause a commit on atime updates, which we don't bother doing.
4898 * We handle synchronous inodes at the highest possible level.
4900 void ext4_dirty_inode(struct inode *inode)
4902 handle_t *current_handle = ext4_journal_current_handle();
4903 handle_t *handle;
4905 handle = ext4_journal_start(inode, 2);
4906 if (IS_ERR(handle))
4907 goto out;
4908 if (current_handle &&
4909 current_handle->h_transaction != handle->h_transaction) {
4910 /* This task has a transaction open against a different fs */
4911 printk(KERN_EMERG "%s: transactions do not match!\n",
4912 __func__);
4913 } else {
4914 jbd_debug(5, "marking dirty. outer handle=%p\n",
4915 current_handle);
4916 ext4_mark_inode_dirty(handle, inode);
4918 ext4_journal_stop(handle);
4919 out:
4920 return;
4923 #if 0
4925 * Bind an inode's backing buffer_head into this transaction, to prevent
4926 * it from being flushed to disk early. Unlike
4927 * ext4_reserve_inode_write, this leaves behind no bh reference and
4928 * returns no iloc structure, so the caller needs to repeat the iloc
4929 * lookup to mark the inode dirty later.
4931 static int ext4_pin_inode(handle_t *handle, struct inode *inode)
4933 struct ext4_iloc iloc;
4935 int err = 0;
4936 if (handle) {
4937 err = ext4_get_inode_loc(inode, &iloc);
4938 if (!err) {
4939 BUFFER_TRACE(iloc.bh, "get_write_access");
4940 err = jbd2_journal_get_write_access(handle, iloc.bh);
4941 if (!err)
4942 err = ext4_journal_dirty_metadata(handle,
4943 iloc.bh);
4944 brelse(iloc.bh);
4947 ext4_std_error(inode->i_sb, err);
4948 return err;
4950 #endif
4952 int ext4_change_inode_journal_flag(struct inode *inode, int val)
4954 journal_t *journal;
4955 handle_t *handle;
4956 int err;
4959 * We have to be very careful here: changing a data block's
4960 * journaling status dynamically is dangerous. If we write a
4961 * data block to the journal, change the status and then delete
4962 * that block, we risk forgetting to revoke the old log record
4963 * from the journal and so a subsequent replay can corrupt data.
4964 * So, first we make sure that the journal is empty and that
4965 * nobody is changing anything.
4968 journal = EXT4_JOURNAL(inode);
4969 if (is_journal_aborted(journal))
4970 return -EROFS;
4972 jbd2_journal_lock_updates(journal);
4973 jbd2_journal_flush(journal);
4976 * OK, there are no updates running now, and all cached data is
4977 * synced to disk. We are now in a completely consistent state
4978 * which doesn't have anything in the journal, and we know that
4979 * no filesystem updates are running, so it is safe to modify
4980 * the inode's in-core data-journaling state flag now.
4983 if (val)
4984 EXT4_I(inode)->i_flags |= EXT4_JOURNAL_DATA_FL;
4985 else
4986 EXT4_I(inode)->i_flags &= ~EXT4_JOURNAL_DATA_FL;
4987 ext4_set_aops(inode);
4989 jbd2_journal_unlock_updates(journal);
4991 /* Finally we can mark the inode as dirty. */
4993 handle = ext4_journal_start(inode, 1);
4994 if (IS_ERR(handle))
4995 return PTR_ERR(handle);
4997 err = ext4_mark_inode_dirty(handle, inode);
4998 handle->h_sync = 1;
4999 ext4_journal_stop(handle);
5000 ext4_std_error(inode->i_sb, err);
5002 return err;
5005 static int ext4_bh_unmapped(handle_t *handle, struct buffer_head *bh)
5007 return !buffer_mapped(bh);
5010 int ext4_page_mkwrite(struct vm_area_struct *vma, struct page *page)
5012 loff_t size;
5013 unsigned long len;
5014 int ret = -EINVAL;
5015 void *fsdata;
5016 struct file *file = vma->vm_file;
5017 struct inode *inode = file->f_path.dentry->d_inode;
5018 struct address_space *mapping = inode->i_mapping;
5021 * Get i_alloc_sem to stop truncates messing with the inode. We cannot
5022 * get i_mutex because we are already holding mmap_sem.
5024 down_read(&inode->i_alloc_sem);
5025 size = i_size_read(inode);
5026 if (page->mapping != mapping || size <= page_offset(page)
5027 || !PageUptodate(page)) {
5028 /* page got truncated from under us? */
5029 goto out_unlock;
5031 ret = 0;
5032 if (PageMappedToDisk(page))
5033 goto out_unlock;
5035 if (page->index == size >> PAGE_CACHE_SHIFT)
5036 len = size & ~PAGE_CACHE_MASK;
5037 else
5038 len = PAGE_CACHE_SIZE;
5040 if (page_has_buffers(page)) {
5041 /* return if we have all the buffers mapped */
5042 if (!walk_page_buffers(NULL, page_buffers(page), 0, len, NULL,
5043 ext4_bh_unmapped))
5044 goto out_unlock;
5047 * OK, we need to fill the hole... Do write_begin write_end
5048 * to do block allocation/reservation.We are not holding
5049 * inode.i__mutex here. That allow * parallel write_begin,
5050 * write_end call. lock_page prevent this from happening
5051 * on the same page though
5053 ret = mapping->a_ops->write_begin(file, mapping, page_offset(page),
5054 len, AOP_FLAG_UNINTERRUPTIBLE, &page, &fsdata);
5055 if (ret < 0)
5056 goto out_unlock;
5057 ret = mapping->a_ops->write_end(file, mapping, page_offset(page),
5058 len, len, page, fsdata);
5059 if (ret < 0)
5060 goto out_unlock;
5061 ret = 0;
5062 out_unlock:
5063 up_read(&inode->i_alloc_sem);
5064 return ret;