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)
11 * linux/fs/minix/inode.c
13 * Copyright (C) 1991, 1992 Linus Torvalds
15 * 64-bit file support on 64-bit platforms by Jakub Jelinek
16 * (jj@sunsite.ms.mff.cuni.cz)
18 * Assorted race fixes, rewrite of ext4_get_block() by Al Viro, 2000
21 #include <linux/module.h>
23 #include <linux/time.h>
24 #include <linux/jbd2.h>
25 #include <linux/highuid.h>
26 #include <linux/pagemap.h>
27 #include <linux/quotaops.h>
28 #include <linux/string.h>
29 #include <linux/buffer_head.h>
30 #include <linux/writeback.h>
31 #include <linux/pagevec.h>
32 #include <linux/mpage.h>
33 #include <linux/namei.h>
34 #include <linux/uio.h>
35 #include <linux/bio.h>
36 #include <linux/workqueue.h>
37 #include <linux/kernel.h>
38 #include <linux/printk.h>
39 #include <linux/slab.h>
40 #include <linux/ratelimit.h>
41 #include <linux/bitops.h>
43 #include "ext4_jbd2.h"
48 #include <trace/events/ext4.h>
50 #define MPAGE_DA_EXTENT_TAIL 0x01
52 static inline int ext4_begin_ordered_truncate(struct inode *inode,
55 trace_ext4_begin_ordered_truncate(inode, new_size);
57 * If jinode is zero, then we never opened the file for
58 * writing, so there's no need to call
59 * jbd2_journal_begin_ordered_truncate() since there's no
60 * outstanding writes we need to flush.
62 if (!EXT4_I(inode)->jinode)
64 return jbd2_journal_begin_ordered_truncate(EXT4_JOURNAL(inode),
65 EXT4_I(inode)->jinode,
69 static void ext4_invalidatepage(struct page *page, unsigned long offset);
70 static int noalloc_get_block_write(struct inode *inode, sector_t iblock,
71 struct buffer_head *bh_result, int create);
72 static int ext4_set_bh_endio(struct buffer_head *bh, struct inode *inode);
73 static void ext4_end_io_buffer_write(struct buffer_head *bh, int uptodate);
74 static int __ext4_journalled_writepage(struct page *page, unsigned int len);
75 static int ext4_bh_delay_or_unwritten(handle_t *handle, struct buffer_head *bh);
78 * Test whether an inode is a fast symlink.
80 static int ext4_inode_is_fast_symlink(struct inode *inode)
82 int ea_blocks = EXT4_I(inode)->i_file_acl ?
83 (inode->i_sb->s_blocksize >> 9) : 0;
85 return (S_ISLNK(inode->i_mode) && inode->i_blocks - ea_blocks == 0);
89 * Restart the transaction associated with *handle. This does a commit,
90 * so before we call here everything must be consistently dirtied against
93 int ext4_truncate_restart_trans(handle_t *handle, struct inode *inode,
99 * Drop i_data_sem to avoid deadlock with ext4_map_blocks. At this
100 * moment, get_block can be called only for blocks inside i_size since
101 * page cache has been already dropped and writes are blocked by
102 * i_mutex. So we can safely drop the i_data_sem here.
104 BUG_ON(EXT4_JOURNAL(inode) == NULL);
105 jbd_debug(2, "restarting handle %p\n", handle);
106 up_write(&EXT4_I(inode)->i_data_sem);
107 ret = ext4_journal_restart(handle, nblocks);
108 down_write(&EXT4_I(inode)->i_data_sem);
109 ext4_discard_preallocations(inode);
115 * Called at the last iput() if i_nlink is zero.
117 void ext4_evict_inode(struct inode *inode)
122 trace_ext4_evict_inode(inode);
124 ext4_ioend_wait(inode);
126 if (inode->i_nlink) {
128 * When journalling data dirty buffers are tracked only in the
129 * journal. So although mm thinks everything is clean and
130 * ready for reaping the inode might still have some pages to
131 * write in the running transaction or waiting to be
132 * checkpointed. Thus calling jbd2_journal_invalidatepage()
133 * (via truncate_inode_pages()) to discard these buffers can
134 * cause data loss. Also even if we did not discard these
135 * buffers, we would have no way to find them after the inode
136 * is reaped and thus user could see stale data if he tries to
137 * read them before the transaction is checkpointed. So be
138 * careful and force everything to disk here... We use
139 * ei->i_datasync_tid to store the newest transaction
140 * containing inode's data.
142 * Note that directories do not have this problem because they
143 * don't use page cache.
145 if (inode->i_ino != EXT4_JOURNAL_INO &&
146 ext4_should_journal_data(inode) &&
147 (S_ISLNK(inode->i_mode) || S_ISREG(inode->i_mode))) {
148 journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
149 tid_t commit_tid = EXT4_I(inode)->i_datasync_tid;
151 jbd2_complete_transaction(journal, commit_tid);
152 filemap_write_and_wait(&inode->i_data);
154 truncate_inode_pages(&inode->i_data, 0);
158 if (is_bad_inode(inode))
160 dquot_initialize(inode);
162 if (ext4_should_order_data(inode))
163 ext4_begin_ordered_truncate(inode, 0);
164 truncate_inode_pages(&inode->i_data, 0);
167 handle = ext4_journal_start(inode, ext4_blocks_for_truncate(inode)+3);
168 if (IS_ERR(handle)) {
169 ext4_std_error(inode->i_sb, PTR_ERR(handle));
171 * If we're going to skip the normal cleanup, we still need to
172 * make sure that the in-core orphan linked list is properly
175 ext4_orphan_del(NULL, inode);
180 ext4_handle_sync(handle);
182 err = ext4_mark_inode_dirty(handle, inode);
184 ext4_warning(inode->i_sb,
185 "couldn't mark inode dirty (err %d)", err);
189 ext4_truncate(inode);
192 * ext4_ext_truncate() doesn't reserve any slop when it
193 * restarts journal transactions; therefore there may not be
194 * enough credits left in the handle to remove the inode from
195 * the orphan list and set the dtime field.
197 if (!ext4_handle_has_enough_credits(handle, 3)) {
198 err = ext4_journal_extend(handle, 3);
200 err = ext4_journal_restart(handle, 3);
202 ext4_warning(inode->i_sb,
203 "couldn't extend journal (err %d)", err);
205 ext4_journal_stop(handle);
206 ext4_orphan_del(NULL, inode);
212 * Kill off the orphan record which ext4_truncate created.
213 * AKPM: I think this can be inside the above `if'.
214 * Note that ext4_orphan_del() has to be able to cope with the
215 * deletion of a non-existent orphan - this is because we don't
216 * know if ext4_truncate() actually created an orphan record.
217 * (Well, we could do this if we need to, but heck - it works)
219 ext4_orphan_del(handle, inode);
220 EXT4_I(inode)->i_dtime = get_seconds();
223 * One subtle ordering requirement: if anything has gone wrong
224 * (transaction abort, IO errors, whatever), then we can still
225 * do these next steps (the fs will already have been marked as
226 * having errors), but we can't free the inode if the mark_dirty
229 if (ext4_mark_inode_dirty(handle, inode))
230 /* If that failed, just do the required in-core inode clear. */
231 ext4_clear_inode(inode);
233 ext4_free_inode(handle, inode);
234 ext4_journal_stop(handle);
237 ext4_clear_inode(inode); /* We must guarantee clearing of inode... */
241 qsize_t *ext4_get_reserved_space(struct inode *inode)
243 return &EXT4_I(inode)->i_reserved_quota;
248 * Calculate the number of metadata blocks need to reserve
249 * to allocate a block located at @lblock
251 static int ext4_calc_metadata_amount(struct inode *inode, ext4_lblk_t lblock)
253 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
254 return ext4_ext_calc_metadata_amount(inode, lblock);
256 return ext4_ind_calc_metadata_amount(inode, lblock);
260 * Called with i_data_sem down, which is important since we can call
261 * ext4_discard_preallocations() from here.
263 void ext4_da_update_reserve_space(struct inode *inode,
264 int used, int quota_claim)
266 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
267 struct ext4_inode_info *ei = EXT4_I(inode);
269 spin_lock(&ei->i_block_reservation_lock);
270 trace_ext4_da_update_reserve_space(inode, used, quota_claim);
271 if (unlikely(used > ei->i_reserved_data_blocks)) {
272 ext4_msg(inode->i_sb, KERN_NOTICE, "%s: ino %lu, used %d "
273 "with only %d reserved data blocks\n",
274 __func__, inode->i_ino, used,
275 ei->i_reserved_data_blocks);
277 used = ei->i_reserved_data_blocks;
280 if (unlikely(ei->i_allocated_meta_blocks > ei->i_reserved_meta_blocks)) {
281 ext4_msg(inode->i_sb, KERN_NOTICE, "%s: ino %lu, allocated %d "
282 "with only %d reserved metadata blocks\n", __func__,
283 inode->i_ino, ei->i_allocated_meta_blocks,
284 ei->i_reserved_meta_blocks);
286 ei->i_allocated_meta_blocks = ei->i_reserved_meta_blocks;
289 /* Update per-inode reservations */
290 ei->i_reserved_data_blocks -= used;
291 ei->i_reserved_meta_blocks -= ei->i_allocated_meta_blocks;
292 percpu_counter_sub(&sbi->s_dirtyclusters_counter,
293 used + ei->i_allocated_meta_blocks);
294 ei->i_allocated_meta_blocks = 0;
296 if (ei->i_reserved_data_blocks == 0) {
298 * We can release all of the reserved metadata blocks
299 * only when we have written all of the delayed
302 percpu_counter_sub(&sbi->s_dirtyclusters_counter,
303 ei->i_reserved_meta_blocks);
304 ei->i_reserved_meta_blocks = 0;
305 ei->i_da_metadata_calc_len = 0;
307 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
309 /* Update quota subsystem for data blocks */
311 dquot_claim_block(inode, EXT4_C2B(sbi, used));
314 * We did fallocate with an offset that is already delayed
315 * allocated. So on delayed allocated writeback we should
316 * not re-claim the quota for fallocated blocks.
318 dquot_release_reservation_block(inode, EXT4_C2B(sbi, used));
322 * If we have done all the pending block allocations and if
323 * there aren't any writers on the inode, we can discard the
324 * inode's preallocations.
326 if ((ei->i_reserved_data_blocks == 0) &&
327 (atomic_read(&inode->i_writecount) == 0))
328 ext4_discard_preallocations(inode);
331 static int __check_block_validity(struct inode *inode, const char *func,
333 struct ext4_map_blocks *map)
335 if (!ext4_data_block_valid(EXT4_SB(inode->i_sb), map->m_pblk,
337 ext4_error_inode(inode, func, line, map->m_pblk,
338 "lblock %lu mapped to illegal pblock "
339 "(length %d)", (unsigned long) map->m_lblk,
346 #define check_block_validity(inode, map) \
347 __check_block_validity((inode), __func__, __LINE__, (map))
350 * Return the number of contiguous dirty pages in a given inode
351 * starting at page frame idx.
353 static pgoff_t ext4_num_dirty_pages(struct inode *inode, pgoff_t idx,
354 unsigned int max_pages)
356 struct address_space *mapping = inode->i_mapping;
360 int i, nr_pages, done = 0;
364 pagevec_init(&pvec, 0);
367 nr_pages = pagevec_lookup_tag(&pvec, mapping, &index,
369 (pgoff_t)PAGEVEC_SIZE);
372 for (i = 0; i < nr_pages; i++) {
373 struct page *page = pvec.pages[i];
374 struct buffer_head *bh, *head;
377 if (unlikely(page->mapping != mapping) ||
379 PageWriteback(page) ||
380 page->index != idx) {
385 if (page_has_buffers(page)) {
386 bh = head = page_buffers(page);
388 if (!buffer_delay(bh) &&
389 !buffer_unwritten(bh))
391 bh = bh->b_this_page;
392 } while (!done && (bh != head));
399 if (num >= max_pages) {
404 pagevec_release(&pvec);
410 * Sets the BH_Da_Mapped bit on the buffer heads corresponding to the given map.
412 static void set_buffers_da_mapped(struct inode *inode,
413 struct ext4_map_blocks *map)
415 struct address_space *mapping = inode->i_mapping;
420 index = map->m_lblk >> (PAGE_CACHE_SHIFT - inode->i_blkbits);
421 end = (map->m_lblk + map->m_len - 1) >>
422 (PAGE_CACHE_SHIFT - inode->i_blkbits);
424 pagevec_init(&pvec, 0);
425 while (index <= end) {
426 nr_pages = pagevec_lookup(&pvec, mapping, index,
428 (pgoff_t)PAGEVEC_SIZE));
431 for (i = 0; i < nr_pages; i++) {
432 struct page *page = pvec.pages[i];
433 struct buffer_head *bh, *head;
435 if (unlikely(page->mapping != mapping) ||
439 if (page_has_buffers(page)) {
440 bh = head = page_buffers(page);
442 set_buffer_da_mapped(bh);
443 bh = bh->b_this_page;
444 } while (bh != head);
448 pagevec_release(&pvec);
453 * The ext4_map_blocks() function tries to look up the requested blocks,
454 * and returns if the blocks are already mapped.
456 * Otherwise it takes the write lock of the i_data_sem and allocate blocks
457 * and store the allocated blocks in the result buffer head and mark it
460 * If file type is extents based, it will call ext4_ext_map_blocks(),
461 * Otherwise, call with ext4_ind_map_blocks() to handle indirect mapping
464 * On success, it returns the number of blocks being mapped or allocate.
465 * if create==0 and the blocks are pre-allocated and uninitialized block,
466 * the result buffer head is unmapped. If the create ==1, it will make sure
467 * the buffer head is mapped.
469 * It returns 0 if plain look up failed (blocks have not been allocated), in
470 * that case, buffer head is unmapped
472 * It returns the error in case of allocation failure.
474 int ext4_map_blocks(handle_t *handle, struct inode *inode,
475 struct ext4_map_blocks *map, int flags)
480 ext_debug("ext4_map_blocks(): inode %lu, flag %d, max_blocks %u,"
481 "logical block %lu\n", inode->i_ino, flags, map->m_len,
482 (unsigned long) map->m_lblk);
484 /* We can handle the block number less than EXT_MAX_BLOCKS */
485 if (unlikely(map->m_lblk >= EXT_MAX_BLOCKS))
489 * Try to see if we can get the block without requesting a new
492 down_read((&EXT4_I(inode)->i_data_sem));
493 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
494 retval = ext4_ext_map_blocks(handle, inode, map, flags &
495 EXT4_GET_BLOCKS_KEEP_SIZE);
497 retval = ext4_ind_map_blocks(handle, inode, map, flags &
498 EXT4_GET_BLOCKS_KEEP_SIZE);
500 up_read((&EXT4_I(inode)->i_data_sem));
502 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
503 int ret = check_block_validity(inode, map);
508 /* If it is only a block(s) look up */
509 if ((flags & EXT4_GET_BLOCKS_CREATE) == 0)
513 * Returns if the blocks have already allocated
515 * Note that if blocks have been preallocated
516 * ext4_ext_get_block() returns the create = 0
517 * with buffer head unmapped.
519 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED)
523 * When we call get_blocks without the create flag, the
524 * BH_Unwritten flag could have gotten set if the blocks
525 * requested were part of a uninitialized extent. We need to
526 * clear this flag now that we are committed to convert all or
527 * part of the uninitialized extent to be an initialized
528 * extent. This is because we need to avoid the combination
529 * of BH_Unwritten and BH_Mapped flags being simultaneously
530 * set on the buffer_head.
532 map->m_flags &= ~EXT4_MAP_UNWRITTEN;
535 * New blocks allocate and/or writing to uninitialized extent
536 * will possibly result in updating i_data, so we take
537 * the write lock of i_data_sem, and call get_blocks()
538 * with create == 1 flag.
540 down_write((&EXT4_I(inode)->i_data_sem));
543 * if the caller is from delayed allocation writeout path
544 * we have already reserved fs blocks for allocation
545 * let the underlying get_block() function know to
546 * avoid double accounting
548 if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
549 ext4_set_inode_state(inode, EXT4_STATE_DELALLOC_RESERVED);
551 * We need to check for EXT4 here because migrate
552 * could have changed the inode type in between
554 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
555 retval = ext4_ext_map_blocks(handle, inode, map, flags);
557 retval = ext4_ind_map_blocks(handle, inode, map, flags);
559 if (retval > 0 && map->m_flags & EXT4_MAP_NEW) {
561 * We allocated new blocks which will result in
562 * i_data's format changing. Force the migrate
563 * to fail by clearing migrate flags
565 ext4_clear_inode_state(inode, EXT4_STATE_EXT_MIGRATE);
569 * Update reserved blocks/metadata blocks after successful
570 * block allocation which had been deferred till now. We don't
571 * support fallocate for non extent files. So we can update
572 * reserve space here.
575 (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE))
576 ext4_da_update_reserve_space(inode, retval, 1);
578 if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) {
579 ext4_clear_inode_state(inode, EXT4_STATE_DELALLOC_RESERVED);
581 /* If we have successfully mapped the delayed allocated blocks,
582 * set the BH_Da_Mapped bit on them. Its important to do this
583 * under the protection of i_data_sem.
585 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED)
586 set_buffers_da_mapped(inode, map);
589 up_write((&EXT4_I(inode)->i_data_sem));
590 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
591 int ret = check_block_validity(inode, map);
599 * Update EXT4_MAP_FLAGS in bh->b_state. For buffer heads attached to pages
600 * we have to be careful as someone else may be manipulating b_state as well.
602 static void ext4_update_bh_state(struct buffer_head *bh, unsigned long flags)
604 unsigned long old_state;
605 unsigned long new_state;
607 flags &= EXT4_MAP_FLAGS;
609 /* Dummy buffer_head? Set non-atomically. */
611 bh->b_state = (bh->b_state & ~EXT4_MAP_FLAGS) | flags;
615 * Someone else may be modifying b_state. Be careful! This is ugly but
616 * once we get rid of using bh as a container for mapping information
617 * to pass to / from get_block functions, this can go away.
620 old_state = ACCESS_ONCE(bh->b_state);
621 new_state = (old_state & ~EXT4_MAP_FLAGS) | flags;
623 cmpxchg(&bh->b_state, old_state, new_state) != old_state));
626 /* Maximum number of blocks we map for direct IO at once. */
627 #define DIO_MAX_BLOCKS 4096
629 static int _ext4_get_block(struct inode *inode, sector_t iblock,
630 struct buffer_head *bh, int flags)
632 handle_t *handle = ext4_journal_current_handle();
633 struct ext4_map_blocks map;
634 int ret = 0, started = 0;
638 map.m_len = bh->b_size >> inode->i_blkbits;
640 if (flags && !handle) {
641 /* Direct IO write... */
642 if (map.m_len > DIO_MAX_BLOCKS)
643 map.m_len = DIO_MAX_BLOCKS;
644 dio_credits = ext4_chunk_trans_blocks(inode, map.m_len);
645 handle = ext4_journal_start(inode, dio_credits);
646 if (IS_ERR(handle)) {
647 ret = PTR_ERR(handle);
653 ret = ext4_map_blocks(handle, inode, &map, flags);
655 map_bh(bh, inode->i_sb, map.m_pblk);
656 ext4_update_bh_state(bh, map.m_flags);
657 bh->b_size = inode->i_sb->s_blocksize * map.m_len;
661 ext4_journal_stop(handle);
665 int ext4_get_block(struct inode *inode, sector_t iblock,
666 struct buffer_head *bh, int create)
668 return _ext4_get_block(inode, iblock, bh,
669 create ? EXT4_GET_BLOCKS_CREATE : 0);
673 * `handle' can be NULL if create is zero
675 struct buffer_head *ext4_getblk(handle_t *handle, struct inode *inode,
676 ext4_lblk_t block, int create, int *errp)
678 struct ext4_map_blocks map;
679 struct buffer_head *bh;
682 J_ASSERT(handle != NULL || create == 0);
686 err = ext4_map_blocks(handle, inode, &map,
687 create ? EXT4_GET_BLOCKS_CREATE : 0);
695 bh = sb_getblk(inode->i_sb, map.m_pblk);
700 if (map.m_flags & EXT4_MAP_NEW) {
701 J_ASSERT(create != 0);
702 J_ASSERT(handle != NULL);
705 * Now that we do not always journal data, we should
706 * keep in mind whether this should always journal the
707 * new buffer as metadata. For now, regular file
708 * writes use ext4_get_block instead, so it's not a
712 BUFFER_TRACE(bh, "call get_create_access");
713 fatal = ext4_journal_get_create_access(handle, bh);
714 if (!fatal && !buffer_uptodate(bh)) {
715 memset(bh->b_data, 0, inode->i_sb->s_blocksize);
716 set_buffer_uptodate(bh);
719 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
720 err = ext4_handle_dirty_metadata(handle, inode, bh);
724 BUFFER_TRACE(bh, "not a new buffer");
734 struct buffer_head *ext4_bread(handle_t *handle, struct inode *inode,
735 ext4_lblk_t block, int create, int *err)
737 struct buffer_head *bh;
739 bh = ext4_getblk(handle, inode, block, create, err);
742 if (buffer_uptodate(bh))
744 ll_rw_block(READ | REQ_META | REQ_PRIO, 1, &bh);
746 if (buffer_uptodate(bh))
753 static int walk_page_buffers(handle_t *handle,
754 struct buffer_head *head,
758 int (*fn)(handle_t *handle,
759 struct buffer_head *bh))
761 struct buffer_head *bh;
762 unsigned block_start, block_end;
763 unsigned blocksize = head->b_size;
765 struct buffer_head *next;
767 for (bh = head, block_start = 0;
768 ret == 0 && (bh != head || !block_start);
769 block_start = block_end, bh = next) {
770 next = bh->b_this_page;
771 block_end = block_start + blocksize;
772 if (block_end <= from || block_start >= to) {
773 if (partial && !buffer_uptodate(bh))
777 err = (*fn)(handle, bh);
785 * To preserve ordering, it is essential that the hole instantiation and
786 * the data write be encapsulated in a single transaction. We cannot
787 * close off a transaction and start a new one between the ext4_get_block()
788 * and the commit_write(). So doing the jbd2_journal_start at the start of
789 * prepare_write() is the right place.
791 * Also, this function can nest inside ext4_writepage() ->
792 * block_write_full_page(). In that case, we *know* that ext4_writepage()
793 * has generated enough buffer credits to do the whole page. So we won't
794 * block on the journal in that case, which is good, because the caller may
797 * By accident, ext4 can be reentered when a transaction is open via
798 * quota file writes. If we were to commit the transaction while thus
799 * reentered, there can be a deadlock - we would be holding a quota
800 * lock, and the commit would never complete if another thread had a
801 * transaction open and was blocking on the quota lock - a ranking
804 * So what we do is to rely on the fact that jbd2_journal_stop/journal_start
805 * will _not_ run commit under these circumstances because handle->h_ref
806 * is elevated. We'll still have enough credits for the tiny quotafile
809 static int do_journal_get_write_access(handle_t *handle,
810 struct buffer_head *bh)
812 int dirty = buffer_dirty(bh);
815 if (!buffer_mapped(bh) || buffer_freed(bh))
818 * __block_write_begin() could have dirtied some buffers. Clean
819 * the dirty bit as jbd2_journal_get_write_access() could complain
820 * otherwise about fs integrity issues. Setting of the dirty bit
821 * by __block_write_begin() isn't a real problem here as we clear
822 * the bit before releasing a page lock and thus writeback cannot
823 * ever write the buffer.
826 clear_buffer_dirty(bh);
827 ret = ext4_journal_get_write_access(handle, bh);
829 ret = ext4_handle_dirty_metadata(handle, NULL, bh);
833 static int ext4_get_block_write(struct inode *inode, sector_t iblock,
834 struct buffer_head *bh_result, int create);
835 static int ext4_write_begin(struct file *file, struct address_space *mapping,
836 loff_t pos, unsigned len, unsigned flags,
837 struct page **pagep, void **fsdata)
839 struct inode *inode = mapping->host;
840 int ret, needed_blocks;
847 trace_ext4_write_begin(inode, pos, len, flags);
849 * Reserve one block more for addition to orphan list in case
850 * we allocate blocks but write fails for some reason
852 needed_blocks = ext4_writepage_trans_blocks(inode) + 1;
853 index = pos >> PAGE_CACHE_SHIFT;
854 from = pos & (PAGE_CACHE_SIZE - 1);
858 handle = ext4_journal_start(inode, needed_blocks);
859 if (IS_ERR(handle)) {
860 ret = PTR_ERR(handle);
864 /* We cannot recurse into the filesystem as the transaction is already
866 flags |= AOP_FLAG_NOFS;
868 page = grab_cache_page_write_begin(mapping, index, flags);
870 ext4_journal_stop(handle);
876 if (ext4_should_dioread_nolock(inode))
877 ret = __block_write_begin(page, pos, len, ext4_get_block_write);
879 ret = __block_write_begin(page, pos, len, ext4_get_block);
881 if (!ret && ext4_should_journal_data(inode)) {
882 ret = walk_page_buffers(handle, page_buffers(page),
883 from, to, NULL, do_journal_get_write_access);
888 page_cache_release(page);
890 * __block_write_begin may have instantiated a few blocks
891 * outside i_size. Trim these off again. Don't need
892 * i_size_read because we hold i_mutex.
894 * Add inode to orphan list in case we crash before
897 if (pos + len > inode->i_size && ext4_can_truncate(inode))
898 ext4_orphan_add(handle, inode);
900 ext4_journal_stop(handle);
901 if (pos + len > inode->i_size) {
902 ext4_truncate_failed_write(inode);
904 * If truncate failed early the inode might
905 * still be on the orphan list; we need to
906 * make sure the inode is removed from the
907 * orphan list in that case.
910 ext4_orphan_del(NULL, inode);
914 if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
920 /* For write_end() in data=journal mode */
921 static int write_end_fn(handle_t *handle, struct buffer_head *bh)
923 if (!buffer_mapped(bh) || buffer_freed(bh))
925 set_buffer_uptodate(bh);
926 return ext4_handle_dirty_metadata(handle, NULL, bh);
929 static int ext4_generic_write_end(struct file *file,
930 struct address_space *mapping,
931 loff_t pos, unsigned len, unsigned copied,
932 struct page *page, void *fsdata)
934 int i_size_changed = 0;
935 struct inode *inode = mapping->host;
936 handle_t *handle = ext4_journal_current_handle();
938 copied = block_write_end(file, mapping, pos, len, copied, page, fsdata);
941 * No need to use i_size_read() here, the i_size
942 * cannot change under us because we hold i_mutex.
944 * But it's important to update i_size while still holding page lock:
945 * page writeout could otherwise come in and zero beyond i_size.
947 if (pos + copied > inode->i_size) {
948 i_size_write(inode, pos + copied);
952 if (pos + copied > EXT4_I(inode)->i_disksize) {
953 /* We need to mark inode dirty even if
954 * new_i_size is less that inode->i_size
955 * bu greater than i_disksize.(hint delalloc)
957 ext4_update_i_disksize(inode, (pos + copied));
961 page_cache_release(page);
964 * Don't mark the inode dirty under page lock. First, it unnecessarily
965 * makes the holding time of page lock longer. Second, it forces lock
966 * ordering of page lock and transaction start for journaling
970 ext4_mark_inode_dirty(handle, inode);
976 * We need to pick up the new inode size which generic_commit_write gave us
977 * `file' can be NULL - eg, when called from page_symlink().
979 * ext4 never places buffers on inode->i_mapping->private_list. metadata
980 * buffers are managed internally.
982 static int ext4_ordered_write_end(struct file *file,
983 struct address_space *mapping,
984 loff_t pos, unsigned len, unsigned copied,
985 struct page *page, void *fsdata)
987 handle_t *handle = ext4_journal_current_handle();
988 struct inode *inode = mapping->host;
991 trace_ext4_ordered_write_end(inode, pos, len, copied);
992 ret = ext4_jbd2_file_inode(handle, inode);
995 ret2 = ext4_generic_write_end(file, mapping, pos, len, copied,
998 if (pos + len > inode->i_size && ext4_can_truncate(inode))
999 /* if we have allocated more blocks and copied
1000 * less. We will have blocks allocated outside
1001 * inode->i_size. So truncate them
1003 ext4_orphan_add(handle, inode);
1008 page_cache_release(page);
1011 ret2 = ext4_journal_stop(handle);
1015 if (pos + len > inode->i_size) {
1016 ext4_truncate_failed_write(inode);
1018 * If truncate failed early the inode might still be
1019 * on the orphan list; we need to make sure the inode
1020 * is removed from the orphan list in that case.
1023 ext4_orphan_del(NULL, inode);
1027 return ret ? ret : copied;
1030 static int ext4_writeback_write_end(struct file *file,
1031 struct address_space *mapping,
1032 loff_t pos, unsigned len, unsigned copied,
1033 struct page *page, void *fsdata)
1035 handle_t *handle = ext4_journal_current_handle();
1036 struct inode *inode = mapping->host;
1039 trace_ext4_writeback_write_end(inode, pos, len, copied);
1040 ret2 = ext4_generic_write_end(file, mapping, pos, len, copied,
1043 if (pos + len > inode->i_size && ext4_can_truncate(inode))
1044 /* if we have allocated more blocks and copied
1045 * less. We will have blocks allocated outside
1046 * inode->i_size. So truncate them
1048 ext4_orphan_add(handle, inode);
1053 ret2 = ext4_journal_stop(handle);
1057 if (pos + len > inode->i_size) {
1058 ext4_truncate_failed_write(inode);
1060 * If truncate failed early the inode might still be
1061 * on the orphan list; we need to make sure the inode
1062 * is removed from the orphan list in that case.
1065 ext4_orphan_del(NULL, inode);
1068 return ret ? ret : copied;
1071 static int ext4_journalled_write_end(struct file *file,
1072 struct address_space *mapping,
1073 loff_t pos, unsigned len, unsigned copied,
1074 struct page *page, void *fsdata)
1076 handle_t *handle = ext4_journal_current_handle();
1077 struct inode *inode = mapping->host;
1083 trace_ext4_journalled_write_end(inode, pos, len, copied);
1084 from = pos & (PAGE_CACHE_SIZE - 1);
1087 BUG_ON(!ext4_handle_valid(handle));
1090 if (!PageUptodate(page))
1092 page_zero_new_buffers(page, from+copied, to);
1095 ret = walk_page_buffers(handle, page_buffers(page), from,
1096 to, &partial, write_end_fn);
1098 SetPageUptodate(page);
1099 new_i_size = pos + copied;
1100 if (new_i_size > inode->i_size)
1101 i_size_write(inode, pos+copied);
1102 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
1103 EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
1104 if (new_i_size > EXT4_I(inode)->i_disksize) {
1105 ext4_update_i_disksize(inode, new_i_size);
1106 ret2 = ext4_mark_inode_dirty(handle, inode);
1112 page_cache_release(page);
1113 if (pos + len > inode->i_size && ext4_can_truncate(inode))
1114 /* if we have allocated more blocks and copied
1115 * less. We will have blocks allocated outside
1116 * inode->i_size. So truncate them
1118 ext4_orphan_add(handle, inode);
1120 ret2 = ext4_journal_stop(handle);
1123 if (pos + len > inode->i_size) {
1124 ext4_truncate_failed_write(inode);
1126 * If truncate failed early the inode might still be
1127 * on the orphan list; we need to make sure the inode
1128 * is removed from the orphan list in that case.
1131 ext4_orphan_del(NULL, inode);
1134 return ret ? ret : copied;
1138 * Reserve a single cluster located at lblock
1140 static int ext4_da_reserve_space(struct inode *inode, ext4_lblk_t lblock)
1143 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1144 struct ext4_inode_info *ei = EXT4_I(inode);
1145 unsigned int md_needed;
1147 ext4_lblk_t save_last_lblock;
1151 * We will charge metadata quota at writeout time; this saves
1152 * us from metadata over-estimation, though we may go over by
1153 * a small amount in the end. Here we just reserve for data.
1155 ret = dquot_reserve_block(inode, EXT4_C2B(sbi, 1));
1160 * recalculate the amount of metadata blocks to reserve
1161 * in order to allocate nrblocks
1162 * worse case is one extent per block
1165 spin_lock(&ei->i_block_reservation_lock);
1167 * ext4_calc_metadata_amount() has side effects, which we have
1168 * to be prepared undo if we fail to claim space.
1170 save_len = ei->i_da_metadata_calc_len;
1171 save_last_lblock = ei->i_da_metadata_calc_last_lblock;
1172 md_needed = EXT4_NUM_B2C(sbi,
1173 ext4_calc_metadata_amount(inode, lblock));
1174 trace_ext4_da_reserve_space(inode, md_needed);
1177 * We do still charge estimated metadata to the sb though;
1178 * we cannot afford to run out of free blocks.
1180 if (ext4_claim_free_clusters(sbi, md_needed + 1, 0)) {
1181 ei->i_da_metadata_calc_len = save_len;
1182 ei->i_da_metadata_calc_last_lblock = save_last_lblock;
1183 spin_unlock(&ei->i_block_reservation_lock);
1184 if (ext4_should_retry_alloc(inode->i_sb, &retries)) {
1188 dquot_release_reservation_block(inode, EXT4_C2B(sbi, 1));
1191 ei->i_reserved_data_blocks++;
1192 ei->i_reserved_meta_blocks += md_needed;
1193 spin_unlock(&ei->i_block_reservation_lock);
1195 return 0; /* success */
1198 static void ext4_da_release_space(struct inode *inode, int to_free)
1200 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1201 struct ext4_inode_info *ei = EXT4_I(inode);
1204 return; /* Nothing to release, exit */
1206 spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
1208 trace_ext4_da_release_space(inode, to_free);
1209 if (unlikely(to_free > ei->i_reserved_data_blocks)) {
1211 * if there aren't enough reserved blocks, then the
1212 * counter is messed up somewhere. Since this
1213 * function is called from invalidate page, it's
1214 * harmless to return without any action.
1216 ext4_msg(inode->i_sb, KERN_NOTICE, "ext4_da_release_space: "
1217 "ino %lu, to_free %d with only %d reserved "
1218 "data blocks\n", inode->i_ino, to_free,
1219 ei->i_reserved_data_blocks);
1221 to_free = ei->i_reserved_data_blocks;
1223 ei->i_reserved_data_blocks -= to_free;
1225 if (ei->i_reserved_data_blocks == 0) {
1227 * We can release all of the reserved metadata blocks
1228 * only when we have written all of the delayed
1229 * allocation blocks.
1230 * Note that in case of bigalloc, i_reserved_meta_blocks,
1231 * i_reserved_data_blocks, etc. refer to number of clusters.
1233 percpu_counter_sub(&sbi->s_dirtyclusters_counter,
1234 ei->i_reserved_meta_blocks);
1235 ei->i_reserved_meta_blocks = 0;
1236 ei->i_da_metadata_calc_len = 0;
1239 /* update fs dirty data blocks counter */
1240 percpu_counter_sub(&sbi->s_dirtyclusters_counter, to_free);
1242 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
1244 dquot_release_reservation_block(inode, EXT4_C2B(sbi, to_free));
1247 static void ext4_da_page_release_reservation(struct page *page,
1248 unsigned long offset)
1251 struct buffer_head *head, *bh;
1252 unsigned int curr_off = 0;
1253 struct inode *inode = page->mapping->host;
1254 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1257 head = page_buffers(page);
1260 unsigned int next_off = curr_off + bh->b_size;
1262 if ((offset <= curr_off) && (buffer_delay(bh))) {
1264 clear_buffer_delay(bh);
1265 clear_buffer_da_mapped(bh);
1267 curr_off = next_off;
1268 } while ((bh = bh->b_this_page) != head);
1270 /* If we have released all the blocks belonging to a cluster, then we
1271 * need to release the reserved space for that cluster. */
1272 num_clusters = EXT4_NUM_B2C(sbi, to_release);
1273 while (num_clusters > 0) {
1275 lblk = (page->index << (PAGE_CACHE_SHIFT - inode->i_blkbits)) +
1276 ((num_clusters - 1) << sbi->s_cluster_bits);
1277 if (sbi->s_cluster_ratio == 1 ||
1278 !ext4_find_delalloc_cluster(inode, lblk, 1))
1279 ext4_da_release_space(inode, 1);
1286 * Delayed allocation stuff
1290 * mpage_da_submit_io - walks through extent of pages and try to write
1291 * them with writepage() call back
1293 * @mpd->inode: inode
1294 * @mpd->first_page: first page of the extent
1295 * @mpd->next_page: page after the last page of the extent
1297 * By the time mpage_da_submit_io() is called we expect all blocks
1298 * to be allocated. this may be wrong if allocation failed.
1300 * As pages are already locked by write_cache_pages(), we can't use it
1302 static int mpage_da_submit_io(struct mpage_da_data *mpd,
1303 struct ext4_map_blocks *map)
1305 struct pagevec pvec;
1306 unsigned long index, end;
1307 int ret = 0, err, nr_pages, i;
1308 struct inode *inode = mpd->inode;
1309 struct address_space *mapping = inode->i_mapping;
1310 loff_t size = i_size_read(inode);
1311 unsigned int len, block_start;
1312 struct buffer_head *bh, *page_bufs = NULL;
1313 int journal_data = ext4_should_journal_data(inode);
1314 sector_t pblock = 0, cur_logical = 0;
1315 struct ext4_io_submit io_submit;
1317 BUG_ON(mpd->next_page <= mpd->first_page);
1318 memset(&io_submit, 0, sizeof(io_submit));
1320 * We need to start from the first_page to the next_page - 1
1321 * to make sure we also write the mapped dirty buffer_heads.
1322 * If we look at mpd->b_blocknr we would only be looking
1323 * at the currently mapped buffer_heads.
1325 index = mpd->first_page;
1326 end = mpd->next_page - 1;
1328 pagevec_init(&pvec, 0);
1329 while (index <= end) {
1330 nr_pages = pagevec_lookup(&pvec, mapping, index, PAGEVEC_SIZE);
1333 for (i = 0; i < nr_pages; i++) {
1334 int commit_write = 0, skip_page = 0;
1335 struct page *page = pvec.pages[i];
1337 index = page->index;
1341 if (index == size >> PAGE_CACHE_SHIFT)
1342 len = size & ~PAGE_CACHE_MASK;
1344 len = PAGE_CACHE_SIZE;
1346 cur_logical = index << (PAGE_CACHE_SHIFT -
1348 pblock = map->m_pblk + (cur_logical -
1353 BUG_ON(!PageLocked(page));
1354 BUG_ON(PageWriteback(page));
1357 * If the page does not have buffers (for
1358 * whatever reason), try to create them using
1359 * __block_write_begin. If this fails,
1360 * skip the page and move on.
1362 if (!page_has_buffers(page)) {
1363 if (__block_write_begin(page, 0, len,
1364 noalloc_get_block_write)) {
1372 bh = page_bufs = page_buffers(page);
1377 if (map && (cur_logical >= map->m_lblk) &&
1378 (cur_logical <= (map->m_lblk +
1379 (map->m_len - 1)))) {
1380 if (buffer_delay(bh)) {
1381 clear_buffer_delay(bh);
1382 bh->b_blocknr = pblock;
1384 if (buffer_da_mapped(bh))
1385 clear_buffer_da_mapped(bh);
1386 if (buffer_unwritten(bh) ||
1388 BUG_ON(bh->b_blocknr != pblock);
1389 if (map->m_flags & EXT4_MAP_UNINIT)
1390 set_buffer_uninit(bh);
1391 clear_buffer_unwritten(bh);
1395 * skip page if block allocation undone and
1398 if (ext4_bh_delay_or_unwritten(NULL, bh))
1400 bh = bh->b_this_page;
1401 block_start += bh->b_size;
1404 } while (bh != page_bufs);
1410 /* mark the buffer_heads as dirty & uptodate */
1411 block_commit_write(page, 0, len);
1413 clear_page_dirty_for_io(page);
1415 * Delalloc doesn't support data journalling,
1416 * but eventually maybe we'll lift this
1419 if (unlikely(journal_data && PageChecked(page)))
1420 err = __ext4_journalled_writepage(page, len);
1421 else if (test_opt(inode->i_sb, MBLK_IO_SUBMIT))
1422 err = ext4_bio_write_page(&io_submit, page,
1424 else if (buffer_uninit(page_bufs)) {
1425 ext4_set_bh_endio(page_bufs, inode);
1426 err = block_write_full_page_endio(page,
1427 noalloc_get_block_write,
1428 mpd->wbc, ext4_end_io_buffer_write);
1430 err = block_write_full_page(page,
1431 noalloc_get_block_write, mpd->wbc);
1434 mpd->pages_written++;
1436 * In error case, we have to continue because
1437 * remaining pages are still locked
1442 pagevec_release(&pvec);
1444 ext4_io_submit(&io_submit);
1448 static void ext4_da_block_invalidatepages(struct mpage_da_data *mpd)
1452 struct pagevec pvec;
1453 struct inode *inode = mpd->inode;
1454 struct address_space *mapping = inode->i_mapping;
1456 index = mpd->first_page;
1457 end = mpd->next_page - 1;
1458 pagevec_init(&pvec, 0);
1459 while (index <= end) {
1460 nr_pages = pagevec_lookup(&pvec, mapping, index, PAGEVEC_SIZE);
1463 for (i = 0; i < nr_pages; i++) {
1464 struct page *page = pvec.pages[i];
1465 if (page->index > end)
1467 BUG_ON(!PageLocked(page));
1468 BUG_ON(PageWriteback(page));
1469 block_invalidatepage(page, 0);
1470 ClearPageUptodate(page);
1473 index = pvec.pages[nr_pages - 1]->index + 1;
1474 pagevec_release(&pvec);
1479 static void ext4_print_free_blocks(struct inode *inode)
1481 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1482 printk(KERN_CRIT "Total free blocks count %lld\n",
1483 EXT4_C2B(EXT4_SB(inode->i_sb),
1484 ext4_count_free_clusters(inode->i_sb)));
1485 printk(KERN_CRIT "Free/Dirty block details\n");
1486 printk(KERN_CRIT "free_blocks=%lld\n",
1487 (long long) EXT4_C2B(EXT4_SB(inode->i_sb),
1488 percpu_counter_sum(&sbi->s_freeclusters_counter)));
1489 printk(KERN_CRIT "dirty_blocks=%lld\n",
1490 (long long) EXT4_C2B(EXT4_SB(inode->i_sb),
1491 percpu_counter_sum(&sbi->s_dirtyclusters_counter)));
1492 printk(KERN_CRIT "Block reservation details\n");
1493 printk(KERN_CRIT "i_reserved_data_blocks=%u\n",
1494 EXT4_I(inode)->i_reserved_data_blocks);
1495 printk(KERN_CRIT "i_reserved_meta_blocks=%u\n",
1496 EXT4_I(inode)->i_reserved_meta_blocks);
1501 * mpage_da_map_and_submit - go through given space, map them
1502 * if necessary, and then submit them for I/O
1504 * @mpd - bh describing space
1506 * The function skips space we know is already mapped to disk blocks.
1509 static void mpage_da_map_and_submit(struct mpage_da_data *mpd)
1511 int err, blks, get_blocks_flags;
1512 struct ext4_map_blocks map, *mapp = NULL;
1513 sector_t next = mpd->b_blocknr;
1514 unsigned max_blocks = mpd->b_size >> mpd->inode->i_blkbits;
1515 loff_t disksize = EXT4_I(mpd->inode)->i_disksize;
1516 handle_t *handle = NULL;
1519 * If the blocks are mapped already, or we couldn't accumulate
1520 * any blocks, then proceed immediately to the submission stage.
1522 if ((mpd->b_size == 0) ||
1523 ((mpd->b_state & (1 << BH_Mapped)) &&
1524 !(mpd->b_state & (1 << BH_Delay)) &&
1525 !(mpd->b_state & (1 << BH_Unwritten))))
1528 handle = ext4_journal_current_handle();
1532 * Call ext4_map_blocks() to allocate any delayed allocation
1533 * blocks, or to convert an uninitialized extent to be
1534 * initialized (in the case where we have written into
1535 * one or more preallocated blocks).
1537 * We pass in the magic EXT4_GET_BLOCKS_DELALLOC_RESERVE to
1538 * indicate that we are on the delayed allocation path. This
1539 * affects functions in many different parts of the allocation
1540 * call path. This flag exists primarily because we don't
1541 * want to change *many* call functions, so ext4_map_blocks()
1542 * will set the EXT4_STATE_DELALLOC_RESERVED flag once the
1543 * inode's allocation semaphore is taken.
1545 * If the blocks in questions were delalloc blocks, set
1546 * EXT4_GET_BLOCKS_DELALLOC_RESERVE so the delalloc accounting
1547 * variables are updated after the blocks have been allocated.
1550 map.m_len = max_blocks;
1551 get_blocks_flags = EXT4_GET_BLOCKS_CREATE;
1552 if (ext4_should_dioread_nolock(mpd->inode))
1553 get_blocks_flags |= EXT4_GET_BLOCKS_IO_CREATE_EXT;
1554 if (mpd->b_state & (1 << BH_Delay))
1555 get_blocks_flags |= EXT4_GET_BLOCKS_DELALLOC_RESERVE;
1557 blks = ext4_map_blocks(handle, mpd->inode, &map, get_blocks_flags);
1559 struct super_block *sb = mpd->inode->i_sb;
1563 * If get block returns EAGAIN or ENOSPC and there
1564 * appears to be free blocks we will just let
1565 * mpage_da_submit_io() unlock all of the pages.
1570 if (err == -ENOSPC && ext4_count_free_clusters(sb)) {
1576 * get block failure will cause us to loop in
1577 * writepages, because a_ops->writepage won't be able
1578 * to make progress. The page will be redirtied by
1579 * writepage and writepages will again try to write
1582 if (!(EXT4_SB(sb)->s_mount_flags & EXT4_MF_FS_ABORTED)) {
1583 ext4_msg(sb, KERN_CRIT,
1584 "delayed block allocation failed for inode %lu "
1585 "at logical offset %llu with max blocks %zd "
1586 "with error %d", mpd->inode->i_ino,
1587 (unsigned long long) next,
1588 mpd->b_size >> mpd->inode->i_blkbits, err);
1589 ext4_msg(sb, KERN_CRIT,
1590 "This should not happen!! Data will be lost\n");
1592 ext4_print_free_blocks(mpd->inode);
1594 /* invalidate all the pages */
1595 ext4_da_block_invalidatepages(mpd);
1597 /* Mark this page range as having been completed */
1604 if (map.m_flags & EXT4_MAP_NEW) {
1605 struct block_device *bdev = mpd->inode->i_sb->s_bdev;
1608 for (i = 0; i < map.m_len; i++)
1609 unmap_underlying_metadata(bdev, map.m_pblk + i);
1611 if (ext4_should_order_data(mpd->inode)) {
1612 err = ext4_jbd2_file_inode(handle, mpd->inode);
1614 /* Only if the journal is aborted */
1622 * Update on-disk size along with block allocation.
1624 disksize = ((loff_t) next + blks) << mpd->inode->i_blkbits;
1625 if (disksize > i_size_read(mpd->inode))
1626 disksize = i_size_read(mpd->inode);
1627 if (disksize > EXT4_I(mpd->inode)->i_disksize) {
1628 ext4_update_i_disksize(mpd->inode, disksize);
1629 err = ext4_mark_inode_dirty(handle, mpd->inode);
1631 ext4_error(mpd->inode->i_sb,
1632 "Failed to mark inode %lu dirty",
1637 mpage_da_submit_io(mpd, mapp);
1641 #define BH_FLAGS ((1 << BH_Uptodate) | (1 << BH_Mapped) | \
1642 (1 << BH_Delay) | (1 << BH_Unwritten))
1645 * mpage_add_bh_to_extent - try to add one more block to extent of blocks
1647 * @mpd->lbh - extent of blocks
1648 * @logical - logical number of the block in the file
1649 * @bh - bh of the block (used to access block's state)
1651 * the function is used to collect contig. blocks in same state
1653 static void mpage_add_bh_to_extent(struct mpage_da_data *mpd,
1654 sector_t logical, size_t b_size,
1655 unsigned long b_state)
1658 int nrblocks = mpd->b_size >> mpd->inode->i_blkbits;
1661 * XXX Don't go larger than mballoc is willing to allocate
1662 * This is a stopgap solution. We eventually need to fold
1663 * mpage_da_submit_io() into this function and then call
1664 * ext4_map_blocks() multiple times in a loop
1666 if (nrblocks >= 8*1024*1024/mpd->inode->i_sb->s_blocksize)
1669 /* check if thereserved journal credits might overflow */
1670 if (!(ext4_test_inode_flag(mpd->inode, EXT4_INODE_EXTENTS))) {
1671 if (nrblocks >= EXT4_MAX_TRANS_DATA) {
1673 * With non-extent format we are limited by the journal
1674 * credit available. Total credit needed to insert
1675 * nrblocks contiguous blocks is dependent on the
1676 * nrblocks. So limit nrblocks.
1679 } else if ((nrblocks + (b_size >> mpd->inode->i_blkbits)) >
1680 EXT4_MAX_TRANS_DATA) {
1682 * Adding the new buffer_head would make it cross the
1683 * allowed limit for which we have journal credit
1684 * reserved. So limit the new bh->b_size
1686 b_size = (EXT4_MAX_TRANS_DATA - nrblocks) <<
1687 mpd->inode->i_blkbits;
1688 /* we will do mpage_da_submit_io in the next loop */
1692 * First block in the extent
1694 if (mpd->b_size == 0) {
1695 mpd->b_blocknr = logical;
1696 mpd->b_size = b_size;
1697 mpd->b_state = b_state & BH_FLAGS;
1701 next = mpd->b_blocknr + nrblocks;
1703 * Can we merge the block to our big extent?
1705 if (logical == next && (b_state & BH_FLAGS) == mpd->b_state) {
1706 mpd->b_size += b_size;
1712 * We couldn't merge the block to our extent, so we
1713 * need to flush current extent and start new one
1715 mpage_da_map_and_submit(mpd);
1719 static int ext4_bh_delay_or_unwritten(handle_t *handle, struct buffer_head *bh)
1721 return (buffer_delay(bh) || buffer_unwritten(bh)) && buffer_dirty(bh);
1725 * This function is grabs code from the very beginning of
1726 * ext4_map_blocks, but assumes that the caller is from delayed write
1727 * time. This function looks up the requested blocks and sets the
1728 * buffer delay bit under the protection of i_data_sem.
1730 static int ext4_da_map_blocks(struct inode *inode, sector_t iblock,
1731 struct ext4_map_blocks *map,
1732 struct buffer_head *bh)
1735 sector_t invalid_block = ~((sector_t) 0xffff);
1737 if (invalid_block < ext4_blocks_count(EXT4_SB(inode->i_sb)->s_es))
1741 ext_debug("ext4_da_map_blocks(): inode %lu, max_blocks %u,"
1742 "logical block %lu\n", inode->i_ino, map->m_len,
1743 (unsigned long) map->m_lblk);
1745 * Try to see if we can get the block without requesting a new
1746 * file system block.
1748 down_read((&EXT4_I(inode)->i_data_sem));
1749 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
1750 retval = ext4_ext_map_blocks(NULL, inode, map, 0);
1752 retval = ext4_ind_map_blocks(NULL, inode, map, 0);
1756 * XXX: __block_prepare_write() unmaps passed block,
1759 /* If the block was allocated from previously allocated cluster,
1760 * then we dont need to reserve it again. */
1761 if (!(map->m_flags & EXT4_MAP_FROM_CLUSTER)) {
1762 retval = ext4_da_reserve_space(inode, iblock);
1764 /* not enough space to reserve */
1768 /* Clear EXT4_MAP_FROM_CLUSTER flag since its purpose is served
1769 * and it should not appear on the bh->b_state.
1771 map->m_flags &= ~EXT4_MAP_FROM_CLUSTER;
1773 map_bh(bh, inode->i_sb, invalid_block);
1775 set_buffer_delay(bh);
1779 up_read((&EXT4_I(inode)->i_data_sem));
1785 * This is a special get_blocks_t callback which is used by
1786 * ext4_da_write_begin(). It will either return mapped block or
1787 * reserve space for a single block.
1789 * For delayed buffer_head we have BH_Mapped, BH_New, BH_Delay set.
1790 * We also have b_blocknr = -1 and b_bdev initialized properly
1792 * For unwritten buffer_head we have BH_Mapped, BH_New, BH_Unwritten set.
1793 * We also have b_blocknr = physicalblock mapping unwritten extent and b_bdev
1794 * initialized properly.
1796 static int ext4_da_get_block_prep(struct inode *inode, sector_t iblock,
1797 struct buffer_head *bh, int create)
1799 struct ext4_map_blocks map;
1802 BUG_ON(create == 0);
1803 BUG_ON(bh->b_size != inode->i_sb->s_blocksize);
1805 map.m_lblk = iblock;
1809 * first, we need to know whether the block is allocated already
1810 * preallocated blocks are unmapped but should treated
1811 * the same as allocated blocks.
1813 ret = ext4_da_map_blocks(inode, iblock, &map, bh);
1817 map_bh(bh, inode->i_sb, map.m_pblk);
1818 ext4_update_bh_state(bh, map.m_flags);
1820 if (buffer_unwritten(bh)) {
1821 /* A delayed write to unwritten bh should be marked
1822 * new and mapped. Mapped ensures that we don't do
1823 * get_block multiple times when we write to the same
1824 * offset and new ensures that we do proper zero out
1825 * for partial write.
1828 set_buffer_mapped(bh);
1834 * This function is used as a standard get_block_t calback function
1835 * when there is no desire to allocate any blocks. It is used as a
1836 * callback function for block_write_begin() and block_write_full_page().
1837 * These functions should only try to map a single block at a time.
1839 * Since this function doesn't do block allocations even if the caller
1840 * requests it by passing in create=1, it is critically important that
1841 * any caller checks to make sure that any buffer heads are returned
1842 * by this function are either all already mapped or marked for
1843 * delayed allocation before calling block_write_full_page(). Otherwise,
1844 * b_blocknr could be left unitialized, and the page write functions will
1845 * be taken by surprise.
1847 static int noalloc_get_block_write(struct inode *inode, sector_t iblock,
1848 struct buffer_head *bh_result, int create)
1850 BUG_ON(bh_result->b_size != inode->i_sb->s_blocksize);
1851 return _ext4_get_block(inode, iblock, bh_result, 0);
1854 static int bget_one(handle_t *handle, struct buffer_head *bh)
1860 static int bput_one(handle_t *handle, struct buffer_head *bh)
1866 static int __ext4_journalled_writepage(struct page *page,
1869 struct address_space *mapping = page->mapping;
1870 struct inode *inode = mapping->host;
1871 struct buffer_head *page_bufs;
1872 handle_t *handle = NULL;
1876 ClearPageChecked(page);
1877 page_bufs = page_buffers(page);
1879 walk_page_buffers(handle, page_bufs, 0, len, NULL, bget_one);
1881 * We need to release the page lock before we start the
1882 * journal, so grab a reference so the page won't disappear
1883 * out from under us.
1888 handle = ext4_journal_start(inode, ext4_writepage_trans_blocks(inode));
1889 if (IS_ERR(handle)) {
1890 ret = PTR_ERR(handle);
1892 goto out_no_pagelock;
1894 BUG_ON(!ext4_handle_valid(handle));
1898 if (page->mapping != mapping) {
1899 /* The page got truncated from under us */
1900 ext4_journal_stop(handle);
1905 ret = walk_page_buffers(handle, page_bufs, 0, len, NULL,
1906 do_journal_get_write_access);
1908 err = walk_page_buffers(handle, page_bufs, 0, len, NULL,
1912 EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
1913 err = ext4_journal_stop(handle);
1917 walk_page_buffers(handle, page_bufs, 0, len, NULL, bput_one);
1918 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
1925 static int ext4_set_bh_endio(struct buffer_head *bh, struct inode *inode);
1926 static void ext4_end_io_buffer_write(struct buffer_head *bh, int uptodate);
1929 * Note that we don't need to start a transaction unless we're journaling data
1930 * because we should have holes filled from ext4_page_mkwrite(). We even don't
1931 * need to file the inode to the transaction's list in ordered mode because if
1932 * we are writing back data added by write(), the inode is already there and if
1933 * we are writing back data modified via mmap(), no one guarantees in which
1934 * transaction the data will hit the disk. In case we are journaling data, we
1935 * cannot start transaction directly because transaction start ranks above page
1936 * lock so we have to do some magic.
1938 * This function can get called via...
1939 * - ext4_da_writepages after taking page lock (have journal handle)
1940 * - journal_submit_inode_data_buffers (no journal handle)
1941 * - shrink_page_list via pdflush (no journal handle)
1942 * - grab_page_cache when doing write_begin (have journal handle)
1944 * We don't do any block allocation in this function. If we have page with
1945 * multiple blocks we need to write those buffer_heads that are mapped. This
1946 * is important for mmaped based write. So if we do with blocksize 1K
1947 * truncate(f, 1024);
1948 * a = mmap(f, 0, 4096);
1950 * truncate(f, 4096);
1951 * we have in the page first buffer_head mapped via page_mkwrite call back
1952 * but other bufer_heads would be unmapped but dirty(dirty done via the
1953 * do_wp_page). So writepage should write the first block. If we modify
1954 * the mmap area beyond 1024 we will again get a page_fault and the
1955 * page_mkwrite callback will do the block allocation and mark the
1956 * buffer_heads mapped.
1958 * We redirty the page if we have any buffer_heads that is either delay or
1959 * unwritten in the page.
1961 * We can get recursively called as show below.
1963 * ext4_writepage() -> kmalloc() -> __alloc_pages() -> page_launder() ->
1966 * But since we don't do any block allocation we should not deadlock.
1967 * Page also have the dirty flag cleared so we don't get recurive page_lock.
1969 static int ext4_writepage(struct page *page,
1970 struct writeback_control *wbc)
1972 int ret = 0, commit_write = 0;
1975 struct buffer_head *page_bufs = NULL;
1976 struct inode *inode = page->mapping->host;
1978 trace_ext4_writepage(page);
1979 size = i_size_read(inode);
1980 if (page->index == size >> PAGE_CACHE_SHIFT)
1981 len = size & ~PAGE_CACHE_MASK;
1983 len = PAGE_CACHE_SIZE;
1986 * If the page does not have buffers (for whatever reason),
1987 * try to create them using __block_write_begin. If this
1988 * fails, redirty the page and move on.
1990 if (!page_has_buffers(page)) {
1991 if (__block_write_begin(page, 0, len,
1992 noalloc_get_block_write)) {
1994 redirty_page_for_writepage(wbc, page);
2000 page_bufs = page_buffers(page);
2001 if (walk_page_buffers(NULL, page_bufs, 0, len, NULL,
2002 ext4_bh_delay_or_unwritten)) {
2004 * We don't want to do block allocation, so redirty
2005 * the page and return. We may reach here when we do
2006 * a journal commit via journal_submit_inode_data_buffers.
2007 * We can also reach here via shrink_page_list but it
2008 * should never be for direct reclaim so warn if that
2011 WARN_ON_ONCE((current->flags & (PF_MEMALLOC|PF_KSWAPD)) ==
2016 /* now mark the buffer_heads as dirty and uptodate */
2017 block_commit_write(page, 0, len);
2019 if (PageChecked(page) && ext4_should_journal_data(inode))
2021 * It's mmapped pagecache. Add buffers and journal it. There
2022 * doesn't seem much point in redirtying the page here.
2024 return __ext4_journalled_writepage(page, len);
2026 if (buffer_uninit(page_bufs)) {
2027 ext4_set_bh_endio(page_bufs, inode);
2028 ret = block_write_full_page_endio(page, noalloc_get_block_write,
2029 wbc, ext4_end_io_buffer_write);
2031 ret = block_write_full_page(page, noalloc_get_block_write,
2038 * This is called via ext4_da_writepages() to
2039 * calculate the total number of credits to reserve to fit
2040 * a single extent allocation into a single transaction,
2041 * ext4_da_writpeages() will loop calling this before
2042 * the block allocation.
2045 static int ext4_da_writepages_trans_blocks(struct inode *inode)
2047 int max_blocks = EXT4_I(inode)->i_reserved_data_blocks;
2050 * With non-extent format the journal credit needed to
2051 * insert nrblocks contiguous block is dependent on
2052 * number of contiguous block. So we will limit
2053 * number of contiguous block to a sane value
2055 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) &&
2056 (max_blocks > EXT4_MAX_TRANS_DATA))
2057 max_blocks = EXT4_MAX_TRANS_DATA;
2059 return ext4_chunk_trans_blocks(inode, max_blocks);
2063 * write_cache_pages_da - walk the list of dirty pages of the given
2064 * address space and accumulate pages that need writing, and call
2065 * mpage_da_map_and_submit to map a single contiguous memory region
2066 * and then write them.
2068 static int write_cache_pages_da(struct address_space *mapping,
2069 struct writeback_control *wbc,
2070 struct mpage_da_data *mpd,
2071 pgoff_t *done_index)
2073 struct buffer_head *bh, *head;
2074 struct inode *inode = mapping->host;
2075 struct pagevec pvec;
2076 unsigned int nr_pages;
2079 long nr_to_write = wbc->nr_to_write;
2080 int i, tag, ret = 0;
2082 memset(mpd, 0, sizeof(struct mpage_da_data));
2085 pagevec_init(&pvec, 0);
2086 index = wbc->range_start >> PAGE_CACHE_SHIFT;
2087 end = wbc->range_end >> PAGE_CACHE_SHIFT;
2089 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
2090 tag = PAGECACHE_TAG_TOWRITE;
2092 tag = PAGECACHE_TAG_DIRTY;
2094 *done_index = index;
2095 while (index <= end) {
2096 nr_pages = pagevec_lookup_tag(&pvec, mapping, &index, tag,
2097 min(end - index, (pgoff_t)PAGEVEC_SIZE-1) + 1);
2101 for (i = 0; i < nr_pages; i++) {
2102 struct page *page = pvec.pages[i];
2105 * At this point, the page may be truncated or
2106 * invalidated (changing page->mapping to NULL), or
2107 * even swizzled back from swapper_space to tmpfs file
2108 * mapping. However, page->index will not change
2109 * because we have a reference on the page.
2111 if (page->index > end)
2114 *done_index = page->index + 1;
2117 * If we can't merge this page, and we have
2118 * accumulated an contiguous region, write it
2120 if ((mpd->next_page != page->index) &&
2121 (mpd->next_page != mpd->first_page)) {
2122 mpage_da_map_and_submit(mpd);
2123 goto ret_extent_tail;
2129 * If the page is no longer dirty, or its
2130 * mapping no longer corresponds to inode we
2131 * are writing (which means it has been
2132 * truncated or invalidated), or the page is
2133 * already under writeback and we are not
2134 * doing a data integrity writeback, skip the page
2136 if (!PageDirty(page) ||
2137 (PageWriteback(page) &&
2138 (wbc->sync_mode == WB_SYNC_NONE)) ||
2139 unlikely(page->mapping != mapping)) {
2144 wait_on_page_writeback(page);
2145 BUG_ON(PageWriteback(page));
2147 if (mpd->next_page != page->index)
2148 mpd->first_page = page->index;
2149 mpd->next_page = page->index + 1;
2150 logical = (sector_t) page->index <<
2151 (PAGE_CACHE_SHIFT - inode->i_blkbits);
2153 if (!page_has_buffers(page)) {
2154 mpage_add_bh_to_extent(mpd, logical,
2156 (1 << BH_Dirty) | (1 << BH_Uptodate));
2158 goto ret_extent_tail;
2161 * Page with regular buffer heads,
2162 * just add all dirty ones
2164 head = page_buffers(page);
2167 BUG_ON(buffer_locked(bh));
2169 * We need to try to allocate
2170 * unmapped blocks in the same page.
2171 * Otherwise we won't make progress
2172 * with the page in ext4_writepage
2174 if (ext4_bh_delay_or_unwritten(NULL, bh)) {
2175 mpage_add_bh_to_extent(mpd, logical,
2179 goto ret_extent_tail;
2180 } else if (buffer_dirty(bh) && (buffer_mapped(bh))) {
2182 * mapped dirty buffer. We need
2183 * to update the b_state
2184 * because we look at b_state
2185 * in mpage_da_map_blocks. We
2186 * don't update b_size because
2187 * if we find an unmapped
2188 * buffer_head later we need to
2189 * use the b_state flag of that
2192 if (mpd->b_size == 0)
2193 mpd->b_state = bh->b_state & BH_FLAGS;
2196 } while ((bh = bh->b_this_page) != head);
2199 if (nr_to_write > 0) {
2201 if (nr_to_write == 0 &&
2202 wbc->sync_mode == WB_SYNC_NONE)
2204 * We stop writing back only if we are
2205 * not doing integrity sync. In case of
2206 * integrity sync we have to keep going
2207 * because someone may be concurrently
2208 * dirtying pages, and we might have
2209 * synced a lot of newly appeared dirty
2210 * pages, but have not synced all of the
2216 pagevec_release(&pvec);
2221 ret = MPAGE_DA_EXTENT_TAIL;
2223 pagevec_release(&pvec);
2229 static int ext4_da_writepages(struct address_space *mapping,
2230 struct writeback_control *wbc)
2233 int range_whole = 0;
2234 handle_t *handle = NULL;
2235 struct mpage_da_data mpd;
2236 struct inode *inode = mapping->host;
2237 int pages_written = 0;
2238 unsigned int max_pages;
2239 int range_cyclic, cycled = 1, io_done = 0;
2240 int needed_blocks, ret = 0;
2241 long desired_nr_to_write, nr_to_writebump = 0;
2242 loff_t range_start = wbc->range_start;
2243 struct ext4_sb_info *sbi = EXT4_SB(mapping->host->i_sb);
2244 pgoff_t done_index = 0;
2246 struct blk_plug plug;
2248 trace_ext4_da_writepages(inode, wbc);
2251 * No pages to write? This is mainly a kludge to avoid starting
2252 * a transaction for special inodes like journal inode on last iput()
2253 * because that could violate lock ordering on umount
2255 if (!mapping->nrpages || !mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
2259 * If the filesystem has aborted, it is read-only, so return
2260 * right away instead of dumping stack traces later on that
2261 * will obscure the real source of the problem. We test
2262 * EXT4_MF_FS_ABORTED instead of sb->s_flag's MS_RDONLY because
2263 * the latter could be true if the filesystem is mounted
2264 * read-only, and in that case, ext4_da_writepages should
2265 * *never* be called, so if that ever happens, we would want
2268 if (unlikely(sbi->s_mount_flags & EXT4_MF_FS_ABORTED))
2271 if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
2274 range_cyclic = wbc->range_cyclic;
2275 if (wbc->range_cyclic) {
2276 index = mapping->writeback_index;
2279 wbc->range_start = index << PAGE_CACHE_SHIFT;
2280 wbc->range_end = LLONG_MAX;
2281 wbc->range_cyclic = 0;
2284 index = wbc->range_start >> PAGE_CACHE_SHIFT;
2285 end = wbc->range_end >> PAGE_CACHE_SHIFT;
2289 * This works around two forms of stupidity. The first is in
2290 * the writeback code, which caps the maximum number of pages
2291 * written to be 1024 pages. This is wrong on multiple
2292 * levels; different architectues have a different page size,
2293 * which changes the maximum amount of data which gets
2294 * written. Secondly, 4 megabytes is way too small. XFS
2295 * forces this value to be 16 megabytes by multiplying
2296 * nr_to_write parameter by four, and then relies on its
2297 * allocator to allocate larger extents to make them
2298 * contiguous. Unfortunately this brings us to the second
2299 * stupidity, which is that ext4's mballoc code only allocates
2300 * at most 2048 blocks. So we force contiguous writes up to
2301 * the number of dirty blocks in the inode, or
2302 * sbi->max_writeback_mb_bump whichever is smaller.
2304 max_pages = sbi->s_max_writeback_mb_bump << (20 - PAGE_CACHE_SHIFT);
2305 if (!range_cyclic && range_whole) {
2306 if (wbc->nr_to_write == LONG_MAX)
2307 desired_nr_to_write = wbc->nr_to_write;
2309 desired_nr_to_write = wbc->nr_to_write * 8;
2311 desired_nr_to_write = ext4_num_dirty_pages(inode, index,
2313 if (desired_nr_to_write > max_pages)
2314 desired_nr_to_write = max_pages;
2316 if (wbc->nr_to_write < desired_nr_to_write) {
2317 nr_to_writebump = desired_nr_to_write - wbc->nr_to_write;
2318 wbc->nr_to_write = desired_nr_to_write;
2322 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
2323 tag_pages_for_writeback(mapping, index, end);
2325 blk_start_plug(&plug);
2326 while (!ret && wbc->nr_to_write > 0) {
2329 * we insert one extent at a time. So we need
2330 * credit needed for single extent allocation.
2331 * journalled mode is currently not supported
2334 BUG_ON(ext4_should_journal_data(inode));
2335 needed_blocks = ext4_da_writepages_trans_blocks(inode);
2337 /* start a new transaction*/
2338 handle = ext4_journal_start(inode, needed_blocks);
2339 if (IS_ERR(handle)) {
2340 ret = PTR_ERR(handle);
2341 ext4_msg(inode->i_sb, KERN_CRIT, "%s: jbd2_start: "
2342 "%ld pages, ino %lu; err %d", __func__,
2343 wbc->nr_to_write, inode->i_ino, ret);
2344 blk_finish_plug(&plug);
2345 goto out_writepages;
2349 * Now call write_cache_pages_da() to find the next
2350 * contiguous region of logical blocks that need
2351 * blocks to be allocated by ext4 and submit them.
2353 ret = write_cache_pages_da(mapping, wbc, &mpd, &done_index);
2355 * If we have a contiguous extent of pages and we
2356 * haven't done the I/O yet, map the blocks and submit
2359 if (!mpd.io_done && mpd.next_page != mpd.first_page) {
2360 mpage_da_map_and_submit(&mpd);
2361 ret = MPAGE_DA_EXTENT_TAIL;
2363 trace_ext4_da_write_pages(inode, &mpd);
2364 wbc->nr_to_write -= mpd.pages_written;
2366 ext4_journal_stop(handle);
2368 if ((mpd.retval == -ENOSPC) && sbi->s_journal) {
2369 /* commit the transaction which would
2370 * free blocks released in the transaction
2373 jbd2_journal_force_commit_nested(sbi->s_journal);
2375 } else if (ret == MPAGE_DA_EXTENT_TAIL) {
2377 * Got one extent now try with rest of the pages.
2378 * If mpd.retval is set -EIO, journal is aborted.
2379 * So we don't need to write any more.
2381 pages_written += mpd.pages_written;
2384 } else if (wbc->nr_to_write)
2386 * There is no more writeout needed
2387 * or we requested for a noblocking writeout
2388 * and we found the device congested
2392 blk_finish_plug(&plug);
2393 if (!io_done && !cycled) {
2396 wbc->range_start = index << PAGE_CACHE_SHIFT;
2397 wbc->range_end = mapping->writeback_index - 1;
2402 wbc->range_cyclic = range_cyclic;
2403 if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
2405 * set the writeback_index so that range_cyclic
2406 * mode will write it back later
2408 mapping->writeback_index = done_index;
2411 wbc->nr_to_write -= nr_to_writebump;
2412 wbc->range_start = range_start;
2413 trace_ext4_da_writepages_result(inode, wbc, ret, pages_written);
2417 #define FALL_BACK_TO_NONDELALLOC 1
2418 static int ext4_nonda_switch(struct super_block *sb)
2420 s64 free_blocks, dirty_blocks;
2421 struct ext4_sb_info *sbi = EXT4_SB(sb);
2424 * switch to non delalloc mode if we are running low
2425 * on free block. The free block accounting via percpu
2426 * counters can get slightly wrong with percpu_counter_batch getting
2427 * accumulated on each CPU without updating global counters
2428 * Delalloc need an accurate free block accounting. So switch
2429 * to non delalloc when we are near to error range.
2431 free_blocks = EXT4_C2B(sbi,
2432 percpu_counter_read_positive(&sbi->s_freeclusters_counter));
2433 dirty_blocks = percpu_counter_read_positive(&sbi->s_dirtyclusters_counter);
2435 * Start pushing delalloc when 1/2 of free blocks are dirty.
2437 if (dirty_blocks && (free_blocks < 2 * dirty_blocks) &&
2438 !writeback_in_progress(sb->s_bdi) &&
2439 down_read_trylock(&sb->s_umount)) {
2440 writeback_inodes_sb(sb, WB_REASON_FS_FREE_SPACE);
2441 up_read(&sb->s_umount);
2444 if (2 * free_blocks < 3 * dirty_blocks ||
2445 free_blocks < (dirty_blocks + EXT4_FREECLUSTERS_WATERMARK)) {
2447 * free block count is less than 150% of dirty blocks
2448 * or free blocks is less than watermark
2455 /* We always reserve for an inode update; the superblock could be there too */
2456 static int ext4_da_write_credits(struct inode *inode, loff_t pos, unsigned len)
2458 if (likely(EXT4_HAS_RO_COMPAT_FEATURE(inode->i_sb,
2459 EXT4_FEATURE_RO_COMPAT_LARGE_FILE)))
2462 if (pos + len <= 0x7fffffffULL)
2465 /* We might need to update the superblock to set LARGE_FILE */
2469 static int ext4_da_write_begin(struct file *file, struct address_space *mapping,
2470 loff_t pos, unsigned len, unsigned flags,
2471 struct page **pagep, void **fsdata)
2473 int ret, retries = 0;
2476 struct inode *inode = mapping->host;
2479 index = pos >> PAGE_CACHE_SHIFT;
2481 if (ext4_nonda_switch(inode->i_sb)) {
2482 *fsdata = (void *)FALL_BACK_TO_NONDELALLOC;
2483 return ext4_write_begin(file, mapping, pos,
2484 len, flags, pagep, fsdata);
2486 *fsdata = (void *)0;
2487 trace_ext4_da_write_begin(inode, pos, len, flags);
2490 * With delayed allocation, we don't log the i_disksize update
2491 * if there is delayed block allocation. But we still need
2492 * to journalling the i_disksize update if writes to the end
2493 * of file which has an already mapped buffer.
2495 handle = ext4_journal_start(inode,
2496 ext4_da_write_credits(inode, pos, len));
2497 if (IS_ERR(handle)) {
2498 ret = PTR_ERR(handle);
2501 /* We cannot recurse into the filesystem as the transaction is already
2503 flags |= AOP_FLAG_NOFS;
2505 page = grab_cache_page_write_begin(mapping, index, flags);
2507 ext4_journal_stop(handle);
2513 ret = __block_write_begin(page, pos, len, ext4_da_get_block_prep);
2516 ext4_journal_stop(handle);
2517 page_cache_release(page);
2519 * block_write_begin may have instantiated a few blocks
2520 * outside i_size. Trim these off again. Don't need
2521 * i_size_read because we hold i_mutex.
2523 if (pos + len > inode->i_size)
2524 ext4_truncate_failed_write(inode);
2527 if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
2534 * Check if we should update i_disksize
2535 * when write to the end of file but not require block allocation
2537 static int ext4_da_should_update_i_disksize(struct page *page,
2538 unsigned long offset)
2540 struct buffer_head *bh;
2541 struct inode *inode = page->mapping->host;
2545 bh = page_buffers(page);
2546 idx = offset >> inode->i_blkbits;
2548 for (i = 0; i < idx; i++)
2549 bh = bh->b_this_page;
2551 if (!buffer_mapped(bh) || (buffer_delay(bh)) || buffer_unwritten(bh))
2556 static int ext4_da_write_end(struct file *file,
2557 struct address_space *mapping,
2558 loff_t pos, unsigned len, unsigned copied,
2559 struct page *page, void *fsdata)
2561 struct inode *inode = mapping->host;
2563 handle_t *handle = ext4_journal_current_handle();
2565 unsigned long start, end;
2566 int write_mode = (int)(unsigned long)fsdata;
2568 if (write_mode == FALL_BACK_TO_NONDELALLOC) {
2569 switch (ext4_inode_journal_mode(inode)) {
2570 case EXT4_INODE_ORDERED_DATA_MODE:
2571 return ext4_ordered_write_end(file, mapping, pos,
2572 len, copied, page, fsdata);
2573 case EXT4_INODE_WRITEBACK_DATA_MODE:
2574 return ext4_writeback_write_end(file, mapping, pos,
2575 len, copied, page, fsdata);
2581 trace_ext4_da_write_end(inode, pos, len, copied);
2582 start = pos & (PAGE_CACHE_SIZE - 1);
2583 end = start + copied - 1;
2586 * generic_write_end() will run mark_inode_dirty() if i_size
2587 * changes. So let's piggyback the i_disksize mark_inode_dirty
2591 new_i_size = pos + copied;
2592 if (copied && new_i_size > EXT4_I(inode)->i_disksize) {
2593 if (ext4_da_should_update_i_disksize(page, end)) {
2594 down_write(&EXT4_I(inode)->i_data_sem);
2595 if (new_i_size > EXT4_I(inode)->i_disksize) {
2597 * Updating i_disksize when extending file
2598 * without needing block allocation
2600 if (ext4_should_order_data(inode))
2601 ret = ext4_jbd2_file_inode(handle,
2604 EXT4_I(inode)->i_disksize = new_i_size;
2606 up_write(&EXT4_I(inode)->i_data_sem);
2607 /* We need to mark inode dirty even if
2608 * new_i_size is less that inode->i_size
2609 * bu greater than i_disksize.(hint delalloc)
2611 ext4_mark_inode_dirty(handle, inode);
2614 ret2 = generic_write_end(file, mapping, pos, len, copied,
2619 ret2 = ext4_journal_stop(handle);
2623 return ret ? ret : copied;
2626 static void ext4_da_invalidatepage(struct page *page, unsigned long offset)
2629 * Drop reserved blocks
2631 BUG_ON(!PageLocked(page));
2632 if (!page_has_buffers(page))
2635 ext4_da_page_release_reservation(page, offset);
2638 ext4_invalidatepage(page, offset);
2644 * Force all delayed allocation blocks to be allocated for a given inode.
2646 int ext4_alloc_da_blocks(struct inode *inode)
2648 trace_ext4_alloc_da_blocks(inode);
2650 if (!EXT4_I(inode)->i_reserved_data_blocks &&
2651 !EXT4_I(inode)->i_reserved_meta_blocks)
2655 * We do something simple for now. The filemap_flush() will
2656 * also start triggering a write of the data blocks, which is
2657 * not strictly speaking necessary (and for users of
2658 * laptop_mode, not even desirable). However, to do otherwise
2659 * would require replicating code paths in:
2661 * ext4_da_writepages() ->
2662 * write_cache_pages() ---> (via passed in callback function)
2663 * __mpage_da_writepage() -->
2664 * mpage_add_bh_to_extent()
2665 * mpage_da_map_blocks()
2667 * The problem is that write_cache_pages(), located in
2668 * mm/page-writeback.c, marks pages clean in preparation for
2669 * doing I/O, which is not desirable if we're not planning on
2672 * We could call write_cache_pages(), and then redirty all of
2673 * the pages by calling redirty_page_for_writepage() but that
2674 * would be ugly in the extreme. So instead we would need to
2675 * replicate parts of the code in the above functions,
2676 * simplifying them because we wouldn't actually intend to
2677 * write out the pages, but rather only collect contiguous
2678 * logical block extents, call the multi-block allocator, and
2679 * then update the buffer heads with the block allocations.
2681 * For now, though, we'll cheat by calling filemap_flush(),
2682 * which will map the blocks, and start the I/O, but not
2683 * actually wait for the I/O to complete.
2685 return filemap_flush(inode->i_mapping);
2689 * bmap() is special. It gets used by applications such as lilo and by
2690 * the swapper to find the on-disk block of a specific piece of data.
2692 * Naturally, this is dangerous if the block concerned is still in the
2693 * journal. If somebody makes a swapfile on an ext4 data-journaling
2694 * filesystem and enables swap, then they may get a nasty shock when the
2695 * data getting swapped to that swapfile suddenly gets overwritten by
2696 * the original zero's written out previously to the journal and
2697 * awaiting writeback in the kernel's buffer cache.
2699 * So, if we see any bmap calls here on a modified, data-journaled file,
2700 * take extra steps to flush any blocks which might be in the cache.
2702 static sector_t ext4_bmap(struct address_space *mapping, sector_t block)
2704 struct inode *inode = mapping->host;
2708 if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY) &&
2709 test_opt(inode->i_sb, DELALLOC)) {
2711 * With delalloc we want to sync the file
2712 * so that we can make sure we allocate
2715 filemap_write_and_wait(mapping);
2718 if (EXT4_JOURNAL(inode) &&
2719 ext4_test_inode_state(inode, EXT4_STATE_JDATA)) {
2721 * This is a REALLY heavyweight approach, but the use of
2722 * bmap on dirty files is expected to be extremely rare:
2723 * only if we run lilo or swapon on a freshly made file
2724 * do we expect this to happen.
2726 * (bmap requires CAP_SYS_RAWIO so this does not
2727 * represent an unprivileged user DOS attack --- we'd be
2728 * in trouble if mortal users could trigger this path at
2731 * NB. EXT4_STATE_JDATA is not set on files other than
2732 * regular files. If somebody wants to bmap a directory
2733 * or symlink and gets confused because the buffer
2734 * hasn't yet been flushed to disk, they deserve
2735 * everything they get.
2738 ext4_clear_inode_state(inode, EXT4_STATE_JDATA);
2739 journal = EXT4_JOURNAL(inode);
2740 jbd2_journal_lock_updates(journal);
2741 err = jbd2_journal_flush(journal);
2742 jbd2_journal_unlock_updates(journal);
2748 return generic_block_bmap(mapping, block, ext4_get_block);
2751 static int ext4_readpage(struct file *file, struct page *page)
2753 trace_ext4_readpage(page);
2754 return mpage_readpage(page, ext4_get_block);
2758 ext4_readpages(struct file *file, struct address_space *mapping,
2759 struct list_head *pages, unsigned nr_pages)
2761 return mpage_readpages(mapping, pages, nr_pages, ext4_get_block);
2764 static void ext4_invalidatepage_free_endio(struct page *page, unsigned long offset)
2766 struct buffer_head *head, *bh;
2767 unsigned int curr_off = 0;
2769 if (!page_has_buffers(page))
2771 head = bh = page_buffers(page);
2773 if (offset <= curr_off && test_clear_buffer_uninit(bh)
2775 ext4_free_io_end(bh->b_private);
2776 bh->b_private = NULL;
2777 bh->b_end_io = NULL;
2779 curr_off = curr_off + bh->b_size;
2780 bh = bh->b_this_page;
2781 } while (bh != head);
2784 static void ext4_invalidatepage(struct page *page, unsigned long offset)
2786 journal_t *journal = EXT4_JOURNAL(page->mapping->host);
2788 trace_ext4_invalidatepage(page, offset);
2791 * free any io_end structure allocated for buffers to be discarded
2793 if (ext4_should_dioread_nolock(page->mapping->host))
2794 ext4_invalidatepage_free_endio(page, offset);
2796 * If it's a full truncate we just forget about the pending dirtying
2799 ClearPageChecked(page);
2802 jbd2_journal_invalidatepage(journal, page, offset);
2804 block_invalidatepage(page, offset);
2807 static int ext4_releasepage(struct page *page, gfp_t wait)
2809 journal_t *journal = EXT4_JOURNAL(page->mapping->host);
2811 trace_ext4_releasepage(page);
2813 WARN_ON(PageChecked(page));
2814 if (!page_has_buffers(page))
2817 return jbd2_journal_try_to_free_buffers(journal, page, wait);
2819 return try_to_free_buffers(page);
2823 * ext4_get_block used when preparing for a DIO write or buffer write.
2824 * We allocate an uinitialized extent if blocks haven't been allocated.
2825 * The extent will be converted to initialized after the IO is complete.
2827 static int ext4_get_block_write(struct inode *inode, sector_t iblock,
2828 struct buffer_head *bh_result, int create)
2830 ext4_debug("ext4_get_block_write: inode %lu, create flag %d\n",
2831 inode->i_ino, create);
2832 return _ext4_get_block(inode, iblock, bh_result,
2833 EXT4_GET_BLOCKS_IO_CREATE_EXT);
2836 static void ext4_end_io_dio(struct kiocb *iocb, loff_t offset,
2837 ssize_t size, void *private, int ret,
2840 struct inode *inode = iocb->ki_filp->f_path.dentry->d_inode;
2841 ext4_io_end_t *io_end = iocb->private;
2842 struct workqueue_struct *wq;
2843 unsigned long flags;
2844 struct ext4_inode_info *ei;
2846 /* if not async direct IO or dio with 0 bytes write, just return */
2847 if (!io_end || !size)
2850 ext_debug("ext4_end_io_dio(): io_end 0x%p"
2851 "for inode %lu, iocb 0x%p, offset %llu, size %llu\n",
2852 iocb->private, io_end->inode->i_ino, iocb, offset,
2855 iocb->private = NULL;
2857 /* if not aio dio with unwritten extents, just free io and return */
2858 if (!(io_end->flag & EXT4_IO_END_UNWRITTEN)) {
2859 ext4_free_io_end(io_end);
2861 inode_dio_done(inode);
2863 aio_complete(iocb, ret, 0);
2867 io_end->offset = offset;
2868 io_end->size = size;
2870 io_end->iocb = iocb;
2871 io_end->result = ret;
2873 wq = EXT4_SB(io_end->inode->i_sb)->dio_unwritten_wq;
2875 /* Add the io_end to per-inode completed aio dio list*/
2876 ei = EXT4_I(io_end->inode);
2877 spin_lock_irqsave(&ei->i_completed_io_lock, flags);
2878 list_add_tail(&io_end->list, &ei->i_completed_io_list);
2879 spin_unlock_irqrestore(&ei->i_completed_io_lock, flags);
2881 /* queue the work to convert unwritten extents to written */
2882 queue_work(wq, &io_end->work);
2885 static void ext4_end_io_buffer_write(struct buffer_head *bh, int uptodate)
2887 ext4_io_end_t *io_end = bh->b_private;
2888 struct workqueue_struct *wq;
2889 struct inode *inode;
2890 unsigned long flags;
2892 if (!test_clear_buffer_uninit(bh) || !io_end)
2895 if (!(io_end->inode->i_sb->s_flags & MS_ACTIVE)) {
2896 printk("sb umounted, discard end_io request for inode %lu\n",
2897 io_end->inode->i_ino);
2898 ext4_free_io_end(io_end);
2903 * It may be over-defensive here to check EXT4_IO_END_UNWRITTEN now,
2904 * but being more careful is always safe for the future change.
2906 inode = io_end->inode;
2907 ext4_set_io_unwritten_flag(inode, io_end);
2909 /* Add the io_end to per-inode completed io list*/
2910 spin_lock_irqsave(&EXT4_I(inode)->i_completed_io_lock, flags);
2911 list_add_tail(&io_end->list, &EXT4_I(inode)->i_completed_io_list);
2912 spin_unlock_irqrestore(&EXT4_I(inode)->i_completed_io_lock, flags);
2914 wq = EXT4_SB(inode->i_sb)->dio_unwritten_wq;
2915 /* queue the work to convert unwritten extents to written */
2916 queue_work(wq, &io_end->work);
2918 bh->b_private = NULL;
2919 bh->b_end_io = NULL;
2920 clear_buffer_uninit(bh);
2921 end_buffer_async_write(bh, uptodate);
2924 static int ext4_set_bh_endio(struct buffer_head *bh, struct inode *inode)
2926 ext4_io_end_t *io_end;
2927 struct page *page = bh->b_page;
2928 loff_t offset = (sector_t)page->index << PAGE_CACHE_SHIFT;
2929 size_t size = bh->b_size;
2932 io_end = ext4_init_io_end(inode, GFP_ATOMIC);
2934 pr_warn_ratelimited("%s: allocation fail\n", __func__);
2938 io_end->offset = offset;
2939 io_end->size = size;
2941 * We need to hold a reference to the page to make sure it
2942 * doesn't get evicted before ext4_end_io_work() has a chance
2943 * to convert the extent from written to unwritten.
2945 io_end->page = page;
2946 get_page(io_end->page);
2948 bh->b_private = io_end;
2949 bh->b_end_io = ext4_end_io_buffer_write;
2954 * For ext4 extent files, ext4 will do direct-io write to holes,
2955 * preallocated extents, and those write extend the file, no need to
2956 * fall back to buffered IO.
2958 * For holes, we fallocate those blocks, mark them as uninitialized
2959 * If those blocks were preallocated, we mark sure they are splited, but
2960 * still keep the range to write as uninitialized.
2962 * The unwrritten extents will be converted to written when DIO is completed.
2963 * For async direct IO, since the IO may still pending when return, we
2964 * set up an end_io call back function, which will do the conversion
2965 * when async direct IO completed.
2967 * If the O_DIRECT write will extend the file then add this inode to the
2968 * orphan list. So recovery will truncate it back to the original size
2969 * if the machine crashes during the write.
2972 static ssize_t ext4_ext_direct_IO(int rw, struct kiocb *iocb,
2973 const struct iovec *iov, loff_t offset,
2974 unsigned long nr_segs)
2976 struct file *file = iocb->ki_filp;
2977 struct inode *inode = file->f_mapping->host;
2979 size_t count = iov_length(iov, nr_segs);
2981 loff_t final_size = offset + count;
2982 if (rw == WRITE && final_size <= inode->i_size) {
2984 * We could direct write to holes and fallocate.
2986 * Allocated blocks to fill the hole are marked as uninitialized
2987 * to prevent parallel buffered read to expose the stale data
2988 * before DIO complete the data IO.
2990 * As to previously fallocated extents, ext4 get_block
2991 * will just simply mark the buffer mapped but still
2992 * keep the extents uninitialized.
2994 * for non AIO case, we will convert those unwritten extents
2995 * to written after return back from blockdev_direct_IO.
2997 * for async DIO, the conversion needs to be defered when
2998 * the IO is completed. The ext4 end_io callback function
2999 * will be called to take care of the conversion work.
3000 * Here for async case, we allocate an io_end structure to
3003 iocb->private = NULL;
3004 EXT4_I(inode)->cur_aio_dio = NULL;
3005 if (!is_sync_kiocb(iocb)) {
3006 ext4_io_end_t *io_end =
3007 ext4_init_io_end(inode, GFP_NOFS);
3010 io_end->flag |= EXT4_IO_END_DIRECT;
3011 iocb->private = io_end;
3013 * we save the io structure for current async
3014 * direct IO, so that later ext4_map_blocks()
3015 * could flag the io structure whether there
3016 * is a unwritten extents needs to be converted
3017 * when IO is completed.
3019 EXT4_I(inode)->cur_aio_dio = iocb->private;
3022 ret = __blockdev_direct_IO(rw, iocb, inode,
3023 inode->i_sb->s_bdev, iov,
3025 ext4_get_block_write,
3028 DIO_LOCKING | DIO_SKIP_HOLES);
3030 EXT4_I(inode)->cur_aio_dio = NULL;
3032 * The io_end structure takes a reference to the inode,
3033 * that structure needs to be destroyed and the
3034 * reference to the inode need to be dropped, when IO is
3035 * complete, even with 0 byte write, or failed.
3037 * In the successful AIO DIO case, the io_end structure will be
3038 * desctroyed and the reference to the inode will be dropped
3039 * after the end_io call back function is called.
3041 * In the case there is 0 byte write, or error case, since
3042 * VFS direct IO won't invoke the end_io call back function,
3043 * we need to free the end_io structure here.
3045 if (ret != -EIOCBQUEUED && ret <= 0 && iocb->private) {
3046 ext4_free_io_end(iocb->private);
3047 iocb->private = NULL;
3048 } else if (ret > 0 && ext4_test_inode_state(inode,
3049 EXT4_STATE_DIO_UNWRITTEN)) {
3052 * for non AIO case, since the IO is already
3053 * completed, we could do the conversion right here
3055 err = ext4_convert_unwritten_extents(inode,
3059 ext4_clear_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN);
3064 /* for write the the end of file case, we fall back to old way */
3065 return ext4_ind_direct_IO(rw, iocb, iov, offset, nr_segs);
3068 static ssize_t ext4_direct_IO(int rw, struct kiocb *iocb,
3069 const struct iovec *iov, loff_t offset,
3070 unsigned long nr_segs)
3072 struct file *file = iocb->ki_filp;
3073 struct inode *inode = file->f_mapping->host;
3077 * If we are doing data journalling we don't support O_DIRECT
3079 if (ext4_should_journal_data(inode))
3082 trace_ext4_direct_IO_enter(inode, offset, iov_length(iov, nr_segs), rw);
3083 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3084 ret = ext4_ext_direct_IO(rw, iocb, iov, offset, nr_segs);
3086 ret = ext4_ind_direct_IO(rw, iocb, iov, offset, nr_segs);
3087 trace_ext4_direct_IO_exit(inode, offset,
3088 iov_length(iov, nr_segs), rw, ret);
3093 * Pages can be marked dirty completely asynchronously from ext4's journalling
3094 * activity. By filemap_sync_pte(), try_to_unmap_one(), etc. We cannot do
3095 * much here because ->set_page_dirty is called under VFS locks. The page is
3096 * not necessarily locked.
3098 * We cannot just dirty the page and leave attached buffers clean, because the
3099 * buffers' dirty state is "definitive". We cannot just set the buffers dirty
3100 * or jbddirty because all the journalling code will explode.
3102 * So what we do is to mark the page "pending dirty" and next time writepage
3103 * is called, propagate that into the buffers appropriately.
3105 static int ext4_journalled_set_page_dirty(struct page *page)
3107 SetPageChecked(page);
3108 return __set_page_dirty_nobuffers(page);
3111 static const struct address_space_operations ext4_ordered_aops = {
3112 .readpage = ext4_readpage,
3113 .readpages = ext4_readpages,
3114 .writepage = ext4_writepage,
3115 .write_begin = ext4_write_begin,
3116 .write_end = ext4_ordered_write_end,
3118 .invalidatepage = ext4_invalidatepage,
3119 .releasepage = ext4_releasepage,
3120 .direct_IO = ext4_direct_IO,
3121 .migratepage = buffer_migrate_page,
3122 .is_partially_uptodate = block_is_partially_uptodate,
3123 .error_remove_page = generic_error_remove_page,
3126 static const struct address_space_operations ext4_writeback_aops = {
3127 .readpage = ext4_readpage,
3128 .readpages = ext4_readpages,
3129 .writepage = ext4_writepage,
3130 .write_begin = ext4_write_begin,
3131 .write_end = ext4_writeback_write_end,
3133 .invalidatepage = ext4_invalidatepage,
3134 .releasepage = ext4_releasepage,
3135 .direct_IO = ext4_direct_IO,
3136 .migratepage = buffer_migrate_page,
3137 .is_partially_uptodate = block_is_partially_uptodate,
3138 .error_remove_page = generic_error_remove_page,
3141 static const struct address_space_operations ext4_journalled_aops = {
3142 .readpage = ext4_readpage,
3143 .readpages = ext4_readpages,
3144 .writepage = ext4_writepage,
3145 .write_begin = ext4_write_begin,
3146 .write_end = ext4_journalled_write_end,
3147 .set_page_dirty = ext4_journalled_set_page_dirty,
3149 .invalidatepage = ext4_invalidatepage,
3150 .releasepage = ext4_releasepage,
3151 .direct_IO = ext4_direct_IO,
3152 .is_partially_uptodate = block_is_partially_uptodate,
3153 .error_remove_page = generic_error_remove_page,
3156 static const struct address_space_operations ext4_da_aops = {
3157 .readpage = ext4_readpage,
3158 .readpages = ext4_readpages,
3159 .writepage = ext4_writepage,
3160 .writepages = ext4_da_writepages,
3161 .write_begin = ext4_da_write_begin,
3162 .write_end = ext4_da_write_end,
3164 .invalidatepage = ext4_da_invalidatepage,
3165 .releasepage = ext4_releasepage,
3166 .direct_IO = ext4_direct_IO,
3167 .migratepage = buffer_migrate_page,
3168 .is_partially_uptodate = block_is_partially_uptodate,
3169 .error_remove_page = generic_error_remove_page,
3172 void ext4_set_aops(struct inode *inode)
3174 switch (ext4_inode_journal_mode(inode)) {
3175 case EXT4_INODE_ORDERED_DATA_MODE:
3176 if (test_opt(inode->i_sb, DELALLOC))
3177 inode->i_mapping->a_ops = &ext4_da_aops;
3179 inode->i_mapping->a_ops = &ext4_ordered_aops;
3181 case EXT4_INODE_WRITEBACK_DATA_MODE:
3182 if (test_opt(inode->i_sb, DELALLOC))
3183 inode->i_mapping->a_ops = &ext4_da_aops;
3185 inode->i_mapping->a_ops = &ext4_writeback_aops;
3187 case EXT4_INODE_JOURNAL_DATA_MODE:
3188 inode->i_mapping->a_ops = &ext4_journalled_aops;
3197 * ext4_discard_partial_page_buffers()
3198 * Wrapper function for ext4_discard_partial_page_buffers_no_lock.
3199 * This function finds and locks the page containing the offset
3200 * "from" and passes it to ext4_discard_partial_page_buffers_no_lock.
3201 * Calling functions that already have the page locked should call
3202 * ext4_discard_partial_page_buffers_no_lock directly.
3204 int ext4_discard_partial_page_buffers(handle_t *handle,
3205 struct address_space *mapping, loff_t from,
3206 loff_t length, int flags)
3208 struct inode *inode = mapping->host;
3212 page = find_or_create_page(mapping, from >> PAGE_CACHE_SHIFT,
3213 mapping_gfp_mask(mapping) & ~__GFP_FS);
3217 err = ext4_discard_partial_page_buffers_no_lock(handle, inode, page,
3218 from, length, flags);
3221 page_cache_release(page);
3226 * ext4_discard_partial_page_buffers_no_lock()
3227 * Zeros a page range of length 'length' starting from offset 'from'.
3228 * Buffer heads that correspond to the block aligned regions of the
3229 * zeroed range will be unmapped. Unblock aligned regions
3230 * will have the corresponding buffer head mapped if needed so that
3231 * that region of the page can be updated with the partial zero out.
3233 * This function assumes that the page has already been locked. The
3234 * The range to be discarded must be contained with in the given page.
3235 * If the specified range exceeds the end of the page it will be shortened
3236 * to the end of the page that corresponds to 'from'. This function is
3237 * appropriate for updating a page and it buffer heads to be unmapped and
3238 * zeroed for blocks that have been either released, or are going to be
3241 * handle: The journal handle
3242 * inode: The files inode
3243 * page: A locked page that contains the offset "from"
3244 * from: The starting byte offset (from the begining of the file)
3245 * to begin discarding
3246 * len: The length of bytes to discard
3247 * flags: Optional flags that may be used:
3249 * EXT4_DISCARD_PARTIAL_PG_ZERO_UNMAPPED
3250 * Only zero the regions of the page whose buffer heads
3251 * have already been unmapped. This flag is appropriate
3252 * for updateing the contents of a page whose blocks may
3253 * have already been released, and we only want to zero
3254 * out the regions that correspond to those released blocks.
3256 * Returns zero on sucess or negative on failure.
3258 int ext4_discard_partial_page_buffers_no_lock(handle_t *handle,
3259 struct inode *inode, struct page *page, loff_t from,
3260 loff_t length, int flags)
3262 ext4_fsblk_t index = from >> PAGE_CACHE_SHIFT;
3263 unsigned int offset = from & (PAGE_CACHE_SIZE-1);
3264 unsigned int blocksize, max, pos;
3266 struct buffer_head *bh;
3269 blocksize = inode->i_sb->s_blocksize;
3270 max = PAGE_CACHE_SIZE - offset;
3272 if (index != page->index)
3276 * correct length if it does not fall between
3277 * 'from' and the end of the page
3279 if (length > max || length < 0)
3282 iblock = index << (PAGE_CACHE_SHIFT - inode->i_sb->s_blocksize_bits);
3284 if (!page_has_buffers(page))
3285 create_empty_buffers(page, blocksize, 0);
3287 /* Find the buffer that contains "offset" */
3288 bh = page_buffers(page);
3290 while (offset >= pos) {
3291 bh = bh->b_this_page;
3297 while (pos < offset + length) {
3298 unsigned int end_of_block, range_to_discard;
3302 /* The length of space left to zero and unmap */
3303 range_to_discard = offset + length - pos;
3305 /* The length of space until the end of the block */
3306 end_of_block = blocksize - (pos & (blocksize-1));
3309 * Do not unmap or zero past end of block
3310 * for this buffer head
3312 if (range_to_discard > end_of_block)
3313 range_to_discard = end_of_block;
3317 * Skip this buffer head if we are only zeroing unampped
3318 * regions of the page
3320 if (flags & EXT4_DISCARD_PARTIAL_PG_ZERO_UNMAPPED &&
3324 /* If the range is block aligned, unmap */
3325 if (range_to_discard == blocksize) {
3326 clear_buffer_dirty(bh);
3328 clear_buffer_mapped(bh);
3329 clear_buffer_req(bh);
3330 clear_buffer_new(bh);
3331 clear_buffer_delay(bh);
3332 clear_buffer_unwritten(bh);
3333 clear_buffer_uptodate(bh);
3334 zero_user(page, pos, range_to_discard);
3335 BUFFER_TRACE(bh, "Buffer discarded");
3340 * If this block is not completely contained in the range
3341 * to be discarded, then it is not going to be released. Because
3342 * we need to keep this block, we need to make sure this part
3343 * of the page is uptodate before we modify it by writeing
3344 * partial zeros on it.
3346 if (!buffer_mapped(bh)) {
3348 * Buffer head must be mapped before we can read
3351 BUFFER_TRACE(bh, "unmapped");
3352 ext4_get_block(inode, iblock, bh, 0);
3353 /* unmapped? It's a hole - nothing to do */
3354 if (!buffer_mapped(bh)) {
3355 BUFFER_TRACE(bh, "still unmapped");
3360 /* Ok, it's mapped. Make sure it's up-to-date */
3361 if (PageUptodate(page))
3362 set_buffer_uptodate(bh);
3364 if (!buffer_uptodate(bh)) {
3366 ll_rw_block(READ, 1, &bh);
3368 /* Uhhuh. Read error. Complain and punt.*/
3369 if (!buffer_uptodate(bh))
3373 if (ext4_should_journal_data(inode)) {
3374 BUFFER_TRACE(bh, "get write access");
3375 err = ext4_journal_get_write_access(handle, bh);
3380 zero_user(page, pos, range_to_discard);
3383 if (ext4_should_journal_data(inode)) {
3384 err = ext4_handle_dirty_metadata(handle, inode, bh);
3386 mark_buffer_dirty(bh);
3388 BUFFER_TRACE(bh, "Partial buffer zeroed");
3390 bh = bh->b_this_page;
3392 pos += range_to_discard;
3399 * ext4_block_truncate_page() zeroes out a mapping from file offset `from'
3400 * up to the end of the block which corresponds to `from'.
3401 * This required during truncate. We need to physically zero the tail end
3402 * of that block so it doesn't yield old data if the file is later grown.
3404 int ext4_block_truncate_page(handle_t *handle,
3405 struct address_space *mapping, loff_t from)
3407 unsigned offset = from & (PAGE_CACHE_SIZE-1);
3410 struct inode *inode = mapping->host;
3412 blocksize = inode->i_sb->s_blocksize;
3413 length = blocksize - (offset & (blocksize - 1));
3415 return ext4_block_zero_page_range(handle, mapping, from, length);
3419 * ext4_block_zero_page_range() zeros out a mapping of length 'length'
3420 * starting from file offset 'from'. The range to be zero'd must
3421 * be contained with in one block. If the specified range exceeds
3422 * the end of the block it will be shortened to end of the block
3423 * that cooresponds to 'from'
3425 int ext4_block_zero_page_range(handle_t *handle,
3426 struct address_space *mapping, loff_t from, loff_t length)
3428 ext4_fsblk_t index = from >> PAGE_CACHE_SHIFT;
3429 unsigned offset = from & (PAGE_CACHE_SIZE-1);
3430 unsigned blocksize, max, pos;
3432 struct inode *inode = mapping->host;
3433 struct buffer_head *bh;
3437 page = find_or_create_page(mapping, from >> PAGE_CACHE_SHIFT,
3438 mapping_gfp_mask(mapping) & ~__GFP_FS);
3442 blocksize = inode->i_sb->s_blocksize;
3443 max = blocksize - (offset & (blocksize - 1));
3446 * correct length if it does not fall between
3447 * 'from' and the end of the block
3449 if (length > max || length < 0)
3452 iblock = index << (PAGE_CACHE_SHIFT - inode->i_sb->s_blocksize_bits);
3454 if (!page_has_buffers(page))
3455 create_empty_buffers(page, blocksize, 0);
3457 /* Find the buffer that contains "offset" */
3458 bh = page_buffers(page);
3460 while (offset >= pos) {
3461 bh = bh->b_this_page;
3467 if (buffer_freed(bh)) {
3468 BUFFER_TRACE(bh, "freed: skip");
3472 if (!buffer_mapped(bh)) {
3473 BUFFER_TRACE(bh, "unmapped");
3474 ext4_get_block(inode, iblock, bh, 0);
3475 /* unmapped? It's a hole - nothing to do */
3476 if (!buffer_mapped(bh)) {
3477 BUFFER_TRACE(bh, "still unmapped");
3482 /* Ok, it's mapped. Make sure it's up-to-date */
3483 if (PageUptodate(page))
3484 set_buffer_uptodate(bh);
3486 if (!buffer_uptodate(bh)) {
3488 ll_rw_block(READ, 1, &bh);
3490 /* Uhhuh. Read error. Complain and punt. */
3491 if (!buffer_uptodate(bh))
3495 if (ext4_should_journal_data(inode)) {
3496 BUFFER_TRACE(bh, "get write access");
3497 err = ext4_journal_get_write_access(handle, bh);
3502 zero_user(page, offset, length);
3504 BUFFER_TRACE(bh, "zeroed end of block");
3507 if (ext4_should_journal_data(inode)) {
3508 err = ext4_handle_dirty_metadata(handle, inode, bh);
3510 mark_buffer_dirty(bh);
3514 page_cache_release(page);
3518 int ext4_can_truncate(struct inode *inode)
3520 if (S_ISREG(inode->i_mode))
3522 if (S_ISDIR(inode->i_mode))
3524 if (S_ISLNK(inode->i_mode))
3525 return !ext4_inode_is_fast_symlink(inode);
3530 * ext4_punch_hole: punches a hole in a file by releaseing the blocks
3531 * associated with the given offset and length
3533 * @inode: File inode
3534 * @offset: The offset where the hole will begin
3535 * @len: The length of the hole
3537 * Returns: 0 on sucess or negative on failure
3540 int ext4_punch_hole(struct file *file, loff_t offset, loff_t length)
3542 struct inode *inode = file->f_path.dentry->d_inode;
3543 if (!S_ISREG(inode->i_mode))
3546 if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
3547 /* TODO: Add support for non extent hole punching */
3551 if (EXT4_SB(inode->i_sb)->s_cluster_ratio > 1) {
3552 /* TODO: Add support for bigalloc file systems */
3556 return ext4_ext_punch_hole(file, offset, length);
3562 * We block out ext4_get_block() block instantiations across the entire
3563 * transaction, and VFS/VM ensures that ext4_truncate() cannot run
3564 * simultaneously on behalf of the same inode.
3566 * As we work through the truncate and commmit bits of it to the journal there
3567 * is one core, guiding principle: the file's tree must always be consistent on
3568 * disk. We must be able to restart the truncate after a crash.
3570 * The file's tree may be transiently inconsistent in memory (although it
3571 * probably isn't), but whenever we close off and commit a journal transaction,
3572 * the contents of (the filesystem + the journal) must be consistent and
3573 * restartable. It's pretty simple, really: bottom up, right to left (although
3574 * left-to-right works OK too).
3576 * Note that at recovery time, journal replay occurs *before* the restart of
3577 * truncate against the orphan inode list.
3579 * The committed inode has the new, desired i_size (which is the same as
3580 * i_disksize in this case). After a crash, ext4_orphan_cleanup() will see
3581 * that this inode's truncate did not complete and it will again call
3582 * ext4_truncate() to have another go. So there will be instantiated blocks
3583 * to the right of the truncation point in a crashed ext4 filesystem. But
3584 * that's fine - as long as they are linked from the inode, the post-crash
3585 * ext4_truncate() run will find them and release them.
3587 void ext4_truncate(struct inode *inode)
3589 trace_ext4_truncate_enter(inode);
3591 if (!ext4_can_truncate(inode))
3594 ext4_clear_inode_flag(inode, EXT4_INODE_EOFBLOCKS);
3596 if (inode->i_size == 0 && !test_opt(inode->i_sb, NO_AUTO_DA_ALLOC))
3597 ext4_set_inode_state(inode, EXT4_STATE_DA_ALLOC_CLOSE);
3599 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3600 ext4_ext_truncate(inode);
3602 ext4_ind_truncate(inode);
3604 trace_ext4_truncate_exit(inode);
3608 * ext4_get_inode_loc returns with an extra refcount against the inode's
3609 * underlying buffer_head on success. If 'in_mem' is true, we have all
3610 * data in memory that is needed to recreate the on-disk version of this
3613 static int __ext4_get_inode_loc(struct inode *inode,
3614 struct ext4_iloc *iloc, int in_mem)
3616 struct ext4_group_desc *gdp;
3617 struct buffer_head *bh;
3618 struct super_block *sb = inode->i_sb;
3620 int inodes_per_block, inode_offset;
3623 if (!ext4_valid_inum(sb, inode->i_ino))
3626 iloc->block_group = (inode->i_ino - 1) / EXT4_INODES_PER_GROUP(sb);
3627 gdp = ext4_get_group_desc(sb, iloc->block_group, NULL);
3632 * Figure out the offset within the block group inode table
3634 inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
3635 inode_offset = ((inode->i_ino - 1) %
3636 EXT4_INODES_PER_GROUP(sb));
3637 block = ext4_inode_table(sb, gdp) + (inode_offset / inodes_per_block);
3638 iloc->offset = (inode_offset % inodes_per_block) * EXT4_INODE_SIZE(sb);
3640 bh = sb_getblk(sb, block);
3643 if (!buffer_uptodate(bh)) {
3647 * If the buffer has the write error flag, we have failed
3648 * to write out another inode in the same block. In this
3649 * case, we don't have to read the block because we may
3650 * read the old inode data successfully.
3652 if (buffer_write_io_error(bh) && !buffer_uptodate(bh))
3653 set_buffer_uptodate(bh);
3655 if (buffer_uptodate(bh)) {
3656 /* someone brought it uptodate while we waited */
3662 * If we have all information of the inode in memory and this
3663 * is the only valid inode in the block, we need not read the
3667 struct buffer_head *bitmap_bh;
3670 start = inode_offset & ~(inodes_per_block - 1);
3672 /* Is the inode bitmap in cache? */
3673 bitmap_bh = sb_getblk(sb, ext4_inode_bitmap(sb, gdp));
3678 * If the inode bitmap isn't in cache then the
3679 * optimisation may end up performing two reads instead
3680 * of one, so skip it.
3682 if (!buffer_uptodate(bitmap_bh)) {
3686 for (i = start; i < start + inodes_per_block; i++) {
3687 if (i == inode_offset)
3689 if (ext4_test_bit(i, bitmap_bh->b_data))
3693 if (i == start + inodes_per_block) {
3694 /* all other inodes are free, so skip I/O */
3695 memset(bh->b_data, 0, bh->b_size);
3696 set_buffer_uptodate(bh);
3704 * If we need to do any I/O, try to pre-readahead extra
3705 * blocks from the inode table.
3707 if (EXT4_SB(sb)->s_inode_readahead_blks) {
3708 ext4_fsblk_t b, end, table;
3711 table = ext4_inode_table(sb, gdp);
3712 /* s_inode_readahead_blks is always a power of 2 */
3713 b = block & ~(EXT4_SB(sb)->s_inode_readahead_blks-1);
3716 end = b + EXT4_SB(sb)->s_inode_readahead_blks;
3717 num = EXT4_INODES_PER_GROUP(sb);
3718 if (EXT4_HAS_RO_COMPAT_FEATURE(sb,
3719 EXT4_FEATURE_RO_COMPAT_GDT_CSUM))
3720 num -= ext4_itable_unused_count(sb, gdp);
3721 table += num / inodes_per_block;
3725 sb_breadahead(sb, b++);
3729 * There are other valid inodes in the buffer, this inode
3730 * has in-inode xattrs, or we don't have this inode in memory.
3731 * Read the block from disk.
3733 trace_ext4_load_inode(inode);
3735 bh->b_end_io = end_buffer_read_sync;
3736 submit_bh(READ | REQ_META | REQ_PRIO, bh);
3738 if (!buffer_uptodate(bh)) {
3739 EXT4_ERROR_INODE_BLOCK(inode, block,
3740 "unable to read itable block");
3750 int ext4_get_inode_loc(struct inode *inode, struct ext4_iloc *iloc)
3752 /* We have all inode data except xattrs in memory here. */
3753 return __ext4_get_inode_loc(inode, iloc,
3754 !ext4_test_inode_state(inode, EXT4_STATE_XATTR));
3757 void ext4_set_inode_flags(struct inode *inode)
3759 unsigned int flags = EXT4_I(inode)->i_flags;
3760 unsigned int new_fl = 0;
3762 if (flags & EXT4_SYNC_FL)
3764 if (flags & EXT4_APPEND_FL)
3766 if (flags & EXT4_IMMUTABLE_FL)
3767 new_fl |= S_IMMUTABLE;
3768 if (flags & EXT4_NOATIME_FL)
3769 new_fl |= S_NOATIME;
3770 if (flags & EXT4_DIRSYNC_FL)
3771 new_fl |= S_DIRSYNC;
3772 set_mask_bits(&inode->i_flags,
3773 S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME|S_DIRSYNC, new_fl);
3776 /* Propagate flags from i_flags to EXT4_I(inode)->i_flags */
3777 void ext4_get_inode_flags(struct ext4_inode_info *ei)
3779 unsigned int vfs_fl;
3780 unsigned long old_fl, new_fl;
3783 vfs_fl = ei->vfs_inode.i_flags;
3784 old_fl = ei->i_flags;
3785 new_fl = old_fl & ~(EXT4_SYNC_FL|EXT4_APPEND_FL|
3786 EXT4_IMMUTABLE_FL|EXT4_NOATIME_FL|
3788 if (vfs_fl & S_SYNC)
3789 new_fl |= EXT4_SYNC_FL;
3790 if (vfs_fl & S_APPEND)
3791 new_fl |= EXT4_APPEND_FL;
3792 if (vfs_fl & S_IMMUTABLE)
3793 new_fl |= EXT4_IMMUTABLE_FL;
3794 if (vfs_fl & S_NOATIME)
3795 new_fl |= EXT4_NOATIME_FL;
3796 if (vfs_fl & S_DIRSYNC)
3797 new_fl |= EXT4_DIRSYNC_FL;
3798 } while (cmpxchg(&ei->i_flags, old_fl, new_fl) != old_fl);
3801 static blkcnt_t ext4_inode_blocks(struct ext4_inode *raw_inode,
3802 struct ext4_inode_info *ei)
3805 struct inode *inode = &(ei->vfs_inode);
3806 struct super_block *sb = inode->i_sb;
3808 if (EXT4_HAS_RO_COMPAT_FEATURE(sb,
3809 EXT4_FEATURE_RO_COMPAT_HUGE_FILE)) {
3810 /* we are using combined 48 bit field */
3811 i_blocks = ((u64)le16_to_cpu(raw_inode->i_blocks_high)) << 32 |
3812 le32_to_cpu(raw_inode->i_blocks_lo);
3813 if (ext4_test_inode_flag(inode, EXT4_INODE_HUGE_FILE)) {
3814 /* i_blocks represent file system block size */
3815 return i_blocks << (inode->i_blkbits - 9);
3820 return le32_to_cpu(raw_inode->i_blocks_lo);
3824 struct inode *ext4_iget(struct super_block *sb, unsigned long ino)
3826 struct ext4_iloc iloc;
3827 struct ext4_inode *raw_inode;
3828 struct ext4_inode_info *ei;
3829 struct inode *inode;
3830 journal_t *journal = EXT4_SB(sb)->s_journal;
3834 inode = iget_locked(sb, ino);
3836 return ERR_PTR(-ENOMEM);
3837 if (!(inode->i_state & I_NEW))
3843 ret = __ext4_get_inode_loc(inode, &iloc, 0);
3846 raw_inode = ext4_raw_inode(&iloc);
3847 inode->i_mode = le16_to_cpu(raw_inode->i_mode);
3848 inode->i_uid = (uid_t)le16_to_cpu(raw_inode->i_uid_low);
3849 inode->i_gid = (gid_t)le16_to_cpu(raw_inode->i_gid_low);
3850 if (!(test_opt(inode->i_sb, NO_UID32))) {
3851 inode->i_uid |= le16_to_cpu(raw_inode->i_uid_high) << 16;
3852 inode->i_gid |= le16_to_cpu(raw_inode->i_gid_high) << 16;
3854 set_nlink(inode, le16_to_cpu(raw_inode->i_links_count));
3856 ext4_clear_state_flags(ei); /* Only relevant on 32-bit archs */
3857 ei->i_dir_start_lookup = 0;
3858 ei->i_dtime = le32_to_cpu(raw_inode->i_dtime);
3859 /* We now have enough fields to check if the inode was active or not.
3860 * This is needed because nfsd might try to access dead inodes
3861 * the test is that same one that e2fsck uses
3862 * NeilBrown 1999oct15
3864 if (inode->i_nlink == 0) {
3865 if (inode->i_mode == 0 ||
3866 !(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_ORPHAN_FS)) {
3867 /* this inode is deleted */
3871 /* The only unlinked inodes we let through here have
3872 * valid i_mode and are being read by the orphan
3873 * recovery code: that's fine, we're about to complete
3874 * the process of deleting those. */
3876 ei->i_flags = le32_to_cpu(raw_inode->i_flags);
3877 inode->i_blocks = ext4_inode_blocks(raw_inode, ei);
3878 ei->i_file_acl = le32_to_cpu(raw_inode->i_file_acl_lo);
3879 if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_64BIT))
3881 ((__u64)le16_to_cpu(raw_inode->i_file_acl_high)) << 32;
3882 inode->i_size = ext4_isize(raw_inode);
3883 ei->i_disksize = inode->i_size;
3885 ei->i_reserved_quota = 0;
3887 inode->i_generation = le32_to_cpu(raw_inode->i_generation);
3888 ei->i_block_group = iloc.block_group;
3889 ei->i_last_alloc_group = ~0;
3891 * NOTE! The in-memory inode i_data array is in little-endian order
3892 * even on big-endian machines: we do NOT byteswap the block numbers!
3894 for (block = 0; block < EXT4_N_BLOCKS; block++)
3895 ei->i_data[block] = raw_inode->i_block[block];
3896 INIT_LIST_HEAD(&ei->i_orphan);
3899 * Set transaction id's of transactions that have to be committed
3900 * to finish f[data]sync. We set them to currently running transaction
3901 * as we cannot be sure that the inode or some of its metadata isn't
3902 * part of the transaction - the inode could have been reclaimed and
3903 * now it is reread from disk.
3906 transaction_t *transaction;
3909 read_lock(&journal->j_state_lock);
3910 if (journal->j_running_transaction)
3911 transaction = journal->j_running_transaction;
3913 transaction = journal->j_committing_transaction;
3915 tid = transaction->t_tid;
3917 tid = journal->j_commit_sequence;
3918 read_unlock(&journal->j_state_lock);
3919 ei->i_sync_tid = tid;
3920 ei->i_datasync_tid = tid;
3923 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
3924 ei->i_extra_isize = le16_to_cpu(raw_inode->i_extra_isize);
3925 if (EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize >
3926 EXT4_INODE_SIZE(inode->i_sb)) {
3930 if (ei->i_extra_isize == 0) {
3931 /* The extra space is currently unused. Use it. */
3932 ei->i_extra_isize = sizeof(struct ext4_inode) -
3933 EXT4_GOOD_OLD_INODE_SIZE;
3935 __le32 *magic = (void *)raw_inode +
3936 EXT4_GOOD_OLD_INODE_SIZE +
3938 if (*magic == cpu_to_le32(EXT4_XATTR_MAGIC))
3939 ext4_set_inode_state(inode, EXT4_STATE_XATTR);
3942 ei->i_extra_isize = 0;
3944 EXT4_INODE_GET_XTIME(i_ctime, inode, raw_inode);
3945 EXT4_INODE_GET_XTIME(i_mtime, inode, raw_inode);
3946 EXT4_INODE_GET_XTIME(i_atime, inode, raw_inode);
3947 EXT4_EINODE_GET_XTIME(i_crtime, ei, raw_inode);
3949 inode->i_version = le32_to_cpu(raw_inode->i_disk_version);
3950 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
3951 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
3953 (__u64)(le32_to_cpu(raw_inode->i_version_hi)) << 32;
3957 if (ei->i_file_acl &&
3958 !ext4_data_block_valid(EXT4_SB(sb), ei->i_file_acl, 1)) {
3959 EXT4_ERROR_INODE(inode, "bad extended attribute block %llu",
3963 } else if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
3964 if (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
3965 (S_ISLNK(inode->i_mode) &&
3966 !ext4_inode_is_fast_symlink(inode)))
3967 /* Validate extent which is part of inode */
3968 ret = ext4_ext_check_inode(inode);
3969 } else if (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
3970 (S_ISLNK(inode->i_mode) &&
3971 !ext4_inode_is_fast_symlink(inode))) {
3972 /* Validate block references which are part of inode */
3973 ret = ext4_ind_check_inode(inode);
3978 if (S_ISREG(inode->i_mode)) {
3979 inode->i_op = &ext4_file_inode_operations;
3980 inode->i_fop = &ext4_file_operations;
3981 ext4_set_aops(inode);
3982 } else if (S_ISDIR(inode->i_mode)) {
3983 inode->i_op = &ext4_dir_inode_operations;
3984 inode->i_fop = &ext4_dir_operations;
3985 } else if (S_ISLNK(inode->i_mode)) {
3986 if (ext4_inode_is_fast_symlink(inode)) {
3987 inode->i_op = &ext4_fast_symlink_inode_operations;
3988 nd_terminate_link(ei->i_data, inode->i_size,
3989 sizeof(ei->i_data) - 1);
3991 inode->i_op = &ext4_symlink_inode_operations;
3992 ext4_set_aops(inode);
3994 } else if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode) ||
3995 S_ISFIFO(inode->i_mode) || S_ISSOCK(inode->i_mode)) {
3996 inode->i_op = &ext4_special_inode_operations;
3997 if (raw_inode->i_block[0])
3998 init_special_inode(inode, inode->i_mode,
3999 old_decode_dev(le32_to_cpu(raw_inode->i_block[0])));
4001 init_special_inode(inode, inode->i_mode,
4002 new_decode_dev(le32_to_cpu(raw_inode->i_block[1])));
4005 EXT4_ERROR_INODE(inode, "bogus i_mode (%o)", inode->i_mode);
4009 ext4_set_inode_flags(inode);
4010 unlock_new_inode(inode);
4016 return ERR_PTR(ret);
4019 struct inode *ext4_iget_normal(struct super_block *sb, unsigned long ino)
4021 if (ino < EXT4_FIRST_INO(sb) && ino != EXT4_ROOT_INO)
4022 return ERR_PTR(-EIO);
4023 return ext4_iget(sb, ino);
4026 static int ext4_inode_blocks_set(handle_t *handle,
4027 struct ext4_inode *raw_inode,
4028 struct ext4_inode_info *ei)
4030 struct inode *inode = &(ei->vfs_inode);
4031 u64 i_blocks = inode->i_blocks;
4032 struct super_block *sb = inode->i_sb;
4034 if (i_blocks <= ~0U) {
4036 * i_blocks can be represnted in a 32 bit variable
4037 * as multiple of 512 bytes
4039 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
4040 raw_inode->i_blocks_high = 0;
4041 ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
4044 if (!EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_HUGE_FILE))
4047 if (i_blocks <= 0xffffffffffffULL) {
4049 * i_blocks can be represented in a 48 bit variable
4050 * as multiple of 512 bytes
4052 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
4053 raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
4054 ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
4056 ext4_set_inode_flag(inode, EXT4_INODE_HUGE_FILE);
4057 /* i_block is stored in file system block size */
4058 i_blocks = i_blocks >> (inode->i_blkbits - 9);
4059 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
4060 raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
4066 * Post the struct inode info into an on-disk inode location in the
4067 * buffer-cache. This gobbles the caller's reference to the
4068 * buffer_head in the inode location struct.
4070 * The caller must have write access to iloc->bh.
4072 static int ext4_do_update_inode(handle_t *handle,
4073 struct inode *inode,
4074 struct ext4_iloc *iloc)
4076 struct ext4_inode *raw_inode = ext4_raw_inode(iloc);
4077 struct ext4_inode_info *ei = EXT4_I(inode);
4078 struct buffer_head *bh = iloc->bh;
4079 int err = 0, rc, block;
4080 int need_datasync = 0;
4082 /* For fields not not tracking in the in-memory inode,
4083 * initialise them to zero for new inodes. */
4084 if (ext4_test_inode_state(inode, EXT4_STATE_NEW))
4085 memset(raw_inode, 0, EXT4_SB(inode->i_sb)->s_inode_size);
4087 ext4_get_inode_flags(ei);
4088 raw_inode->i_mode = cpu_to_le16(inode->i_mode);
4089 if (!(test_opt(inode->i_sb, NO_UID32))) {
4090 raw_inode->i_uid_low = cpu_to_le16(low_16_bits(inode->i_uid));
4091 raw_inode->i_gid_low = cpu_to_le16(low_16_bits(inode->i_gid));
4093 * Fix up interoperability with old kernels. Otherwise, old inodes get
4094 * re-used with the upper 16 bits of the uid/gid intact
4096 if (ei->i_dtime && list_empty(&ei->i_orphan)) {
4097 raw_inode->i_uid_high = 0;
4098 raw_inode->i_gid_high = 0;
4100 raw_inode->i_uid_high =
4101 cpu_to_le16(high_16_bits(inode->i_uid));
4102 raw_inode->i_gid_high =
4103 cpu_to_le16(high_16_bits(inode->i_gid));
4106 raw_inode->i_uid_low =
4107 cpu_to_le16(fs_high2lowuid(inode->i_uid));
4108 raw_inode->i_gid_low =
4109 cpu_to_le16(fs_high2lowgid(inode->i_gid));
4110 raw_inode->i_uid_high = 0;
4111 raw_inode->i_gid_high = 0;
4113 raw_inode->i_links_count = cpu_to_le16(inode->i_nlink);
4115 EXT4_INODE_SET_XTIME(i_ctime, inode, raw_inode);
4116 EXT4_INODE_SET_XTIME(i_mtime, inode, raw_inode);
4117 EXT4_INODE_SET_XTIME(i_atime, inode, raw_inode);
4118 EXT4_EINODE_SET_XTIME(i_crtime, ei, raw_inode);
4120 if (ext4_inode_blocks_set(handle, raw_inode, ei))
4122 raw_inode->i_dtime = cpu_to_le32(ei->i_dtime);
4123 raw_inode->i_flags = cpu_to_le32(ei->i_flags & 0xFFFFFFFF);
4124 if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
4125 cpu_to_le32(EXT4_OS_HURD))
4126 raw_inode->i_file_acl_high =
4127 cpu_to_le16(ei->i_file_acl >> 32);
4128 raw_inode->i_file_acl_lo = cpu_to_le32(ei->i_file_acl);
4129 if (ei->i_disksize != ext4_isize(raw_inode)) {
4130 ext4_isize_set(raw_inode, ei->i_disksize);
4133 if (ei->i_disksize > 0x7fffffffULL) {
4134 struct super_block *sb = inode->i_sb;
4135 if (!EXT4_HAS_RO_COMPAT_FEATURE(sb,
4136 EXT4_FEATURE_RO_COMPAT_LARGE_FILE) ||
4137 EXT4_SB(sb)->s_es->s_rev_level ==
4138 cpu_to_le32(EXT4_GOOD_OLD_REV)) {
4139 /* If this is the first large file
4140 * created, add a flag to the superblock.
4142 err = ext4_journal_get_write_access(handle,
4143 EXT4_SB(sb)->s_sbh);
4146 ext4_update_dynamic_rev(sb);
4147 EXT4_SET_RO_COMPAT_FEATURE(sb,
4148 EXT4_FEATURE_RO_COMPAT_LARGE_FILE);
4150 ext4_handle_sync(handle);
4151 err = ext4_handle_dirty_metadata(handle, NULL,
4152 EXT4_SB(sb)->s_sbh);
4155 raw_inode->i_generation = cpu_to_le32(inode->i_generation);
4156 if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) {
4157 if (old_valid_dev(inode->i_rdev)) {
4158 raw_inode->i_block[0] =
4159 cpu_to_le32(old_encode_dev(inode->i_rdev));
4160 raw_inode->i_block[1] = 0;
4162 raw_inode->i_block[0] = 0;
4163 raw_inode->i_block[1] =
4164 cpu_to_le32(new_encode_dev(inode->i_rdev));
4165 raw_inode->i_block[2] = 0;
4168 for (block = 0; block < EXT4_N_BLOCKS; block++)
4169 raw_inode->i_block[block] = ei->i_data[block];
4171 raw_inode->i_disk_version = cpu_to_le32(inode->i_version);
4172 if (ei->i_extra_isize) {
4173 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
4174 raw_inode->i_version_hi =
4175 cpu_to_le32(inode->i_version >> 32);
4176 raw_inode->i_extra_isize = cpu_to_le16(ei->i_extra_isize);
4179 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
4180 rc = ext4_handle_dirty_metadata(handle, NULL, bh);
4183 ext4_clear_inode_state(inode, EXT4_STATE_NEW);
4185 ext4_update_inode_fsync_trans(handle, inode, need_datasync);
4188 ext4_std_error(inode->i_sb, err);
4193 * ext4_write_inode()
4195 * We are called from a few places:
4197 * - Within generic_file_write() for O_SYNC files.
4198 * Here, there will be no transaction running. We wait for any running
4199 * trasnaction to commit.
4201 * - Within sys_sync(), kupdate and such.
4202 * We wait on commit, if tol to.
4204 * - Within prune_icache() (PF_MEMALLOC == true)
4205 * Here we simply return. We can't afford to block kswapd on the
4208 * In all cases it is actually safe for us to return without doing anything,
4209 * because the inode has been copied into a raw inode buffer in
4210 * ext4_mark_inode_dirty(). This is a correctness thing for O_SYNC and for
4213 * Note that we are absolutely dependent upon all inode dirtiers doing the
4214 * right thing: they *must* call mark_inode_dirty() after dirtying info in
4215 * which we are interested.
4217 * It would be a bug for them to not do this. The code:
4219 * mark_inode_dirty(inode)
4221 * inode->i_size = expr;
4223 * is in error because a kswapd-driven write_inode() could occur while
4224 * `stuff()' is running, and the new i_size will be lost. Plus the inode
4225 * will no longer be on the superblock's dirty inode list.
4227 int ext4_write_inode(struct inode *inode, struct writeback_control *wbc)
4231 if (current->flags & PF_MEMALLOC)
4234 if (EXT4_SB(inode->i_sb)->s_journal) {
4235 if (ext4_journal_current_handle()) {
4236 jbd_debug(1, "called recursively, non-PF_MEMALLOC!\n");
4241 if (wbc->sync_mode != WB_SYNC_ALL)
4244 err = ext4_force_commit(inode->i_sb);
4246 struct ext4_iloc iloc;
4248 err = __ext4_get_inode_loc(inode, &iloc, 0);
4251 if (wbc->sync_mode == WB_SYNC_ALL)
4252 sync_dirty_buffer(iloc.bh);
4253 if (buffer_req(iloc.bh) && !buffer_uptodate(iloc.bh)) {
4254 EXT4_ERROR_INODE_BLOCK(inode, iloc.bh->b_blocknr,
4255 "IO error syncing inode");
4266 * Called from notify_change.
4268 * We want to trap VFS attempts to truncate the file as soon as
4269 * possible. In particular, we want to make sure that when the VFS
4270 * shrinks i_size, we put the inode on the orphan list and modify
4271 * i_disksize immediately, so that during the subsequent flushing of
4272 * dirty pages and freeing of disk blocks, we can guarantee that any
4273 * commit will leave the blocks being flushed in an unused state on
4274 * disk. (On recovery, the inode will get truncated and the blocks will
4275 * be freed, so we have a strong guarantee that no future commit will
4276 * leave these blocks visible to the user.)
4278 * Another thing we have to assure is that if we are in ordered mode
4279 * and inode is still attached to the committing transaction, we must
4280 * we start writeout of all the dirty pages which are being truncated.
4281 * This way we are sure that all the data written in the previous
4282 * transaction are already on disk (truncate waits for pages under
4285 * Called with inode->i_mutex down.
4287 int ext4_setattr(struct dentry *dentry, struct iattr *attr)
4289 struct inode *inode = dentry->d_inode;
4292 const unsigned int ia_valid = attr->ia_valid;
4294 error = setattr_prepare(dentry, attr);
4298 if (is_quota_modification(inode, attr))
4299 dquot_initialize(inode);
4300 if ((ia_valid & ATTR_UID && attr->ia_uid != inode->i_uid) ||
4301 (ia_valid & ATTR_GID && attr->ia_gid != inode->i_gid)) {
4304 /* (user+group)*(old+new) structure, inode write (sb,
4305 * inode block, ? - but truncate inode update has it) */
4306 handle = ext4_journal_start(inode, (EXT4_MAXQUOTAS_INIT_BLOCKS(inode->i_sb)+
4307 EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb))+3);
4308 if (IS_ERR(handle)) {
4309 error = PTR_ERR(handle);
4312 error = dquot_transfer(inode, attr);
4314 ext4_journal_stop(handle);
4317 /* Update corresponding info in inode so that everything is in
4318 * one transaction */
4319 if (attr->ia_valid & ATTR_UID)
4320 inode->i_uid = attr->ia_uid;
4321 if (attr->ia_valid & ATTR_GID)
4322 inode->i_gid = attr->ia_gid;
4323 error = ext4_mark_inode_dirty(handle, inode);
4324 ext4_journal_stop(handle);
4327 if (attr->ia_valid & ATTR_SIZE) {
4328 inode_dio_wait(inode);
4330 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
4331 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4333 if (attr->ia_size > sbi->s_bitmap_maxbytes)
4338 if (S_ISREG(inode->i_mode) &&
4339 attr->ia_valid & ATTR_SIZE &&
4340 (attr->ia_size < inode->i_size)) {
4343 handle = ext4_journal_start(inode, 3);
4344 if (IS_ERR(handle)) {
4345 error = PTR_ERR(handle);
4348 if (ext4_handle_valid(handle)) {
4349 error = ext4_orphan_add(handle, inode);
4352 EXT4_I(inode)->i_disksize = attr->ia_size;
4353 rc = ext4_mark_inode_dirty(handle, inode);
4356 ext4_journal_stop(handle);
4358 if (ext4_should_order_data(inode)) {
4359 error = ext4_begin_ordered_truncate(inode,
4362 /* Do as much error cleanup as possible */
4363 handle = ext4_journal_start(inode, 3);
4364 if (IS_ERR(handle)) {
4365 ext4_orphan_del(NULL, inode);
4368 ext4_orphan_del(handle, inode);
4370 ext4_journal_stop(handle);
4376 if (attr->ia_valid & ATTR_SIZE) {
4377 if (attr->ia_size != i_size_read(inode)) {
4378 truncate_setsize(inode, attr->ia_size);
4379 ext4_truncate(inode);
4380 } else if (ext4_test_inode_flag(inode, EXT4_INODE_EOFBLOCKS))
4381 ext4_truncate(inode);
4385 setattr_copy(inode, attr);
4386 mark_inode_dirty(inode);
4390 * If the call to ext4_truncate failed to get a transaction handle at
4391 * all, we need to clean up the in-core orphan list manually.
4393 if (orphan && inode->i_nlink)
4394 ext4_orphan_del(NULL, inode);
4396 if (!rc && (ia_valid & ATTR_MODE))
4397 rc = ext4_acl_chmod(inode);
4400 ext4_std_error(inode->i_sb, error);
4406 int ext4_getattr(struct vfsmount *mnt, struct dentry *dentry,
4409 struct inode *inode;
4410 unsigned long long delalloc_blocks;
4412 inode = dentry->d_inode;
4413 generic_fillattr(inode, stat);
4416 * We can't update i_blocks if the block allocation is delayed
4417 * otherwise in the case of system crash before the real block
4418 * allocation is done, we will have i_blocks inconsistent with
4419 * on-disk file blocks.
4420 * We always keep i_blocks updated together with real
4421 * allocation. But to not confuse with user, stat
4422 * will return the blocks that include the delayed allocation
4423 * blocks for this file.
4425 delalloc_blocks = EXT4_I(inode)->i_reserved_data_blocks;
4427 stat->blocks += delalloc_blocks << (inode->i_sb->s_blocksize_bits-9);
4431 static int ext4_index_trans_blocks(struct inode *inode, int nrblocks, int chunk)
4433 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
4434 return ext4_ind_trans_blocks(inode, nrblocks, chunk);
4435 return ext4_ext_index_trans_blocks(inode, nrblocks, chunk);
4439 * Account for index blocks, block groups bitmaps and block group
4440 * descriptor blocks if modify datablocks and index blocks
4441 * worse case, the indexs blocks spread over different block groups
4443 * If datablocks are discontiguous, they are possible to spread over
4444 * different block groups too. If they are contiuguous, with flexbg,
4445 * they could still across block group boundary.
4447 * Also account for superblock, inode, quota and xattr blocks
4449 static int ext4_meta_trans_blocks(struct inode *inode, int nrblocks, int chunk)
4451 ext4_group_t groups, ngroups = ext4_get_groups_count(inode->i_sb);
4457 * How many index blocks need to touch to modify nrblocks?
4458 * The "Chunk" flag indicating whether the nrblocks is
4459 * physically contiguous on disk
4461 * For Direct IO and fallocate, they calls get_block to allocate
4462 * one single extent at a time, so they could set the "Chunk" flag
4464 idxblocks = ext4_index_trans_blocks(inode, nrblocks, chunk);
4469 * Now let's see how many group bitmaps and group descriptors need
4479 if (groups > ngroups)
4481 if (groups > EXT4_SB(inode->i_sb)->s_gdb_count)
4482 gdpblocks = EXT4_SB(inode->i_sb)->s_gdb_count;
4484 /* bitmaps and block group descriptor blocks */
4485 ret += groups + gdpblocks;
4487 /* Blocks for super block, inode, quota and xattr blocks */
4488 ret += EXT4_META_TRANS_BLOCKS(inode->i_sb);
4494 * Calculate the total number of credits to reserve to fit
4495 * the modification of a single pages into a single transaction,
4496 * which may include multiple chunks of block allocations.
4498 * This could be called via ext4_write_begin()
4500 * We need to consider the worse case, when
4501 * one new block per extent.
4503 int ext4_writepage_trans_blocks(struct inode *inode)
4505 int bpp = ext4_journal_blocks_per_page(inode);
4508 ret = ext4_meta_trans_blocks(inode, bpp, 0);
4510 /* Account for data blocks for journalled mode */
4511 if (ext4_should_journal_data(inode))
4517 * Calculate the journal credits for a chunk of data modification.
4519 * This is called from DIO, fallocate or whoever calling
4520 * ext4_map_blocks() to map/allocate a chunk of contiguous disk blocks.
4522 * journal buffers for data blocks are not included here, as DIO
4523 * and fallocate do no need to journal data buffers.
4525 int ext4_chunk_trans_blocks(struct inode *inode, int nrblocks)
4527 return ext4_meta_trans_blocks(inode, nrblocks, 1);
4531 * The caller must have previously called ext4_reserve_inode_write().
4532 * Give this, we know that the caller already has write access to iloc->bh.
4534 int ext4_mark_iloc_dirty(handle_t *handle,
4535 struct inode *inode, struct ext4_iloc *iloc)
4539 if (test_opt(inode->i_sb, I_VERSION))
4540 inode_inc_iversion(inode);
4542 /* the do_update_inode consumes one bh->b_count */
4545 /* ext4_do_update_inode() does jbd2_journal_dirty_metadata */
4546 err = ext4_do_update_inode(handle, inode, iloc);
4552 * On success, We end up with an outstanding reference count against
4553 * iloc->bh. This _must_ be cleaned up later.
4557 ext4_reserve_inode_write(handle_t *handle, struct inode *inode,
4558 struct ext4_iloc *iloc)
4562 err = ext4_get_inode_loc(inode, iloc);
4564 BUFFER_TRACE(iloc->bh, "get_write_access");
4565 err = ext4_journal_get_write_access(handle, iloc->bh);
4571 ext4_std_error(inode->i_sb, err);
4576 * Expand an inode by new_extra_isize bytes.
4577 * Returns 0 on success or negative error number on failure.
4579 static int ext4_expand_extra_isize(struct inode *inode,
4580 unsigned int new_extra_isize,
4581 struct ext4_iloc iloc,
4584 struct ext4_inode *raw_inode;
4585 struct ext4_xattr_ibody_header *header;
4587 if (EXT4_I(inode)->i_extra_isize >= new_extra_isize)
4590 raw_inode = ext4_raw_inode(&iloc);
4592 header = IHDR(inode, raw_inode);
4594 /* No extended attributes present */
4595 if (!ext4_test_inode_state(inode, EXT4_STATE_XATTR) ||
4596 header->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC)) {
4597 memset((void *)raw_inode + EXT4_GOOD_OLD_INODE_SIZE, 0,
4599 EXT4_I(inode)->i_extra_isize = new_extra_isize;
4603 /* try to expand with EAs present */
4604 return ext4_expand_extra_isize_ea(inode, new_extra_isize,
4609 * What we do here is to mark the in-core inode as clean with respect to inode
4610 * dirtiness (it may still be data-dirty).
4611 * This means that the in-core inode may be reaped by prune_icache
4612 * without having to perform any I/O. This is a very good thing,
4613 * because *any* task may call prune_icache - even ones which
4614 * have a transaction open against a different journal.
4616 * Is this cheating? Not really. Sure, we haven't written the
4617 * inode out, but prune_icache isn't a user-visible syncing function.
4618 * Whenever the user wants stuff synced (sys_sync, sys_msync, sys_fsync)
4619 * we start and wait on commits.
4621 * Is this efficient/effective? Well, we're being nice to the system
4622 * by cleaning up our inodes proactively so they can be reaped
4623 * without I/O. But we are potentially leaving up to five seconds'
4624 * worth of inodes floating about which prune_icache wants us to
4625 * write out. One way to fix that would be to get prune_icache()
4626 * to do a write_super() to free up some memory. It has the desired
4629 int ext4_mark_inode_dirty(handle_t *handle, struct inode *inode)
4631 struct ext4_iloc iloc;
4632 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4633 static unsigned int mnt_count;
4637 trace_ext4_mark_inode_dirty(inode, _RET_IP_);
4638 err = ext4_reserve_inode_write(handle, inode, &iloc);
4641 if (ext4_handle_valid(handle) &&
4642 EXT4_I(inode)->i_extra_isize < sbi->s_want_extra_isize &&
4643 !ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND)) {
4645 * We need extra buffer credits since we may write into EA block
4646 * with this same handle. If journal_extend fails, then it will
4647 * only result in a minor loss of functionality for that inode.
4648 * If this is felt to be critical, then e2fsck should be run to
4649 * force a large enough s_min_extra_isize.
4651 if ((jbd2_journal_extend(handle,
4652 EXT4_DATA_TRANS_BLOCKS(inode->i_sb))) == 0) {
4653 ret = ext4_expand_extra_isize(inode,
4654 sbi->s_want_extra_isize,
4657 ext4_set_inode_state(inode,
4658 EXT4_STATE_NO_EXPAND);
4660 le16_to_cpu(sbi->s_es->s_mnt_count)) {
4661 ext4_warning(inode->i_sb,
4662 "Unable to expand inode %lu. Delete"
4663 " some EAs or run e2fsck.",
4666 le16_to_cpu(sbi->s_es->s_mnt_count);
4671 return ext4_mark_iloc_dirty(handle, inode, &iloc);
4675 * ext4_dirty_inode() is called from __mark_inode_dirty()
4677 * We're really interested in the case where a file is being extended.
4678 * i_size has been changed by generic_commit_write() and we thus need
4679 * to include the updated inode in the current transaction.
4681 * Also, dquot_alloc_block() will always dirty the inode when blocks
4682 * are allocated to the file.
4684 * If the inode is marked synchronous, we don't honour that here - doing
4685 * so would cause a commit on atime updates, which we don't bother doing.
4686 * We handle synchronous inodes at the highest possible level.
4688 void ext4_dirty_inode(struct inode *inode, int flags)
4692 handle = ext4_journal_start(inode, 2);
4696 ext4_mark_inode_dirty(handle, inode);
4698 ext4_journal_stop(handle);
4705 * Bind an inode's backing buffer_head into this transaction, to prevent
4706 * it from being flushed to disk early. Unlike
4707 * ext4_reserve_inode_write, this leaves behind no bh reference and
4708 * returns no iloc structure, so the caller needs to repeat the iloc
4709 * lookup to mark the inode dirty later.
4711 static int ext4_pin_inode(handle_t *handle, struct inode *inode)
4713 struct ext4_iloc iloc;
4717 err = ext4_get_inode_loc(inode, &iloc);
4719 BUFFER_TRACE(iloc.bh, "get_write_access");
4720 err = jbd2_journal_get_write_access(handle, iloc.bh);
4722 err = ext4_handle_dirty_metadata(handle,
4728 ext4_std_error(inode->i_sb, err);
4733 int ext4_change_inode_journal_flag(struct inode *inode, int val)
4740 * We have to be very careful here: changing a data block's
4741 * journaling status dynamically is dangerous. If we write a
4742 * data block to the journal, change the status and then delete
4743 * that block, we risk forgetting to revoke the old log record
4744 * from the journal and so a subsequent replay can corrupt data.
4745 * So, first we make sure that the journal is empty and that
4746 * nobody is changing anything.
4749 journal = EXT4_JOURNAL(inode);
4752 if (is_journal_aborted(journal))
4755 jbd2_journal_lock_updates(journal);
4756 jbd2_journal_flush(journal);
4759 * OK, there are no updates running now, and all cached data is
4760 * synced to disk. We are now in a completely consistent state
4761 * which doesn't have anything in the journal, and we know that
4762 * no filesystem updates are running, so it is safe to modify
4763 * the inode's in-core data-journaling state flag now.
4767 ext4_set_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
4769 ext4_clear_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
4770 ext4_set_aops(inode);
4772 jbd2_journal_unlock_updates(journal);
4774 /* Finally we can mark the inode as dirty. */
4776 handle = ext4_journal_start(inode, 1);
4778 return PTR_ERR(handle);
4780 err = ext4_mark_inode_dirty(handle, inode);
4781 ext4_handle_sync(handle);
4782 ext4_journal_stop(handle);
4783 ext4_std_error(inode->i_sb, err);
4788 static int ext4_bh_unmapped(handle_t *handle, struct buffer_head *bh)
4790 return !buffer_mapped(bh);
4793 int ext4_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
4795 struct page *page = vmf->page;
4799 struct file *file = vma->vm_file;
4800 struct inode *inode = file->f_path.dentry->d_inode;
4801 struct address_space *mapping = inode->i_mapping;
4803 get_block_t *get_block;
4807 * This check is racy but catches the common case. We rely on
4808 * __block_page_mkwrite() to do a reliable check.
4810 vfs_check_frozen(inode->i_sb, SB_FREEZE_WRITE);
4811 /* Delalloc case is easy... */
4812 if (test_opt(inode->i_sb, DELALLOC) &&
4813 !ext4_should_journal_data(inode) &&
4814 !ext4_nonda_switch(inode->i_sb)) {
4816 ret = __block_page_mkwrite(vma, vmf,
4817 ext4_da_get_block_prep);
4818 } while (ret == -ENOSPC &&
4819 ext4_should_retry_alloc(inode->i_sb, &retries));
4824 size = i_size_read(inode);
4825 /* Page got truncated from under us? */
4826 if (page->mapping != mapping || page_offset(page) > size) {
4828 ret = VM_FAULT_NOPAGE;
4832 if (page->index == size >> PAGE_CACHE_SHIFT)
4833 len = size & ~PAGE_CACHE_MASK;
4835 len = PAGE_CACHE_SIZE;
4837 * Return if we have all the buffers mapped. This avoids the need to do
4838 * journal_start/journal_stop which can block and take a long time
4840 if (page_has_buffers(page)) {
4841 if (!walk_page_buffers(NULL, page_buffers(page), 0, len, NULL,
4842 ext4_bh_unmapped)) {
4843 /* Wait so that we don't change page under IO */
4844 wait_on_page_writeback(page);
4845 ret = VM_FAULT_LOCKED;
4850 /* OK, we need to fill the hole... */
4851 if (ext4_should_dioread_nolock(inode))
4852 get_block = ext4_get_block_write;
4854 get_block = ext4_get_block;
4856 handle = ext4_journal_start(inode, ext4_writepage_trans_blocks(inode));
4857 if (IS_ERR(handle)) {
4858 ret = VM_FAULT_SIGBUS;
4861 ret = __block_page_mkwrite(vma, vmf, get_block);
4862 if (!ret && ext4_should_journal_data(inode)) {
4863 if (walk_page_buffers(handle, page_buffers(page), 0,
4864 PAGE_CACHE_SIZE, NULL, do_journal_get_write_access)) {
4866 ret = VM_FAULT_SIGBUS;
4867 ext4_journal_stop(handle);
4870 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
4872 ext4_journal_stop(handle);
4873 if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
4876 ret = block_page_mkwrite_return(ret);