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>
42 #include "ext4_jbd2.h"
47 #include <trace/events/ext4.h>
49 #define MPAGE_DA_EXTENT_TAIL 0x01
51 static inline int ext4_begin_ordered_truncate(struct inode *inode,
54 trace_ext4_begin_ordered_truncate(inode, new_size);
56 * If jinode is zero, then we never opened the file for
57 * writing, so there's no need to call
58 * jbd2_journal_begin_ordered_truncate() since there's no
59 * outstanding writes we need to flush.
61 if (!EXT4_I(inode)->jinode)
63 return jbd2_journal_begin_ordered_truncate(EXT4_JOURNAL(inode),
64 EXT4_I(inode)->jinode,
68 static void ext4_invalidatepage(struct page *page, unsigned long offset);
69 static int noalloc_get_block_write(struct inode *inode, sector_t iblock,
70 struct buffer_head *bh_result, int create);
71 static int ext4_set_bh_endio(struct buffer_head *bh, struct inode *inode);
72 static void ext4_end_io_buffer_write(struct buffer_head *bh, int uptodate);
73 static int __ext4_journalled_writepage(struct page *page, unsigned int len);
74 static int ext4_bh_delay_or_unwritten(handle_t *handle, struct buffer_head *bh);
77 * Test whether an inode is a fast symlink.
79 static int ext4_inode_is_fast_symlink(struct inode *inode)
81 int ea_blocks = EXT4_I(inode)->i_file_acl ?
82 (inode->i_sb->s_blocksize >> 9) : 0;
84 return (S_ISLNK(inode->i_mode) && inode->i_blocks - ea_blocks == 0);
88 * Restart the transaction associated with *handle. This does a commit,
89 * so before we call here everything must be consistently dirtied against
92 int ext4_truncate_restart_trans(handle_t *handle, struct inode *inode,
98 * Drop i_data_sem to avoid deadlock with ext4_map_blocks. At this
99 * moment, get_block can be called only for blocks inside i_size since
100 * page cache has been already dropped and writes are blocked by
101 * i_mutex. So we can safely drop the i_data_sem here.
103 BUG_ON(EXT4_JOURNAL(inode) == NULL);
104 jbd_debug(2, "restarting handle %p\n", handle);
105 up_write(&EXT4_I(inode)->i_data_sem);
106 ret = ext4_journal_restart(handle, nblocks);
107 down_write(&EXT4_I(inode)->i_data_sem);
108 ext4_discard_preallocations(inode);
114 * Called at the last iput() if i_nlink is zero.
116 void ext4_evict_inode(struct inode *inode)
121 trace_ext4_evict_inode(inode);
123 ext4_ioend_wait(inode);
125 if (inode->i_nlink) {
127 * When journalling data dirty buffers are tracked only in the
128 * journal. So although mm thinks everything is clean and
129 * ready for reaping the inode might still have some pages to
130 * write in the running transaction or waiting to be
131 * checkpointed. Thus calling jbd2_journal_invalidatepage()
132 * (via truncate_inode_pages()) to discard these buffers can
133 * cause data loss. Also even if we did not discard these
134 * buffers, we would have no way to find them after the inode
135 * is reaped and thus user could see stale data if he tries to
136 * read them before the transaction is checkpointed. So be
137 * careful and force everything to disk here... We use
138 * ei->i_datasync_tid to store the newest transaction
139 * containing inode's data.
141 * Note that directories do not have this problem because they
142 * don't use page cache.
144 if (ext4_should_journal_data(inode) &&
145 (S_ISLNK(inode->i_mode) || S_ISREG(inode->i_mode)) &&
146 inode->i_ino != EXT4_JOURNAL_INO) {
147 journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
148 tid_t commit_tid = EXT4_I(inode)->i_datasync_tid;
150 jbd2_complete_transaction(journal, commit_tid);
151 filemap_write_and_wait(&inode->i_data);
153 truncate_inode_pages(&inode->i_data, 0);
157 if (!is_bad_inode(inode))
158 dquot_initialize(inode);
160 if (ext4_should_order_data(inode))
161 ext4_begin_ordered_truncate(inode, 0);
162 truncate_inode_pages(&inode->i_data, 0);
164 if (is_bad_inode(inode))
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 * Try to see if we can get the block without requesting a new
487 down_read((&EXT4_I(inode)->i_data_sem));
488 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
489 retval = ext4_ext_map_blocks(handle, inode, map, flags &
490 EXT4_GET_BLOCKS_KEEP_SIZE);
492 retval = ext4_ind_map_blocks(handle, inode, map, flags &
493 EXT4_GET_BLOCKS_KEEP_SIZE);
495 up_read((&EXT4_I(inode)->i_data_sem));
497 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
498 int ret = check_block_validity(inode, map);
503 /* If it is only a block(s) look up */
504 if ((flags & EXT4_GET_BLOCKS_CREATE) == 0)
508 * Returns if the blocks have already allocated
510 * Note that if blocks have been preallocated
511 * ext4_ext_get_block() returns the create = 0
512 * with buffer head unmapped.
514 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED)
518 * When we call get_blocks without the create flag, the
519 * BH_Unwritten flag could have gotten set if the blocks
520 * requested were part of a uninitialized extent. We need to
521 * clear this flag now that we are committed to convert all or
522 * part of the uninitialized extent to be an initialized
523 * extent. This is because we need to avoid the combination
524 * of BH_Unwritten and BH_Mapped flags being simultaneously
525 * set on the buffer_head.
527 map->m_flags &= ~EXT4_MAP_UNWRITTEN;
530 * New blocks allocate and/or writing to uninitialized extent
531 * will possibly result in updating i_data, so we take
532 * the write lock of i_data_sem, and call get_blocks()
533 * with create == 1 flag.
535 down_write((&EXT4_I(inode)->i_data_sem));
538 * if the caller is from delayed allocation writeout path
539 * we have already reserved fs blocks for allocation
540 * let the underlying get_block() function know to
541 * avoid double accounting
543 if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
544 ext4_set_inode_state(inode, EXT4_STATE_DELALLOC_RESERVED);
546 * We need to check for EXT4 here because migrate
547 * could have changed the inode type in between
549 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
550 retval = ext4_ext_map_blocks(handle, inode, map, flags);
552 retval = ext4_ind_map_blocks(handle, inode, map, flags);
554 if (retval > 0 && map->m_flags & EXT4_MAP_NEW) {
556 * We allocated new blocks which will result in
557 * i_data's format changing. Force the migrate
558 * to fail by clearing migrate flags
560 ext4_clear_inode_state(inode, EXT4_STATE_EXT_MIGRATE);
564 * Update reserved blocks/metadata blocks after successful
565 * block allocation which had been deferred till now. We don't
566 * support fallocate for non extent files. So we can update
567 * reserve space here.
570 (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE))
571 ext4_da_update_reserve_space(inode, retval, 1);
573 if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) {
574 ext4_clear_inode_state(inode, EXT4_STATE_DELALLOC_RESERVED);
576 /* If we have successfully mapped the delayed allocated blocks,
577 * set the BH_Da_Mapped bit on them. Its important to do this
578 * under the protection of i_data_sem.
580 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED)
581 set_buffers_da_mapped(inode, map);
584 up_write((&EXT4_I(inode)->i_data_sem));
585 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
586 int ret = check_block_validity(inode, map);
593 /* Maximum number of blocks we map for direct IO at once. */
594 #define DIO_MAX_BLOCKS 4096
596 static int _ext4_get_block(struct inode *inode, sector_t iblock,
597 struct buffer_head *bh, int flags)
599 handle_t *handle = ext4_journal_current_handle();
600 struct ext4_map_blocks map;
601 int ret = 0, started = 0;
605 map.m_len = bh->b_size >> inode->i_blkbits;
607 if (flags && !handle) {
608 /* Direct IO write... */
609 if (map.m_len > DIO_MAX_BLOCKS)
610 map.m_len = DIO_MAX_BLOCKS;
611 dio_credits = ext4_chunk_trans_blocks(inode, map.m_len);
612 handle = ext4_journal_start(inode, dio_credits);
613 if (IS_ERR(handle)) {
614 ret = PTR_ERR(handle);
620 ret = ext4_map_blocks(handle, inode, &map, flags);
622 map_bh(bh, inode->i_sb, map.m_pblk);
623 bh->b_state = (bh->b_state & ~EXT4_MAP_FLAGS) | map.m_flags;
624 bh->b_size = inode->i_sb->s_blocksize * map.m_len;
628 ext4_journal_stop(handle);
632 int ext4_get_block(struct inode *inode, sector_t iblock,
633 struct buffer_head *bh, int create)
635 return _ext4_get_block(inode, iblock, bh,
636 create ? EXT4_GET_BLOCKS_CREATE : 0);
640 * `handle' can be NULL if create is zero
642 struct buffer_head *ext4_getblk(handle_t *handle, struct inode *inode,
643 ext4_lblk_t block, int create, int *errp)
645 struct ext4_map_blocks map;
646 struct buffer_head *bh;
649 J_ASSERT(handle != NULL || create == 0);
653 err = ext4_map_blocks(handle, inode, &map,
654 create ? EXT4_GET_BLOCKS_CREATE : 0);
662 bh = sb_getblk(inode->i_sb, map.m_pblk);
667 if (map.m_flags & EXT4_MAP_NEW) {
668 J_ASSERT(create != 0);
669 J_ASSERT(handle != NULL);
672 * Now that we do not always journal data, we should
673 * keep in mind whether this should always journal the
674 * new buffer as metadata. For now, regular file
675 * writes use ext4_get_block instead, so it's not a
679 BUFFER_TRACE(bh, "call get_create_access");
680 fatal = ext4_journal_get_create_access(handle, bh);
681 if (!fatal && !buffer_uptodate(bh)) {
682 memset(bh->b_data, 0, inode->i_sb->s_blocksize);
683 set_buffer_uptodate(bh);
686 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
687 err = ext4_handle_dirty_metadata(handle, inode, bh);
691 BUFFER_TRACE(bh, "not a new buffer");
701 struct buffer_head *ext4_bread(handle_t *handle, struct inode *inode,
702 ext4_lblk_t block, int create, int *err)
704 struct buffer_head *bh;
706 bh = ext4_getblk(handle, inode, block, create, err);
709 if (buffer_uptodate(bh))
711 ll_rw_block(READ | REQ_META | REQ_PRIO, 1, &bh);
713 if (buffer_uptodate(bh))
720 static int walk_page_buffers(handle_t *handle,
721 struct buffer_head *head,
725 int (*fn)(handle_t *handle,
726 struct buffer_head *bh))
728 struct buffer_head *bh;
729 unsigned block_start, block_end;
730 unsigned blocksize = head->b_size;
732 struct buffer_head *next;
734 for (bh = head, block_start = 0;
735 ret == 0 && (bh != head || !block_start);
736 block_start = block_end, bh = next) {
737 next = bh->b_this_page;
738 block_end = block_start + blocksize;
739 if (block_end <= from || block_start >= to) {
740 if (partial && !buffer_uptodate(bh))
744 err = (*fn)(handle, bh);
752 * To preserve ordering, it is essential that the hole instantiation and
753 * the data write be encapsulated in a single transaction. We cannot
754 * close off a transaction and start a new one between the ext4_get_block()
755 * and the commit_write(). So doing the jbd2_journal_start at the start of
756 * prepare_write() is the right place.
758 * Also, this function can nest inside ext4_writepage() ->
759 * block_write_full_page(). In that case, we *know* that ext4_writepage()
760 * has generated enough buffer credits to do the whole page. So we won't
761 * block on the journal in that case, which is good, because the caller may
764 * By accident, ext4 can be reentered when a transaction is open via
765 * quota file writes. If we were to commit the transaction while thus
766 * reentered, there can be a deadlock - we would be holding a quota
767 * lock, and the commit would never complete if another thread had a
768 * transaction open and was blocking on the quota lock - a ranking
771 * So what we do is to rely on the fact that jbd2_journal_stop/journal_start
772 * will _not_ run commit under these circumstances because handle->h_ref
773 * is elevated. We'll still have enough credits for the tiny quotafile
776 static int do_journal_get_write_access(handle_t *handle,
777 struct buffer_head *bh)
779 int dirty = buffer_dirty(bh);
782 if (!buffer_mapped(bh) || buffer_freed(bh))
785 * __block_write_begin() could have dirtied some buffers. Clean
786 * the dirty bit as jbd2_journal_get_write_access() could complain
787 * otherwise about fs integrity issues. Setting of the dirty bit
788 * by __block_write_begin() isn't a real problem here as we clear
789 * the bit before releasing a page lock and thus writeback cannot
790 * ever write the buffer.
793 clear_buffer_dirty(bh);
794 ret = ext4_journal_get_write_access(handle, bh);
796 ret = ext4_handle_dirty_metadata(handle, NULL, bh);
800 static int ext4_get_block_write(struct inode *inode, sector_t iblock,
801 struct buffer_head *bh_result, int create);
802 static int ext4_write_begin(struct file *file, struct address_space *mapping,
803 loff_t pos, unsigned len, unsigned flags,
804 struct page **pagep, void **fsdata)
806 struct inode *inode = mapping->host;
807 int ret, needed_blocks;
814 trace_ext4_write_begin(inode, pos, len, flags);
816 * Reserve one block more for addition to orphan list in case
817 * we allocate blocks but write fails for some reason
819 needed_blocks = ext4_writepage_trans_blocks(inode) + 1;
820 index = pos >> PAGE_CACHE_SHIFT;
821 from = pos & (PAGE_CACHE_SIZE - 1);
825 handle = ext4_journal_start(inode, needed_blocks);
826 if (IS_ERR(handle)) {
827 ret = PTR_ERR(handle);
831 /* We cannot recurse into the filesystem as the transaction is already
833 flags |= AOP_FLAG_NOFS;
835 page = grab_cache_page_write_begin(mapping, index, flags);
837 ext4_journal_stop(handle);
843 if (ext4_should_dioread_nolock(inode))
844 ret = __block_write_begin(page, pos, len, ext4_get_block_write);
846 ret = __block_write_begin(page, pos, len, ext4_get_block);
848 if (!ret && ext4_should_journal_data(inode)) {
849 ret = walk_page_buffers(handle, page_buffers(page),
850 from, to, NULL, do_journal_get_write_access);
855 page_cache_release(page);
857 * __block_write_begin may have instantiated a few blocks
858 * outside i_size. Trim these off again. Don't need
859 * i_size_read because we hold i_mutex.
861 * Add inode to orphan list in case we crash before
864 if (pos + len > inode->i_size && ext4_can_truncate(inode))
865 ext4_orphan_add(handle, inode);
867 ext4_journal_stop(handle);
868 if (pos + len > inode->i_size) {
869 ext4_truncate_failed_write(inode);
871 * If truncate failed early the inode might
872 * still be on the orphan list; we need to
873 * make sure the inode is removed from the
874 * orphan list in that case.
877 ext4_orphan_del(NULL, inode);
881 if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
887 /* For write_end() in data=journal mode */
888 static int write_end_fn(handle_t *handle, struct buffer_head *bh)
890 if (!buffer_mapped(bh) || buffer_freed(bh))
892 set_buffer_uptodate(bh);
893 return ext4_handle_dirty_metadata(handle, NULL, bh);
896 static int ext4_generic_write_end(struct file *file,
897 struct address_space *mapping,
898 loff_t pos, unsigned len, unsigned copied,
899 struct page *page, void *fsdata)
901 int i_size_changed = 0;
902 struct inode *inode = mapping->host;
903 handle_t *handle = ext4_journal_current_handle();
905 copied = block_write_end(file, mapping, pos, len, copied, page, fsdata);
908 * No need to use i_size_read() here, the i_size
909 * cannot change under us because we hold i_mutex.
911 * But it's important to update i_size while still holding page lock:
912 * page writeout could otherwise come in and zero beyond i_size.
914 if (pos + copied > inode->i_size) {
915 i_size_write(inode, pos + copied);
919 if (pos + copied > EXT4_I(inode)->i_disksize) {
920 /* We need to mark inode dirty even if
921 * new_i_size is less that inode->i_size
922 * bu greater than i_disksize.(hint delalloc)
924 ext4_update_i_disksize(inode, (pos + copied));
928 page_cache_release(page);
931 * Don't mark the inode dirty under page lock. First, it unnecessarily
932 * makes the holding time of page lock longer. Second, it forces lock
933 * ordering of page lock and transaction start for journaling
937 ext4_mark_inode_dirty(handle, inode);
943 * We need to pick up the new inode size which generic_commit_write gave us
944 * `file' can be NULL - eg, when called from page_symlink().
946 * ext4 never places buffers on inode->i_mapping->private_list. metadata
947 * buffers are managed internally.
949 static int ext4_ordered_write_end(struct file *file,
950 struct address_space *mapping,
951 loff_t pos, unsigned len, unsigned copied,
952 struct page *page, void *fsdata)
954 handle_t *handle = ext4_journal_current_handle();
955 struct inode *inode = mapping->host;
958 trace_ext4_ordered_write_end(inode, pos, len, copied);
959 ret = ext4_jbd2_file_inode(handle, inode);
962 ret2 = ext4_generic_write_end(file, mapping, pos, len, copied,
965 if (pos + len > inode->i_size && ext4_can_truncate(inode))
966 /* if we have allocated more blocks and copied
967 * less. We will have blocks allocated outside
968 * inode->i_size. So truncate them
970 ext4_orphan_add(handle, inode);
975 page_cache_release(page);
978 ret2 = ext4_journal_stop(handle);
982 if (pos + len > inode->i_size) {
983 ext4_truncate_failed_write(inode);
985 * If truncate failed early the inode might still be
986 * on the orphan list; we need to make sure the inode
987 * is removed from the orphan list in that case.
990 ext4_orphan_del(NULL, inode);
994 return ret ? ret : copied;
997 static int ext4_writeback_write_end(struct file *file,
998 struct address_space *mapping,
999 loff_t pos, unsigned len, unsigned copied,
1000 struct page *page, void *fsdata)
1002 handle_t *handle = ext4_journal_current_handle();
1003 struct inode *inode = mapping->host;
1006 trace_ext4_writeback_write_end(inode, pos, len, copied);
1007 ret2 = ext4_generic_write_end(file, mapping, pos, len, copied,
1010 if (pos + len > inode->i_size && ext4_can_truncate(inode))
1011 /* if we have allocated more blocks and copied
1012 * less. We will have blocks allocated outside
1013 * inode->i_size. So truncate them
1015 ext4_orphan_add(handle, inode);
1020 ret2 = ext4_journal_stop(handle);
1024 if (pos + len > inode->i_size) {
1025 ext4_truncate_failed_write(inode);
1027 * If truncate failed early the inode might still be
1028 * on the orphan list; we need to make sure the inode
1029 * is removed from the orphan list in that case.
1032 ext4_orphan_del(NULL, inode);
1035 return ret ? ret : copied;
1038 static int ext4_journalled_write_end(struct file *file,
1039 struct address_space *mapping,
1040 loff_t pos, unsigned len, unsigned copied,
1041 struct page *page, void *fsdata)
1043 handle_t *handle = ext4_journal_current_handle();
1044 struct inode *inode = mapping->host;
1050 trace_ext4_journalled_write_end(inode, pos, len, copied);
1051 from = pos & (PAGE_CACHE_SIZE - 1);
1054 BUG_ON(!ext4_handle_valid(handle));
1057 if (!PageUptodate(page))
1059 page_zero_new_buffers(page, from+copied, to);
1062 ret = walk_page_buffers(handle, page_buffers(page), from,
1063 to, &partial, write_end_fn);
1065 SetPageUptodate(page);
1066 new_i_size = pos + copied;
1067 if (new_i_size > inode->i_size)
1068 i_size_write(inode, pos+copied);
1069 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
1070 EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
1071 if (new_i_size > EXT4_I(inode)->i_disksize) {
1072 ext4_update_i_disksize(inode, new_i_size);
1073 ret2 = ext4_mark_inode_dirty(handle, inode);
1079 page_cache_release(page);
1080 if (pos + len > inode->i_size && ext4_can_truncate(inode))
1081 /* if we have allocated more blocks and copied
1082 * less. We will have blocks allocated outside
1083 * inode->i_size. So truncate them
1085 ext4_orphan_add(handle, inode);
1087 ret2 = ext4_journal_stop(handle);
1090 if (pos + len > inode->i_size) {
1091 ext4_truncate_failed_write(inode);
1093 * If truncate failed early the inode might still be
1094 * on the orphan list; we need to make sure the inode
1095 * is removed from the orphan list in that case.
1098 ext4_orphan_del(NULL, inode);
1101 return ret ? ret : copied;
1105 * Reserve a single cluster located at lblock
1107 static int ext4_da_reserve_space(struct inode *inode, ext4_lblk_t lblock)
1110 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1111 struct ext4_inode_info *ei = EXT4_I(inode);
1112 unsigned int md_needed;
1114 ext4_lblk_t save_last_lblock;
1118 * We will charge metadata quota at writeout time; this saves
1119 * us from metadata over-estimation, though we may go over by
1120 * a small amount in the end. Here we just reserve for data.
1122 ret = dquot_reserve_block(inode, EXT4_C2B(sbi, 1));
1127 * recalculate the amount of metadata blocks to reserve
1128 * in order to allocate nrblocks
1129 * worse case is one extent per block
1132 spin_lock(&ei->i_block_reservation_lock);
1134 * ext4_calc_metadata_amount() has side effects, which we have
1135 * to be prepared undo if we fail to claim space.
1137 save_len = ei->i_da_metadata_calc_len;
1138 save_last_lblock = ei->i_da_metadata_calc_last_lblock;
1139 md_needed = EXT4_NUM_B2C(sbi,
1140 ext4_calc_metadata_amount(inode, lblock));
1141 trace_ext4_da_reserve_space(inode, md_needed);
1144 * We do still charge estimated metadata to the sb though;
1145 * we cannot afford to run out of free blocks.
1147 if (ext4_claim_free_clusters(sbi, md_needed + 1, 0)) {
1148 ei->i_da_metadata_calc_len = save_len;
1149 ei->i_da_metadata_calc_last_lblock = save_last_lblock;
1150 spin_unlock(&ei->i_block_reservation_lock);
1151 if (ext4_should_retry_alloc(inode->i_sb, &retries)) {
1155 dquot_release_reservation_block(inode, EXT4_C2B(sbi, 1));
1158 ei->i_reserved_data_blocks++;
1159 ei->i_reserved_meta_blocks += md_needed;
1160 spin_unlock(&ei->i_block_reservation_lock);
1162 return 0; /* success */
1165 static void ext4_da_release_space(struct inode *inode, int to_free)
1167 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1168 struct ext4_inode_info *ei = EXT4_I(inode);
1171 return; /* Nothing to release, exit */
1173 spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
1175 trace_ext4_da_release_space(inode, to_free);
1176 if (unlikely(to_free > ei->i_reserved_data_blocks)) {
1178 * if there aren't enough reserved blocks, then the
1179 * counter is messed up somewhere. Since this
1180 * function is called from invalidate page, it's
1181 * harmless to return without any action.
1183 ext4_msg(inode->i_sb, KERN_NOTICE, "ext4_da_release_space: "
1184 "ino %lu, to_free %d with only %d reserved "
1185 "data blocks\n", inode->i_ino, to_free,
1186 ei->i_reserved_data_blocks);
1188 to_free = ei->i_reserved_data_blocks;
1190 ei->i_reserved_data_blocks -= to_free;
1192 if (ei->i_reserved_data_blocks == 0) {
1194 * We can release all of the reserved metadata blocks
1195 * only when we have written all of the delayed
1196 * allocation blocks.
1197 * Note that in case of bigalloc, i_reserved_meta_blocks,
1198 * i_reserved_data_blocks, etc. refer to number of clusters.
1200 percpu_counter_sub(&sbi->s_dirtyclusters_counter,
1201 ei->i_reserved_meta_blocks);
1202 ei->i_reserved_meta_blocks = 0;
1203 ei->i_da_metadata_calc_len = 0;
1206 /* update fs dirty data blocks counter */
1207 percpu_counter_sub(&sbi->s_dirtyclusters_counter, to_free);
1209 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
1211 dquot_release_reservation_block(inode, EXT4_C2B(sbi, to_free));
1214 static void ext4_da_page_release_reservation(struct page *page,
1215 unsigned long offset)
1218 struct buffer_head *head, *bh;
1219 unsigned int curr_off = 0;
1220 struct inode *inode = page->mapping->host;
1221 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1224 head = page_buffers(page);
1227 unsigned int next_off = curr_off + bh->b_size;
1229 if ((offset <= curr_off) && (buffer_delay(bh))) {
1231 clear_buffer_delay(bh);
1232 clear_buffer_da_mapped(bh);
1234 curr_off = next_off;
1235 } while ((bh = bh->b_this_page) != head);
1237 /* If we have released all the blocks belonging to a cluster, then we
1238 * need to release the reserved space for that cluster. */
1239 num_clusters = EXT4_NUM_B2C(sbi, to_release);
1240 while (num_clusters > 0) {
1242 lblk = (page->index << (PAGE_CACHE_SHIFT - inode->i_blkbits)) +
1243 ((num_clusters - 1) << sbi->s_cluster_bits);
1244 if (sbi->s_cluster_ratio == 1 ||
1245 !ext4_find_delalloc_cluster(inode, lblk, 1))
1246 ext4_da_release_space(inode, 1);
1253 * Delayed allocation stuff
1257 * mpage_da_submit_io - walks through extent of pages and try to write
1258 * them with writepage() call back
1260 * @mpd->inode: inode
1261 * @mpd->first_page: first page of the extent
1262 * @mpd->next_page: page after the last page of the extent
1264 * By the time mpage_da_submit_io() is called we expect all blocks
1265 * to be allocated. this may be wrong if allocation failed.
1267 * As pages are already locked by write_cache_pages(), we can't use it
1269 static int mpage_da_submit_io(struct mpage_da_data *mpd,
1270 struct ext4_map_blocks *map)
1272 struct pagevec pvec;
1273 unsigned long index, end;
1274 int ret = 0, err, nr_pages, i;
1275 struct inode *inode = mpd->inode;
1276 struct address_space *mapping = inode->i_mapping;
1277 loff_t size = i_size_read(inode);
1278 unsigned int len, block_start;
1279 struct buffer_head *bh, *page_bufs = NULL;
1280 int journal_data = ext4_should_journal_data(inode);
1281 sector_t pblock = 0, cur_logical = 0;
1282 struct ext4_io_submit io_submit;
1284 BUG_ON(mpd->next_page <= mpd->first_page);
1285 memset(&io_submit, 0, sizeof(io_submit));
1287 * We need to start from the first_page to the next_page - 1
1288 * to make sure we also write the mapped dirty buffer_heads.
1289 * If we look at mpd->b_blocknr we would only be looking
1290 * at the currently mapped buffer_heads.
1292 index = mpd->first_page;
1293 end = mpd->next_page - 1;
1295 pagevec_init(&pvec, 0);
1296 while (index <= end) {
1297 nr_pages = pagevec_lookup(&pvec, mapping, index, PAGEVEC_SIZE);
1300 for (i = 0; i < nr_pages; i++) {
1301 int commit_write = 0, skip_page = 0;
1302 struct page *page = pvec.pages[i];
1304 index = page->index;
1308 if (index == size >> PAGE_CACHE_SHIFT)
1309 len = size & ~PAGE_CACHE_MASK;
1311 len = PAGE_CACHE_SIZE;
1313 cur_logical = index << (PAGE_CACHE_SHIFT -
1315 pblock = map->m_pblk + (cur_logical -
1320 BUG_ON(!PageLocked(page));
1321 BUG_ON(PageWriteback(page));
1324 * If the page does not have buffers (for
1325 * whatever reason), try to create them using
1326 * __block_write_begin. If this fails,
1327 * skip the page and move on.
1329 if (!page_has_buffers(page)) {
1330 if (__block_write_begin(page, 0, len,
1331 noalloc_get_block_write)) {
1339 bh = page_bufs = page_buffers(page);
1344 if (map && (cur_logical >= map->m_lblk) &&
1345 (cur_logical <= (map->m_lblk +
1346 (map->m_len - 1)))) {
1347 if (buffer_delay(bh)) {
1348 clear_buffer_delay(bh);
1349 bh->b_blocknr = pblock;
1351 if (buffer_da_mapped(bh))
1352 clear_buffer_da_mapped(bh);
1353 if (buffer_unwritten(bh) ||
1355 BUG_ON(bh->b_blocknr != pblock);
1356 if (map->m_flags & EXT4_MAP_UNINIT)
1357 set_buffer_uninit(bh);
1358 clear_buffer_unwritten(bh);
1362 * skip page if block allocation undone and
1365 if (ext4_bh_delay_or_unwritten(NULL, bh))
1367 bh = bh->b_this_page;
1368 block_start += bh->b_size;
1371 } while (bh != page_bufs);
1377 /* mark the buffer_heads as dirty & uptodate */
1378 block_commit_write(page, 0, len);
1380 clear_page_dirty_for_io(page);
1382 * Delalloc doesn't support data journalling,
1383 * but eventually maybe we'll lift this
1386 if (unlikely(journal_data && PageChecked(page)))
1387 err = __ext4_journalled_writepage(page, len);
1388 else if (test_opt(inode->i_sb, MBLK_IO_SUBMIT))
1389 err = ext4_bio_write_page(&io_submit, page,
1391 else if (buffer_uninit(page_bufs)) {
1392 ext4_set_bh_endio(page_bufs, inode);
1393 err = block_write_full_page_endio(page,
1394 noalloc_get_block_write,
1395 mpd->wbc, ext4_end_io_buffer_write);
1397 err = block_write_full_page(page,
1398 noalloc_get_block_write, mpd->wbc);
1401 mpd->pages_written++;
1403 * In error case, we have to continue because
1404 * remaining pages are still locked
1409 pagevec_release(&pvec);
1411 ext4_io_submit(&io_submit);
1415 static void ext4_da_block_invalidatepages(struct mpage_da_data *mpd)
1419 struct pagevec pvec;
1420 struct inode *inode = mpd->inode;
1421 struct address_space *mapping = inode->i_mapping;
1423 index = mpd->first_page;
1424 end = mpd->next_page - 1;
1425 pagevec_init(&pvec, 0);
1426 while (index <= end) {
1427 nr_pages = pagevec_lookup(&pvec, mapping, index, PAGEVEC_SIZE);
1430 for (i = 0; i < nr_pages; i++) {
1431 struct page *page = pvec.pages[i];
1432 if (page->index > end)
1434 BUG_ON(!PageLocked(page));
1435 BUG_ON(PageWriteback(page));
1436 block_invalidatepage(page, 0);
1437 ClearPageUptodate(page);
1440 index = pvec.pages[nr_pages - 1]->index + 1;
1441 pagevec_release(&pvec);
1446 static void ext4_print_free_blocks(struct inode *inode)
1448 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1449 printk(KERN_CRIT "Total free blocks count %lld\n",
1450 EXT4_C2B(EXT4_SB(inode->i_sb),
1451 ext4_count_free_clusters(inode->i_sb)));
1452 printk(KERN_CRIT "Free/Dirty block details\n");
1453 printk(KERN_CRIT "free_blocks=%lld\n",
1454 (long long) EXT4_C2B(EXT4_SB(inode->i_sb),
1455 percpu_counter_sum(&sbi->s_freeclusters_counter)));
1456 printk(KERN_CRIT "dirty_blocks=%lld\n",
1457 (long long) EXT4_C2B(EXT4_SB(inode->i_sb),
1458 percpu_counter_sum(&sbi->s_dirtyclusters_counter)));
1459 printk(KERN_CRIT "Block reservation details\n");
1460 printk(KERN_CRIT "i_reserved_data_blocks=%u\n",
1461 EXT4_I(inode)->i_reserved_data_blocks);
1462 printk(KERN_CRIT "i_reserved_meta_blocks=%u\n",
1463 EXT4_I(inode)->i_reserved_meta_blocks);
1468 * mpage_da_map_and_submit - go through given space, map them
1469 * if necessary, and then submit them for I/O
1471 * @mpd - bh describing space
1473 * The function skips space we know is already mapped to disk blocks.
1476 static void mpage_da_map_and_submit(struct mpage_da_data *mpd)
1478 int err, blks, get_blocks_flags;
1479 struct ext4_map_blocks map, *mapp = NULL;
1480 sector_t next = mpd->b_blocknr;
1481 unsigned max_blocks = mpd->b_size >> mpd->inode->i_blkbits;
1482 loff_t disksize = EXT4_I(mpd->inode)->i_disksize;
1483 handle_t *handle = NULL;
1486 * If the blocks are mapped already, or we couldn't accumulate
1487 * any blocks, then proceed immediately to the submission stage.
1489 if ((mpd->b_size == 0) ||
1490 ((mpd->b_state & (1 << BH_Mapped)) &&
1491 !(mpd->b_state & (1 << BH_Delay)) &&
1492 !(mpd->b_state & (1 << BH_Unwritten))))
1495 handle = ext4_journal_current_handle();
1499 * Call ext4_map_blocks() to allocate any delayed allocation
1500 * blocks, or to convert an uninitialized extent to be
1501 * initialized (in the case where we have written into
1502 * one or more preallocated blocks).
1504 * We pass in the magic EXT4_GET_BLOCKS_DELALLOC_RESERVE to
1505 * indicate that we are on the delayed allocation path. This
1506 * affects functions in many different parts of the allocation
1507 * call path. This flag exists primarily because we don't
1508 * want to change *many* call functions, so ext4_map_blocks()
1509 * will set the EXT4_STATE_DELALLOC_RESERVED flag once the
1510 * inode's allocation semaphore is taken.
1512 * If the blocks in questions were delalloc blocks, set
1513 * EXT4_GET_BLOCKS_DELALLOC_RESERVE so the delalloc accounting
1514 * variables are updated after the blocks have been allocated.
1517 map.m_len = max_blocks;
1518 get_blocks_flags = EXT4_GET_BLOCKS_CREATE;
1519 if (ext4_should_dioread_nolock(mpd->inode))
1520 get_blocks_flags |= EXT4_GET_BLOCKS_IO_CREATE_EXT;
1521 if (mpd->b_state & (1 << BH_Delay))
1522 get_blocks_flags |= EXT4_GET_BLOCKS_DELALLOC_RESERVE;
1524 blks = ext4_map_blocks(handle, mpd->inode, &map, get_blocks_flags);
1526 struct super_block *sb = mpd->inode->i_sb;
1530 * If get block returns EAGAIN or ENOSPC and there
1531 * appears to be free blocks we will just let
1532 * mpage_da_submit_io() unlock all of the pages.
1537 if (err == -ENOSPC && ext4_count_free_clusters(sb)) {
1543 * get block failure will cause us to loop in
1544 * writepages, because a_ops->writepage won't be able
1545 * to make progress. The page will be redirtied by
1546 * writepage and writepages will again try to write
1549 if (!(EXT4_SB(sb)->s_mount_flags & EXT4_MF_FS_ABORTED)) {
1550 ext4_msg(sb, KERN_CRIT,
1551 "delayed block allocation failed for inode %lu "
1552 "at logical offset %llu with max blocks %zd "
1553 "with error %d", mpd->inode->i_ino,
1554 (unsigned long long) next,
1555 mpd->b_size >> mpd->inode->i_blkbits, err);
1556 ext4_msg(sb, KERN_CRIT,
1557 "This should not happen!! Data will be lost\n");
1559 ext4_print_free_blocks(mpd->inode);
1561 /* invalidate all the pages */
1562 ext4_da_block_invalidatepages(mpd);
1564 /* Mark this page range as having been completed */
1571 if (map.m_flags & EXT4_MAP_NEW) {
1572 struct block_device *bdev = mpd->inode->i_sb->s_bdev;
1575 for (i = 0; i < map.m_len; i++)
1576 unmap_underlying_metadata(bdev, map.m_pblk + i);
1578 if (ext4_should_order_data(mpd->inode)) {
1579 err = ext4_jbd2_file_inode(handle, mpd->inode);
1581 /* Only if the journal is aborted */
1589 * Update on-disk size along with block allocation.
1591 disksize = ((loff_t) next + blks) << mpd->inode->i_blkbits;
1592 if (disksize > i_size_read(mpd->inode))
1593 disksize = i_size_read(mpd->inode);
1594 if (disksize > EXT4_I(mpd->inode)->i_disksize) {
1595 ext4_update_i_disksize(mpd->inode, disksize);
1596 err = ext4_mark_inode_dirty(handle, mpd->inode);
1598 ext4_error(mpd->inode->i_sb,
1599 "Failed to mark inode %lu dirty",
1604 mpage_da_submit_io(mpd, mapp);
1608 #define BH_FLAGS ((1 << BH_Uptodate) | (1 << BH_Mapped) | \
1609 (1 << BH_Delay) | (1 << BH_Unwritten))
1612 * mpage_add_bh_to_extent - try to add one more block to extent of blocks
1614 * @mpd->lbh - extent of blocks
1615 * @logical - logical number of the block in the file
1616 * @bh - bh of the block (used to access block's state)
1618 * the function is used to collect contig. blocks in same state
1620 static void mpage_add_bh_to_extent(struct mpage_da_data *mpd,
1621 sector_t logical, size_t b_size,
1622 unsigned long b_state)
1625 int nrblocks = mpd->b_size >> mpd->inode->i_blkbits;
1628 * XXX Don't go larger than mballoc is willing to allocate
1629 * This is a stopgap solution. We eventually need to fold
1630 * mpage_da_submit_io() into this function and then call
1631 * ext4_map_blocks() multiple times in a loop
1633 if (nrblocks >= 8*1024*1024/mpd->inode->i_sb->s_blocksize)
1636 /* check if thereserved journal credits might overflow */
1637 if (!(ext4_test_inode_flag(mpd->inode, EXT4_INODE_EXTENTS))) {
1638 if (nrblocks >= EXT4_MAX_TRANS_DATA) {
1640 * With non-extent format we are limited by the journal
1641 * credit available. Total credit needed to insert
1642 * nrblocks contiguous blocks is dependent on the
1643 * nrblocks. So limit nrblocks.
1646 } else if ((nrblocks + (b_size >> mpd->inode->i_blkbits)) >
1647 EXT4_MAX_TRANS_DATA) {
1649 * Adding the new buffer_head would make it cross the
1650 * allowed limit for which we have journal credit
1651 * reserved. So limit the new bh->b_size
1653 b_size = (EXT4_MAX_TRANS_DATA - nrblocks) <<
1654 mpd->inode->i_blkbits;
1655 /* we will do mpage_da_submit_io in the next loop */
1659 * First block in the extent
1661 if (mpd->b_size == 0) {
1662 mpd->b_blocknr = logical;
1663 mpd->b_size = b_size;
1664 mpd->b_state = b_state & BH_FLAGS;
1668 next = mpd->b_blocknr + nrblocks;
1670 * Can we merge the block to our big extent?
1672 if (logical == next && (b_state & BH_FLAGS) == mpd->b_state) {
1673 mpd->b_size += b_size;
1679 * We couldn't merge the block to our extent, so we
1680 * need to flush current extent and start new one
1682 mpage_da_map_and_submit(mpd);
1686 static int ext4_bh_delay_or_unwritten(handle_t *handle, struct buffer_head *bh)
1688 return (buffer_delay(bh) || buffer_unwritten(bh)) && buffer_dirty(bh);
1692 * This function is grabs code from the very beginning of
1693 * ext4_map_blocks, but assumes that the caller is from delayed write
1694 * time. This function looks up the requested blocks and sets the
1695 * buffer delay bit under the protection of i_data_sem.
1697 static int ext4_da_map_blocks(struct inode *inode, sector_t iblock,
1698 struct ext4_map_blocks *map,
1699 struct buffer_head *bh)
1702 sector_t invalid_block = ~((sector_t) 0xffff);
1704 if (invalid_block < ext4_blocks_count(EXT4_SB(inode->i_sb)->s_es))
1708 ext_debug("ext4_da_map_blocks(): inode %lu, max_blocks %u,"
1709 "logical block %lu\n", inode->i_ino, map->m_len,
1710 (unsigned long) map->m_lblk);
1712 * Try to see if we can get the block without requesting a new
1713 * file system block.
1715 down_read((&EXT4_I(inode)->i_data_sem));
1716 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
1717 retval = ext4_ext_map_blocks(NULL, inode, map, 0);
1719 retval = ext4_ind_map_blocks(NULL, inode, map, 0);
1723 * XXX: __block_prepare_write() unmaps passed block,
1726 /* If the block was allocated from previously allocated cluster,
1727 * then we dont need to reserve it again. */
1728 if (!(map->m_flags & EXT4_MAP_FROM_CLUSTER)) {
1729 retval = ext4_da_reserve_space(inode, iblock);
1731 /* not enough space to reserve */
1735 /* Clear EXT4_MAP_FROM_CLUSTER flag since its purpose is served
1736 * and it should not appear on the bh->b_state.
1738 map->m_flags &= ~EXT4_MAP_FROM_CLUSTER;
1740 map_bh(bh, inode->i_sb, invalid_block);
1742 set_buffer_delay(bh);
1746 up_read((&EXT4_I(inode)->i_data_sem));
1752 * This is a special get_blocks_t callback which is used by
1753 * ext4_da_write_begin(). It will either return mapped block or
1754 * reserve space for a single block.
1756 * For delayed buffer_head we have BH_Mapped, BH_New, BH_Delay set.
1757 * We also have b_blocknr = -1 and b_bdev initialized properly
1759 * For unwritten buffer_head we have BH_Mapped, BH_New, BH_Unwritten set.
1760 * We also have b_blocknr = physicalblock mapping unwritten extent and b_bdev
1761 * initialized properly.
1763 static int ext4_da_get_block_prep(struct inode *inode, sector_t iblock,
1764 struct buffer_head *bh, int create)
1766 struct ext4_map_blocks map;
1769 BUG_ON(create == 0);
1770 BUG_ON(bh->b_size != inode->i_sb->s_blocksize);
1772 map.m_lblk = iblock;
1776 * first, we need to know whether the block is allocated already
1777 * preallocated blocks are unmapped but should treated
1778 * the same as allocated blocks.
1780 ret = ext4_da_map_blocks(inode, iblock, &map, bh);
1784 map_bh(bh, inode->i_sb, map.m_pblk);
1785 bh->b_state = (bh->b_state & ~EXT4_MAP_FLAGS) | map.m_flags;
1787 if (buffer_unwritten(bh)) {
1788 /* A delayed write to unwritten bh should be marked
1789 * new and mapped. Mapped ensures that we don't do
1790 * get_block multiple times when we write to the same
1791 * offset and new ensures that we do proper zero out
1792 * for partial write.
1795 set_buffer_mapped(bh);
1801 * This function is used as a standard get_block_t calback function
1802 * when there is no desire to allocate any blocks. It is used as a
1803 * callback function for block_write_begin() and block_write_full_page().
1804 * These functions should only try to map a single block at a time.
1806 * Since this function doesn't do block allocations even if the caller
1807 * requests it by passing in create=1, it is critically important that
1808 * any caller checks to make sure that any buffer heads are returned
1809 * by this function are either all already mapped or marked for
1810 * delayed allocation before calling block_write_full_page(). Otherwise,
1811 * b_blocknr could be left unitialized, and the page write functions will
1812 * be taken by surprise.
1814 static int noalloc_get_block_write(struct inode *inode, sector_t iblock,
1815 struct buffer_head *bh_result, int create)
1817 BUG_ON(bh_result->b_size != inode->i_sb->s_blocksize);
1818 return _ext4_get_block(inode, iblock, bh_result, 0);
1821 static int bget_one(handle_t *handle, struct buffer_head *bh)
1827 static int bput_one(handle_t *handle, struct buffer_head *bh)
1833 static int __ext4_journalled_writepage(struct page *page,
1836 struct address_space *mapping = page->mapping;
1837 struct inode *inode = mapping->host;
1838 struct buffer_head *page_bufs;
1839 handle_t *handle = NULL;
1843 ClearPageChecked(page);
1844 page_bufs = page_buffers(page);
1846 walk_page_buffers(handle, page_bufs, 0, len, NULL, bget_one);
1847 /* As soon as we unlock the page, it can go away, but we have
1848 * references to buffers so we are safe */
1851 handle = ext4_journal_start(inode, ext4_writepage_trans_blocks(inode));
1852 if (IS_ERR(handle)) {
1853 ret = PTR_ERR(handle);
1857 BUG_ON(!ext4_handle_valid(handle));
1859 ret = walk_page_buffers(handle, page_bufs, 0, len, NULL,
1860 do_journal_get_write_access);
1862 err = walk_page_buffers(handle, page_bufs, 0, len, NULL,
1866 EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
1867 err = ext4_journal_stop(handle);
1871 walk_page_buffers(handle, page_bufs, 0, len, NULL, bput_one);
1872 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
1877 static int ext4_set_bh_endio(struct buffer_head *bh, struct inode *inode);
1878 static void ext4_end_io_buffer_write(struct buffer_head *bh, int uptodate);
1881 * Note that we don't need to start a transaction unless we're journaling data
1882 * because we should have holes filled from ext4_page_mkwrite(). We even don't
1883 * need to file the inode to the transaction's list in ordered mode because if
1884 * we are writing back data added by write(), the inode is already there and if
1885 * we are writing back data modified via mmap(), no one guarantees in which
1886 * transaction the data will hit the disk. In case we are journaling data, we
1887 * cannot start transaction directly because transaction start ranks above page
1888 * lock so we have to do some magic.
1890 * This function can get called via...
1891 * - ext4_da_writepages after taking page lock (have journal handle)
1892 * - journal_submit_inode_data_buffers (no journal handle)
1893 * - shrink_page_list via pdflush (no journal handle)
1894 * - grab_page_cache when doing write_begin (have journal handle)
1896 * We don't do any block allocation in this function. If we have page with
1897 * multiple blocks we need to write those buffer_heads that are mapped. This
1898 * is important for mmaped based write. So if we do with blocksize 1K
1899 * truncate(f, 1024);
1900 * a = mmap(f, 0, 4096);
1902 * truncate(f, 4096);
1903 * we have in the page first buffer_head mapped via page_mkwrite call back
1904 * but other bufer_heads would be unmapped but dirty(dirty done via the
1905 * do_wp_page). So writepage should write the first block. If we modify
1906 * the mmap area beyond 1024 we will again get a page_fault and the
1907 * page_mkwrite callback will do the block allocation and mark the
1908 * buffer_heads mapped.
1910 * We redirty the page if we have any buffer_heads that is either delay or
1911 * unwritten in the page.
1913 * We can get recursively called as show below.
1915 * ext4_writepage() -> kmalloc() -> __alloc_pages() -> page_launder() ->
1918 * But since we don't do any block allocation we should not deadlock.
1919 * Page also have the dirty flag cleared so we don't get recurive page_lock.
1921 static int ext4_writepage(struct page *page,
1922 struct writeback_control *wbc)
1924 int ret = 0, commit_write = 0;
1927 struct buffer_head *page_bufs = NULL;
1928 struct inode *inode = page->mapping->host;
1930 trace_ext4_writepage(page);
1931 size = i_size_read(inode);
1932 if (page->index == size >> PAGE_CACHE_SHIFT)
1933 len = size & ~PAGE_CACHE_MASK;
1935 len = PAGE_CACHE_SIZE;
1938 * If the page does not have buffers (for whatever reason),
1939 * try to create them using __block_write_begin. If this
1940 * fails, redirty the page and move on.
1942 if (!page_has_buffers(page)) {
1943 if (__block_write_begin(page, 0, len,
1944 noalloc_get_block_write)) {
1946 redirty_page_for_writepage(wbc, page);
1952 page_bufs = page_buffers(page);
1953 if (walk_page_buffers(NULL, page_bufs, 0, len, NULL,
1954 ext4_bh_delay_or_unwritten)) {
1956 * We don't want to do block allocation, so redirty
1957 * the page and return. We may reach here when we do
1958 * a journal commit via journal_submit_inode_data_buffers.
1959 * We can also reach here via shrink_page_list but it
1960 * should never be for direct reclaim so warn if that
1963 WARN_ON_ONCE((current->flags & (PF_MEMALLOC|PF_KSWAPD)) ==
1968 /* now mark the buffer_heads as dirty and uptodate */
1969 block_commit_write(page, 0, len);
1971 if (PageChecked(page) && ext4_should_journal_data(inode))
1973 * It's mmapped pagecache. Add buffers and journal it. There
1974 * doesn't seem much point in redirtying the page here.
1976 return __ext4_journalled_writepage(page, len);
1978 if (buffer_uninit(page_bufs)) {
1979 ext4_set_bh_endio(page_bufs, inode);
1980 ret = block_write_full_page_endio(page, noalloc_get_block_write,
1981 wbc, ext4_end_io_buffer_write);
1983 ret = block_write_full_page(page, noalloc_get_block_write,
1990 * This is called via ext4_da_writepages() to
1991 * calculate the total number of credits to reserve to fit
1992 * a single extent allocation into a single transaction,
1993 * ext4_da_writpeages() will loop calling this before
1994 * the block allocation.
1997 static int ext4_da_writepages_trans_blocks(struct inode *inode)
1999 int max_blocks = EXT4_I(inode)->i_reserved_data_blocks;
2002 * With non-extent format the journal credit needed to
2003 * insert nrblocks contiguous block is dependent on
2004 * number of contiguous block. So we will limit
2005 * number of contiguous block to a sane value
2007 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) &&
2008 (max_blocks > EXT4_MAX_TRANS_DATA))
2009 max_blocks = EXT4_MAX_TRANS_DATA;
2011 return ext4_chunk_trans_blocks(inode, max_blocks);
2015 * write_cache_pages_da - walk the list of dirty pages of the given
2016 * address space and accumulate pages that need writing, and call
2017 * mpage_da_map_and_submit to map a single contiguous memory region
2018 * and then write them.
2020 static int write_cache_pages_da(struct address_space *mapping,
2021 struct writeback_control *wbc,
2022 struct mpage_da_data *mpd,
2023 pgoff_t *done_index)
2025 struct buffer_head *bh, *head;
2026 struct inode *inode = mapping->host;
2027 struct pagevec pvec;
2028 unsigned int nr_pages;
2031 long nr_to_write = wbc->nr_to_write;
2032 int i, tag, ret = 0;
2034 memset(mpd, 0, sizeof(struct mpage_da_data));
2037 pagevec_init(&pvec, 0);
2038 index = wbc->range_start >> PAGE_CACHE_SHIFT;
2039 end = wbc->range_end >> PAGE_CACHE_SHIFT;
2041 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
2042 tag = PAGECACHE_TAG_TOWRITE;
2044 tag = PAGECACHE_TAG_DIRTY;
2046 *done_index = index;
2047 while (index <= end) {
2048 nr_pages = pagevec_lookup_tag(&pvec, mapping, &index, tag,
2049 min(end - index, (pgoff_t)PAGEVEC_SIZE-1) + 1);
2053 for (i = 0; i < nr_pages; i++) {
2054 struct page *page = pvec.pages[i];
2057 * At this point, the page may be truncated or
2058 * invalidated (changing page->mapping to NULL), or
2059 * even swizzled back from swapper_space to tmpfs file
2060 * mapping. However, page->index will not change
2061 * because we have a reference on the page.
2063 if (page->index > end)
2066 *done_index = page->index + 1;
2069 * If we can't merge this page, and we have
2070 * accumulated an contiguous region, write it
2072 if ((mpd->next_page != page->index) &&
2073 (mpd->next_page != mpd->first_page)) {
2074 mpage_da_map_and_submit(mpd);
2075 goto ret_extent_tail;
2081 * If the page is no longer dirty, or its
2082 * mapping no longer corresponds to inode we
2083 * are writing (which means it has been
2084 * truncated or invalidated), or the page is
2085 * already under writeback and we are not
2086 * doing a data integrity writeback, skip the page
2088 if (!PageDirty(page) ||
2089 (PageWriteback(page) &&
2090 (wbc->sync_mode == WB_SYNC_NONE)) ||
2091 unlikely(page->mapping != mapping)) {
2096 wait_on_page_writeback(page);
2097 BUG_ON(PageWriteback(page));
2099 if (mpd->next_page != page->index)
2100 mpd->first_page = page->index;
2101 mpd->next_page = page->index + 1;
2102 logical = (sector_t) page->index <<
2103 (PAGE_CACHE_SHIFT - inode->i_blkbits);
2105 if (!page_has_buffers(page)) {
2106 mpage_add_bh_to_extent(mpd, logical,
2108 (1 << BH_Dirty) | (1 << BH_Uptodate));
2110 goto ret_extent_tail;
2113 * Page with regular buffer heads,
2114 * just add all dirty ones
2116 head = page_buffers(page);
2119 BUG_ON(buffer_locked(bh));
2121 * We need to try to allocate
2122 * unmapped blocks in the same page.
2123 * Otherwise we won't make progress
2124 * with the page in ext4_writepage
2126 if (ext4_bh_delay_or_unwritten(NULL, bh)) {
2127 mpage_add_bh_to_extent(mpd, logical,
2131 goto ret_extent_tail;
2132 } else if (buffer_dirty(bh) && (buffer_mapped(bh))) {
2134 * mapped dirty buffer. We need
2135 * to update the b_state
2136 * because we look at b_state
2137 * in mpage_da_map_blocks. We
2138 * don't update b_size because
2139 * if we find an unmapped
2140 * buffer_head later we need to
2141 * use the b_state flag of that
2144 if (mpd->b_size == 0)
2145 mpd->b_state = bh->b_state & BH_FLAGS;
2148 } while ((bh = bh->b_this_page) != head);
2151 if (nr_to_write > 0) {
2153 if (nr_to_write == 0 &&
2154 wbc->sync_mode == WB_SYNC_NONE)
2156 * We stop writing back only if we are
2157 * not doing integrity sync. In case of
2158 * integrity sync we have to keep going
2159 * because someone may be concurrently
2160 * dirtying pages, and we might have
2161 * synced a lot of newly appeared dirty
2162 * pages, but have not synced all of the
2168 pagevec_release(&pvec);
2173 ret = MPAGE_DA_EXTENT_TAIL;
2175 pagevec_release(&pvec);
2181 static int ext4_da_writepages(struct address_space *mapping,
2182 struct writeback_control *wbc)
2185 int range_whole = 0;
2186 handle_t *handle = NULL;
2187 struct mpage_da_data mpd;
2188 struct inode *inode = mapping->host;
2189 int pages_written = 0;
2190 unsigned int max_pages;
2191 int range_cyclic, cycled = 1, io_done = 0;
2192 int needed_blocks, ret = 0;
2193 long desired_nr_to_write, nr_to_writebump = 0;
2194 loff_t range_start = wbc->range_start;
2195 struct ext4_sb_info *sbi = EXT4_SB(mapping->host->i_sb);
2196 pgoff_t done_index = 0;
2198 struct blk_plug plug;
2200 trace_ext4_da_writepages(inode, wbc);
2203 * No pages to write? This is mainly a kludge to avoid starting
2204 * a transaction for special inodes like journal inode on last iput()
2205 * because that could violate lock ordering on umount
2207 if (!mapping->nrpages || !mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
2211 * If the filesystem has aborted, it is read-only, so return
2212 * right away instead of dumping stack traces later on that
2213 * will obscure the real source of the problem. We test
2214 * EXT4_MF_FS_ABORTED instead of sb->s_flag's MS_RDONLY because
2215 * the latter could be true if the filesystem is mounted
2216 * read-only, and in that case, ext4_da_writepages should
2217 * *never* be called, so if that ever happens, we would want
2220 if (unlikely(sbi->s_mount_flags & EXT4_MF_FS_ABORTED))
2223 if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
2226 range_cyclic = wbc->range_cyclic;
2227 if (wbc->range_cyclic) {
2228 index = mapping->writeback_index;
2231 wbc->range_start = index << PAGE_CACHE_SHIFT;
2232 wbc->range_end = LLONG_MAX;
2233 wbc->range_cyclic = 0;
2236 index = wbc->range_start >> PAGE_CACHE_SHIFT;
2237 end = wbc->range_end >> PAGE_CACHE_SHIFT;
2241 * This works around two forms of stupidity. The first is in
2242 * the writeback code, which caps the maximum number of pages
2243 * written to be 1024 pages. This is wrong on multiple
2244 * levels; different architectues have a different page size,
2245 * which changes the maximum amount of data which gets
2246 * written. Secondly, 4 megabytes is way too small. XFS
2247 * forces this value to be 16 megabytes by multiplying
2248 * nr_to_write parameter by four, and then relies on its
2249 * allocator to allocate larger extents to make them
2250 * contiguous. Unfortunately this brings us to the second
2251 * stupidity, which is that ext4's mballoc code only allocates
2252 * at most 2048 blocks. So we force contiguous writes up to
2253 * the number of dirty blocks in the inode, or
2254 * sbi->max_writeback_mb_bump whichever is smaller.
2256 max_pages = sbi->s_max_writeback_mb_bump << (20 - PAGE_CACHE_SHIFT);
2257 if (!range_cyclic && range_whole) {
2258 if (wbc->nr_to_write == LONG_MAX)
2259 desired_nr_to_write = wbc->nr_to_write;
2261 desired_nr_to_write = wbc->nr_to_write * 8;
2263 desired_nr_to_write = ext4_num_dirty_pages(inode, index,
2265 if (desired_nr_to_write > max_pages)
2266 desired_nr_to_write = max_pages;
2268 if (wbc->nr_to_write < desired_nr_to_write) {
2269 nr_to_writebump = desired_nr_to_write - wbc->nr_to_write;
2270 wbc->nr_to_write = desired_nr_to_write;
2274 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
2275 tag_pages_for_writeback(mapping, index, end);
2277 blk_start_plug(&plug);
2278 while (!ret && wbc->nr_to_write > 0) {
2281 * we insert one extent at a time. So we need
2282 * credit needed for single extent allocation.
2283 * journalled mode is currently not supported
2286 BUG_ON(ext4_should_journal_data(inode));
2287 needed_blocks = ext4_da_writepages_trans_blocks(inode);
2289 /* start a new transaction*/
2290 handle = ext4_journal_start(inode, needed_blocks);
2291 if (IS_ERR(handle)) {
2292 ret = PTR_ERR(handle);
2293 ext4_msg(inode->i_sb, KERN_CRIT, "%s: jbd2_start: "
2294 "%ld pages, ino %lu; err %d", __func__,
2295 wbc->nr_to_write, inode->i_ino, ret);
2296 blk_finish_plug(&plug);
2297 goto out_writepages;
2301 * Now call write_cache_pages_da() to find the next
2302 * contiguous region of logical blocks that need
2303 * blocks to be allocated by ext4 and submit them.
2305 ret = write_cache_pages_da(mapping, wbc, &mpd, &done_index);
2307 * If we have a contiguous extent of pages and we
2308 * haven't done the I/O yet, map the blocks and submit
2311 if (!mpd.io_done && mpd.next_page != mpd.first_page) {
2312 mpage_da_map_and_submit(&mpd);
2313 ret = MPAGE_DA_EXTENT_TAIL;
2315 trace_ext4_da_write_pages(inode, &mpd);
2316 wbc->nr_to_write -= mpd.pages_written;
2318 ext4_journal_stop(handle);
2320 if ((mpd.retval == -ENOSPC) && sbi->s_journal) {
2321 /* commit the transaction which would
2322 * free blocks released in the transaction
2325 jbd2_journal_force_commit_nested(sbi->s_journal);
2327 } else if (ret == MPAGE_DA_EXTENT_TAIL) {
2329 * Got one extent now try with rest of the pages.
2330 * If mpd.retval is set -EIO, journal is aborted.
2331 * So we don't need to write any more.
2333 pages_written += mpd.pages_written;
2336 } else if (wbc->nr_to_write)
2338 * There is no more writeout needed
2339 * or we requested for a noblocking writeout
2340 * and we found the device congested
2344 blk_finish_plug(&plug);
2345 if (!io_done && !cycled) {
2348 wbc->range_start = index << PAGE_CACHE_SHIFT;
2349 wbc->range_end = mapping->writeback_index - 1;
2354 wbc->range_cyclic = range_cyclic;
2355 if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
2357 * set the writeback_index so that range_cyclic
2358 * mode will write it back later
2360 mapping->writeback_index = done_index;
2363 wbc->nr_to_write -= nr_to_writebump;
2364 wbc->range_start = range_start;
2365 trace_ext4_da_writepages_result(inode, wbc, ret, pages_written);
2369 #define FALL_BACK_TO_NONDELALLOC 1
2370 static int ext4_nonda_switch(struct super_block *sb)
2372 s64 free_blocks, dirty_blocks;
2373 struct ext4_sb_info *sbi = EXT4_SB(sb);
2376 * switch to non delalloc mode if we are running low
2377 * on free block. The free block accounting via percpu
2378 * counters can get slightly wrong with percpu_counter_batch getting
2379 * accumulated on each CPU without updating global counters
2380 * Delalloc need an accurate free block accounting. So switch
2381 * to non delalloc when we are near to error range.
2383 free_blocks = EXT4_C2B(sbi,
2384 percpu_counter_read_positive(&sbi->s_freeclusters_counter));
2385 dirty_blocks = percpu_counter_read_positive(&sbi->s_dirtyclusters_counter);
2387 * Start pushing delalloc when 1/2 of free blocks are dirty.
2389 if (dirty_blocks && (free_blocks < 2 * dirty_blocks) &&
2390 !writeback_in_progress(sb->s_bdi) &&
2391 down_read_trylock(&sb->s_umount)) {
2392 writeback_inodes_sb(sb, WB_REASON_FS_FREE_SPACE);
2393 up_read(&sb->s_umount);
2396 if (2 * free_blocks < 3 * dirty_blocks ||
2397 free_blocks < (dirty_blocks + EXT4_FREECLUSTERS_WATERMARK)) {
2399 * free block count is less than 150% of dirty blocks
2400 * or free blocks is less than watermark
2407 static int ext4_da_write_begin(struct file *file, struct address_space *mapping,
2408 loff_t pos, unsigned len, unsigned flags,
2409 struct page **pagep, void **fsdata)
2411 int ret, retries = 0;
2414 struct inode *inode = mapping->host;
2417 index = pos >> PAGE_CACHE_SHIFT;
2419 if (ext4_nonda_switch(inode->i_sb)) {
2420 *fsdata = (void *)FALL_BACK_TO_NONDELALLOC;
2421 return ext4_write_begin(file, mapping, pos,
2422 len, flags, pagep, fsdata);
2424 *fsdata = (void *)0;
2425 trace_ext4_da_write_begin(inode, pos, len, flags);
2428 * With delayed allocation, we don't log the i_disksize update
2429 * if there is delayed block allocation. But we still need
2430 * to journalling the i_disksize update if writes to the end
2431 * of file which has an already mapped buffer.
2433 handle = ext4_journal_start(inode, 1);
2434 if (IS_ERR(handle)) {
2435 ret = PTR_ERR(handle);
2438 /* We cannot recurse into the filesystem as the transaction is already
2440 flags |= AOP_FLAG_NOFS;
2442 page = grab_cache_page_write_begin(mapping, index, flags);
2444 ext4_journal_stop(handle);
2450 ret = __block_write_begin(page, pos, len, ext4_da_get_block_prep);
2453 ext4_journal_stop(handle);
2454 page_cache_release(page);
2456 * block_write_begin may have instantiated a few blocks
2457 * outside i_size. Trim these off again. Don't need
2458 * i_size_read because we hold i_mutex.
2460 if (pos + len > inode->i_size)
2461 ext4_truncate_failed_write(inode);
2464 if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
2471 * Check if we should update i_disksize
2472 * when write to the end of file but not require block allocation
2474 static int ext4_da_should_update_i_disksize(struct page *page,
2475 unsigned long offset)
2477 struct buffer_head *bh;
2478 struct inode *inode = page->mapping->host;
2482 bh = page_buffers(page);
2483 idx = offset >> inode->i_blkbits;
2485 for (i = 0; i < idx; i++)
2486 bh = bh->b_this_page;
2488 if (!buffer_mapped(bh) || (buffer_delay(bh)) || buffer_unwritten(bh))
2493 static int ext4_da_write_end(struct file *file,
2494 struct address_space *mapping,
2495 loff_t pos, unsigned len, unsigned copied,
2496 struct page *page, void *fsdata)
2498 struct inode *inode = mapping->host;
2500 handle_t *handle = ext4_journal_current_handle();
2502 unsigned long start, end;
2503 int write_mode = (int)(unsigned long)fsdata;
2505 if (write_mode == FALL_BACK_TO_NONDELALLOC) {
2506 switch (ext4_inode_journal_mode(inode)) {
2507 case EXT4_INODE_ORDERED_DATA_MODE:
2508 return ext4_ordered_write_end(file, mapping, pos,
2509 len, copied, page, fsdata);
2510 case EXT4_INODE_WRITEBACK_DATA_MODE:
2511 return ext4_writeback_write_end(file, mapping, pos,
2512 len, copied, page, fsdata);
2518 trace_ext4_da_write_end(inode, pos, len, copied);
2519 start = pos & (PAGE_CACHE_SIZE - 1);
2520 end = start + copied - 1;
2523 * generic_write_end() will run mark_inode_dirty() if i_size
2524 * changes. So let's piggyback the i_disksize mark_inode_dirty
2528 new_i_size = pos + copied;
2529 if (copied && new_i_size > EXT4_I(inode)->i_disksize) {
2530 if (ext4_da_should_update_i_disksize(page, end)) {
2531 down_write(&EXT4_I(inode)->i_data_sem);
2532 if (new_i_size > EXT4_I(inode)->i_disksize) {
2534 * Updating i_disksize when extending file
2535 * without needing block allocation
2537 if (ext4_should_order_data(inode))
2538 ret = ext4_jbd2_file_inode(handle,
2541 EXT4_I(inode)->i_disksize = new_i_size;
2543 up_write(&EXT4_I(inode)->i_data_sem);
2544 /* We need to mark inode dirty even if
2545 * new_i_size is less that inode->i_size
2546 * bu greater than i_disksize.(hint delalloc)
2548 ext4_mark_inode_dirty(handle, inode);
2551 ret2 = generic_write_end(file, mapping, pos, len, copied,
2556 ret2 = ext4_journal_stop(handle);
2560 return ret ? ret : copied;
2563 static void ext4_da_invalidatepage(struct page *page, unsigned long offset)
2566 * Drop reserved blocks
2568 BUG_ON(!PageLocked(page));
2569 if (!page_has_buffers(page))
2572 ext4_da_page_release_reservation(page, offset);
2575 ext4_invalidatepage(page, offset);
2581 * Force all delayed allocation blocks to be allocated for a given inode.
2583 int ext4_alloc_da_blocks(struct inode *inode)
2585 trace_ext4_alloc_da_blocks(inode);
2587 if (!EXT4_I(inode)->i_reserved_data_blocks &&
2588 !EXT4_I(inode)->i_reserved_meta_blocks)
2592 * We do something simple for now. The filemap_flush() will
2593 * also start triggering a write of the data blocks, which is
2594 * not strictly speaking necessary (and for users of
2595 * laptop_mode, not even desirable). However, to do otherwise
2596 * would require replicating code paths in:
2598 * ext4_da_writepages() ->
2599 * write_cache_pages() ---> (via passed in callback function)
2600 * __mpage_da_writepage() -->
2601 * mpage_add_bh_to_extent()
2602 * mpage_da_map_blocks()
2604 * The problem is that write_cache_pages(), located in
2605 * mm/page-writeback.c, marks pages clean in preparation for
2606 * doing I/O, which is not desirable if we're not planning on
2609 * We could call write_cache_pages(), and then redirty all of
2610 * the pages by calling redirty_page_for_writepage() but that
2611 * would be ugly in the extreme. So instead we would need to
2612 * replicate parts of the code in the above functions,
2613 * simplifying them because we wouldn't actually intend to
2614 * write out the pages, but rather only collect contiguous
2615 * logical block extents, call the multi-block allocator, and
2616 * then update the buffer heads with the block allocations.
2618 * For now, though, we'll cheat by calling filemap_flush(),
2619 * which will map the blocks, and start the I/O, but not
2620 * actually wait for the I/O to complete.
2622 return filemap_flush(inode->i_mapping);
2626 * bmap() is special. It gets used by applications such as lilo and by
2627 * the swapper to find the on-disk block of a specific piece of data.
2629 * Naturally, this is dangerous if the block concerned is still in the
2630 * journal. If somebody makes a swapfile on an ext4 data-journaling
2631 * filesystem and enables swap, then they may get a nasty shock when the
2632 * data getting swapped to that swapfile suddenly gets overwritten by
2633 * the original zero's written out previously to the journal and
2634 * awaiting writeback in the kernel's buffer cache.
2636 * So, if we see any bmap calls here on a modified, data-journaled file,
2637 * take extra steps to flush any blocks which might be in the cache.
2639 static sector_t ext4_bmap(struct address_space *mapping, sector_t block)
2641 struct inode *inode = mapping->host;
2645 if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY) &&
2646 test_opt(inode->i_sb, DELALLOC)) {
2648 * With delalloc we want to sync the file
2649 * so that we can make sure we allocate
2652 filemap_write_and_wait(mapping);
2655 if (EXT4_JOURNAL(inode) &&
2656 ext4_test_inode_state(inode, EXT4_STATE_JDATA)) {
2658 * This is a REALLY heavyweight approach, but the use of
2659 * bmap on dirty files is expected to be extremely rare:
2660 * only if we run lilo or swapon on a freshly made file
2661 * do we expect this to happen.
2663 * (bmap requires CAP_SYS_RAWIO so this does not
2664 * represent an unprivileged user DOS attack --- we'd be
2665 * in trouble if mortal users could trigger this path at
2668 * NB. EXT4_STATE_JDATA is not set on files other than
2669 * regular files. If somebody wants to bmap a directory
2670 * or symlink and gets confused because the buffer
2671 * hasn't yet been flushed to disk, they deserve
2672 * everything they get.
2675 ext4_clear_inode_state(inode, EXT4_STATE_JDATA);
2676 journal = EXT4_JOURNAL(inode);
2677 jbd2_journal_lock_updates(journal);
2678 err = jbd2_journal_flush(journal);
2679 jbd2_journal_unlock_updates(journal);
2685 return generic_block_bmap(mapping, block, ext4_get_block);
2688 static int ext4_readpage(struct file *file, struct page *page)
2690 trace_ext4_readpage(page);
2691 return mpage_readpage(page, ext4_get_block);
2695 ext4_readpages(struct file *file, struct address_space *mapping,
2696 struct list_head *pages, unsigned nr_pages)
2698 return mpage_readpages(mapping, pages, nr_pages, ext4_get_block);
2701 static void ext4_invalidatepage_free_endio(struct page *page, unsigned long offset)
2703 struct buffer_head *head, *bh;
2704 unsigned int curr_off = 0;
2706 if (!page_has_buffers(page))
2708 head = bh = page_buffers(page);
2710 if (offset <= curr_off && test_clear_buffer_uninit(bh)
2712 ext4_free_io_end(bh->b_private);
2713 bh->b_private = NULL;
2714 bh->b_end_io = NULL;
2716 curr_off = curr_off + bh->b_size;
2717 bh = bh->b_this_page;
2718 } while (bh != head);
2721 static void ext4_invalidatepage(struct page *page, unsigned long offset)
2723 journal_t *journal = EXT4_JOURNAL(page->mapping->host);
2725 trace_ext4_invalidatepage(page, offset);
2728 * free any io_end structure allocated for buffers to be discarded
2730 if (ext4_should_dioread_nolock(page->mapping->host))
2731 ext4_invalidatepage_free_endio(page, offset);
2733 * If it's a full truncate we just forget about the pending dirtying
2736 ClearPageChecked(page);
2739 jbd2_journal_invalidatepage(journal, page, offset);
2741 block_invalidatepage(page, offset);
2744 static int ext4_releasepage(struct page *page, gfp_t wait)
2746 journal_t *journal = EXT4_JOURNAL(page->mapping->host);
2748 trace_ext4_releasepage(page);
2750 WARN_ON(PageChecked(page));
2751 if (!page_has_buffers(page))
2754 return jbd2_journal_try_to_free_buffers(journal, page, wait);
2756 return try_to_free_buffers(page);
2760 * ext4_get_block used when preparing for a DIO write or buffer write.
2761 * We allocate an uinitialized extent if blocks haven't been allocated.
2762 * The extent will be converted to initialized after the IO is complete.
2764 static int ext4_get_block_write(struct inode *inode, sector_t iblock,
2765 struct buffer_head *bh_result, int create)
2767 ext4_debug("ext4_get_block_write: inode %lu, create flag %d\n",
2768 inode->i_ino, create);
2769 return _ext4_get_block(inode, iblock, bh_result,
2770 EXT4_GET_BLOCKS_IO_CREATE_EXT);
2773 static void ext4_end_io_dio(struct kiocb *iocb, loff_t offset,
2774 ssize_t size, void *private, int ret,
2777 struct inode *inode = iocb->ki_filp->f_path.dentry->d_inode;
2778 ext4_io_end_t *io_end = iocb->private;
2779 struct workqueue_struct *wq;
2780 unsigned long flags;
2781 struct ext4_inode_info *ei;
2783 /* if not async direct IO or dio with 0 bytes write, just return */
2784 if (!io_end || !size)
2787 ext_debug("ext4_end_io_dio(): io_end 0x%p"
2788 "for inode %lu, iocb 0x%p, offset %llu, size %llu\n",
2789 iocb->private, io_end->inode->i_ino, iocb, offset,
2792 iocb->private = NULL;
2794 /* if not aio dio with unwritten extents, just free io and return */
2795 if (!(io_end->flag & EXT4_IO_END_UNWRITTEN)) {
2796 ext4_free_io_end(io_end);
2798 inode_dio_done(inode);
2800 aio_complete(iocb, ret, 0);
2804 io_end->offset = offset;
2805 io_end->size = size;
2807 io_end->iocb = iocb;
2808 io_end->result = ret;
2810 wq = EXT4_SB(io_end->inode->i_sb)->dio_unwritten_wq;
2812 /* Add the io_end to per-inode completed aio dio list*/
2813 ei = EXT4_I(io_end->inode);
2814 spin_lock_irqsave(&ei->i_completed_io_lock, flags);
2815 list_add_tail(&io_end->list, &ei->i_completed_io_list);
2816 spin_unlock_irqrestore(&ei->i_completed_io_lock, flags);
2818 /* queue the work to convert unwritten extents to written */
2819 queue_work(wq, &io_end->work);
2822 static void ext4_end_io_buffer_write(struct buffer_head *bh, int uptodate)
2824 ext4_io_end_t *io_end = bh->b_private;
2825 struct workqueue_struct *wq;
2826 struct inode *inode;
2827 unsigned long flags;
2829 if (!test_clear_buffer_uninit(bh) || !io_end)
2832 if (!(io_end->inode->i_sb->s_flags & MS_ACTIVE)) {
2833 printk("sb umounted, discard end_io request for inode %lu\n",
2834 io_end->inode->i_ino);
2835 ext4_free_io_end(io_end);
2840 * It may be over-defensive here to check EXT4_IO_END_UNWRITTEN now,
2841 * but being more careful is always safe for the future change.
2843 inode = io_end->inode;
2844 ext4_set_io_unwritten_flag(inode, io_end);
2846 /* Add the io_end to per-inode completed io list*/
2847 spin_lock_irqsave(&EXT4_I(inode)->i_completed_io_lock, flags);
2848 list_add_tail(&io_end->list, &EXT4_I(inode)->i_completed_io_list);
2849 spin_unlock_irqrestore(&EXT4_I(inode)->i_completed_io_lock, flags);
2851 wq = EXT4_SB(inode->i_sb)->dio_unwritten_wq;
2852 /* queue the work to convert unwritten extents to written */
2853 queue_work(wq, &io_end->work);
2855 bh->b_private = NULL;
2856 bh->b_end_io = NULL;
2857 clear_buffer_uninit(bh);
2858 end_buffer_async_write(bh, uptodate);
2861 static int ext4_set_bh_endio(struct buffer_head *bh, struct inode *inode)
2863 ext4_io_end_t *io_end;
2864 struct page *page = bh->b_page;
2865 loff_t offset = (sector_t)page->index << PAGE_CACHE_SHIFT;
2866 size_t size = bh->b_size;
2869 io_end = ext4_init_io_end(inode, GFP_ATOMIC);
2871 pr_warn_ratelimited("%s: allocation fail\n", __func__);
2875 io_end->offset = offset;
2876 io_end->size = size;
2878 * We need to hold a reference to the page to make sure it
2879 * doesn't get evicted before ext4_end_io_work() has a chance
2880 * to convert the extent from written to unwritten.
2882 io_end->page = page;
2883 get_page(io_end->page);
2885 bh->b_private = io_end;
2886 bh->b_end_io = ext4_end_io_buffer_write;
2891 * For ext4 extent files, ext4 will do direct-io write to holes,
2892 * preallocated extents, and those write extend the file, no need to
2893 * fall back to buffered IO.
2895 * For holes, we fallocate those blocks, mark them as uninitialized
2896 * If those blocks were preallocated, we mark sure they are splited, but
2897 * still keep the range to write as uninitialized.
2899 * The unwrritten extents will be converted to written when DIO is completed.
2900 * For async direct IO, since the IO may still pending when return, we
2901 * set up an end_io call back function, which will do the conversion
2902 * when async direct IO completed.
2904 * If the O_DIRECT write will extend the file then add this inode to the
2905 * orphan list. So recovery will truncate it back to the original size
2906 * if the machine crashes during the write.
2909 static ssize_t ext4_ext_direct_IO(int rw, struct kiocb *iocb,
2910 const struct iovec *iov, loff_t offset,
2911 unsigned long nr_segs)
2913 struct file *file = iocb->ki_filp;
2914 struct inode *inode = file->f_mapping->host;
2916 size_t count = iov_length(iov, nr_segs);
2918 loff_t final_size = offset + count;
2919 if (rw == WRITE && final_size <= inode->i_size) {
2921 * We could direct write to holes and fallocate.
2923 * Allocated blocks to fill the hole are marked as uninitialized
2924 * to prevent parallel buffered read to expose the stale data
2925 * before DIO complete the data IO.
2927 * As to previously fallocated extents, ext4 get_block
2928 * will just simply mark the buffer mapped but still
2929 * keep the extents uninitialized.
2931 * for non AIO case, we will convert those unwritten extents
2932 * to written after return back from blockdev_direct_IO.
2934 * for async DIO, the conversion needs to be defered when
2935 * the IO is completed. The ext4 end_io callback function
2936 * will be called to take care of the conversion work.
2937 * Here for async case, we allocate an io_end structure to
2940 iocb->private = NULL;
2941 EXT4_I(inode)->cur_aio_dio = NULL;
2942 if (!is_sync_kiocb(iocb)) {
2943 ext4_io_end_t *io_end =
2944 ext4_init_io_end(inode, GFP_NOFS);
2947 io_end->flag |= EXT4_IO_END_DIRECT;
2948 iocb->private = io_end;
2950 * we save the io structure for current async
2951 * direct IO, so that later ext4_map_blocks()
2952 * could flag the io structure whether there
2953 * is a unwritten extents needs to be converted
2954 * when IO is completed.
2956 EXT4_I(inode)->cur_aio_dio = iocb->private;
2959 ret = __blockdev_direct_IO(rw, iocb, inode,
2960 inode->i_sb->s_bdev, iov,
2962 ext4_get_block_write,
2965 DIO_LOCKING | DIO_SKIP_HOLES);
2967 EXT4_I(inode)->cur_aio_dio = NULL;
2969 * The io_end structure takes a reference to the inode,
2970 * that structure needs to be destroyed and the
2971 * reference to the inode need to be dropped, when IO is
2972 * complete, even with 0 byte write, or failed.
2974 * In the successful AIO DIO case, the io_end structure will be
2975 * desctroyed and the reference to the inode will be dropped
2976 * after the end_io call back function is called.
2978 * In the case there is 0 byte write, or error case, since
2979 * VFS direct IO won't invoke the end_io call back function,
2980 * we need to free the end_io structure here.
2982 if (ret != -EIOCBQUEUED && ret <= 0 && iocb->private) {
2983 ext4_free_io_end(iocb->private);
2984 iocb->private = NULL;
2985 } else if (ret > 0 && ext4_test_inode_state(inode,
2986 EXT4_STATE_DIO_UNWRITTEN)) {
2989 * for non AIO case, since the IO is already
2990 * completed, we could do the conversion right here
2992 err = ext4_convert_unwritten_extents(inode,
2996 ext4_clear_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN);
3001 /* for write the the end of file case, we fall back to old way */
3002 return ext4_ind_direct_IO(rw, iocb, iov, offset, nr_segs);
3005 static ssize_t ext4_direct_IO(int rw, struct kiocb *iocb,
3006 const struct iovec *iov, loff_t offset,
3007 unsigned long nr_segs)
3009 struct file *file = iocb->ki_filp;
3010 struct inode *inode = file->f_mapping->host;
3014 * If we are doing data journalling we don't support O_DIRECT
3016 if (ext4_should_journal_data(inode))
3019 trace_ext4_direct_IO_enter(inode, offset, iov_length(iov, nr_segs), rw);
3020 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3021 ret = ext4_ext_direct_IO(rw, iocb, iov, offset, nr_segs);
3023 ret = ext4_ind_direct_IO(rw, iocb, iov, offset, nr_segs);
3024 trace_ext4_direct_IO_exit(inode, offset,
3025 iov_length(iov, nr_segs), rw, ret);
3030 * Pages can be marked dirty completely asynchronously from ext4's journalling
3031 * activity. By filemap_sync_pte(), try_to_unmap_one(), etc. We cannot do
3032 * much here because ->set_page_dirty is called under VFS locks. The page is
3033 * not necessarily locked.
3035 * We cannot just dirty the page and leave attached buffers clean, because the
3036 * buffers' dirty state is "definitive". We cannot just set the buffers dirty
3037 * or jbddirty because all the journalling code will explode.
3039 * So what we do is to mark the page "pending dirty" and next time writepage
3040 * is called, propagate that into the buffers appropriately.
3042 static int ext4_journalled_set_page_dirty(struct page *page)
3044 SetPageChecked(page);
3045 return __set_page_dirty_nobuffers(page);
3048 static const struct address_space_operations ext4_ordered_aops = {
3049 .readpage = ext4_readpage,
3050 .readpages = ext4_readpages,
3051 .writepage = ext4_writepage,
3052 .write_begin = ext4_write_begin,
3053 .write_end = ext4_ordered_write_end,
3055 .invalidatepage = ext4_invalidatepage,
3056 .releasepage = ext4_releasepage,
3057 .direct_IO = ext4_direct_IO,
3058 .migratepage = buffer_migrate_page,
3059 .is_partially_uptodate = block_is_partially_uptodate,
3060 .error_remove_page = generic_error_remove_page,
3063 static const struct address_space_operations ext4_writeback_aops = {
3064 .readpage = ext4_readpage,
3065 .readpages = ext4_readpages,
3066 .writepage = ext4_writepage,
3067 .write_begin = ext4_write_begin,
3068 .write_end = ext4_writeback_write_end,
3070 .invalidatepage = ext4_invalidatepage,
3071 .releasepage = ext4_releasepage,
3072 .direct_IO = ext4_direct_IO,
3073 .migratepage = buffer_migrate_page,
3074 .is_partially_uptodate = block_is_partially_uptodate,
3075 .error_remove_page = generic_error_remove_page,
3078 static const struct address_space_operations ext4_journalled_aops = {
3079 .readpage = ext4_readpage,
3080 .readpages = ext4_readpages,
3081 .writepage = ext4_writepage,
3082 .write_begin = ext4_write_begin,
3083 .write_end = ext4_journalled_write_end,
3084 .set_page_dirty = ext4_journalled_set_page_dirty,
3086 .invalidatepage = ext4_invalidatepage,
3087 .releasepage = ext4_releasepage,
3088 .direct_IO = ext4_direct_IO,
3089 .is_partially_uptodate = block_is_partially_uptodate,
3090 .error_remove_page = generic_error_remove_page,
3093 static const struct address_space_operations ext4_da_aops = {
3094 .readpage = ext4_readpage,
3095 .readpages = ext4_readpages,
3096 .writepage = ext4_writepage,
3097 .writepages = ext4_da_writepages,
3098 .write_begin = ext4_da_write_begin,
3099 .write_end = ext4_da_write_end,
3101 .invalidatepage = ext4_da_invalidatepage,
3102 .releasepage = ext4_releasepage,
3103 .direct_IO = ext4_direct_IO,
3104 .migratepage = buffer_migrate_page,
3105 .is_partially_uptodate = block_is_partially_uptodate,
3106 .error_remove_page = generic_error_remove_page,
3109 void ext4_set_aops(struct inode *inode)
3111 switch (ext4_inode_journal_mode(inode)) {
3112 case EXT4_INODE_ORDERED_DATA_MODE:
3113 if (test_opt(inode->i_sb, DELALLOC))
3114 inode->i_mapping->a_ops = &ext4_da_aops;
3116 inode->i_mapping->a_ops = &ext4_ordered_aops;
3118 case EXT4_INODE_WRITEBACK_DATA_MODE:
3119 if (test_opt(inode->i_sb, DELALLOC))
3120 inode->i_mapping->a_ops = &ext4_da_aops;
3122 inode->i_mapping->a_ops = &ext4_writeback_aops;
3124 case EXT4_INODE_JOURNAL_DATA_MODE:
3125 inode->i_mapping->a_ops = &ext4_journalled_aops;
3134 * ext4_discard_partial_page_buffers()
3135 * Wrapper function for ext4_discard_partial_page_buffers_no_lock.
3136 * This function finds and locks the page containing the offset
3137 * "from" and passes it to ext4_discard_partial_page_buffers_no_lock.
3138 * Calling functions that already have the page locked should call
3139 * ext4_discard_partial_page_buffers_no_lock directly.
3141 int ext4_discard_partial_page_buffers(handle_t *handle,
3142 struct address_space *mapping, loff_t from,
3143 loff_t length, int flags)
3145 struct inode *inode = mapping->host;
3149 page = find_or_create_page(mapping, from >> PAGE_CACHE_SHIFT,
3150 mapping_gfp_mask(mapping) & ~__GFP_FS);
3154 err = ext4_discard_partial_page_buffers_no_lock(handle, inode, page,
3155 from, length, flags);
3158 page_cache_release(page);
3163 * ext4_discard_partial_page_buffers_no_lock()
3164 * Zeros a page range of length 'length' starting from offset 'from'.
3165 * Buffer heads that correspond to the block aligned regions of the
3166 * zeroed range will be unmapped. Unblock aligned regions
3167 * will have the corresponding buffer head mapped if needed so that
3168 * that region of the page can be updated with the partial zero out.
3170 * This function assumes that the page has already been locked. The
3171 * The range to be discarded must be contained with in the given page.
3172 * If the specified range exceeds the end of the page it will be shortened
3173 * to the end of the page that corresponds to 'from'. This function is
3174 * appropriate for updating a page and it buffer heads to be unmapped and
3175 * zeroed for blocks that have been either released, or are going to be
3178 * handle: The journal handle
3179 * inode: The files inode
3180 * page: A locked page that contains the offset "from"
3181 * from: The starting byte offset (from the begining of the file)
3182 * to begin discarding
3183 * len: The length of bytes to discard
3184 * flags: Optional flags that may be used:
3186 * EXT4_DISCARD_PARTIAL_PG_ZERO_UNMAPPED
3187 * Only zero the regions of the page whose buffer heads
3188 * have already been unmapped. This flag is appropriate
3189 * for updateing the contents of a page whose blocks may
3190 * have already been released, and we only want to zero
3191 * out the regions that correspond to those released blocks.
3193 * Returns zero on sucess or negative on failure.
3195 int ext4_discard_partial_page_buffers_no_lock(handle_t *handle,
3196 struct inode *inode, struct page *page, loff_t from,
3197 loff_t length, int flags)
3199 ext4_fsblk_t index = from >> PAGE_CACHE_SHIFT;
3200 unsigned int offset = from & (PAGE_CACHE_SIZE-1);
3201 unsigned int blocksize, max, pos;
3203 struct buffer_head *bh;
3206 blocksize = inode->i_sb->s_blocksize;
3207 max = PAGE_CACHE_SIZE - offset;
3209 if (index != page->index)
3213 * correct length if it does not fall between
3214 * 'from' and the end of the page
3216 if (length > max || length < 0)
3219 iblock = index << (PAGE_CACHE_SHIFT - inode->i_sb->s_blocksize_bits);
3221 if (!page_has_buffers(page))
3222 create_empty_buffers(page, blocksize, 0);
3224 /* Find the buffer that contains "offset" */
3225 bh = page_buffers(page);
3227 while (offset >= pos) {
3228 bh = bh->b_this_page;
3234 while (pos < offset + length) {
3235 unsigned int end_of_block, range_to_discard;
3239 /* The length of space left to zero and unmap */
3240 range_to_discard = offset + length - pos;
3242 /* The length of space until the end of the block */
3243 end_of_block = blocksize - (pos & (blocksize-1));
3246 * Do not unmap or zero past end of block
3247 * for this buffer head
3249 if (range_to_discard > end_of_block)
3250 range_to_discard = end_of_block;
3254 * Skip this buffer head if we are only zeroing unampped
3255 * regions of the page
3257 if (flags & EXT4_DISCARD_PARTIAL_PG_ZERO_UNMAPPED &&
3261 /* If the range is block aligned, unmap */
3262 if (range_to_discard == blocksize) {
3263 clear_buffer_dirty(bh);
3265 clear_buffer_mapped(bh);
3266 clear_buffer_req(bh);
3267 clear_buffer_new(bh);
3268 clear_buffer_delay(bh);
3269 clear_buffer_unwritten(bh);
3270 clear_buffer_uptodate(bh);
3271 zero_user(page, pos, range_to_discard);
3272 BUFFER_TRACE(bh, "Buffer discarded");
3277 * If this block is not completely contained in the range
3278 * to be discarded, then it is not going to be released. Because
3279 * we need to keep this block, we need to make sure this part
3280 * of the page is uptodate before we modify it by writeing
3281 * partial zeros on it.
3283 if (!buffer_mapped(bh)) {
3285 * Buffer head must be mapped before we can read
3288 BUFFER_TRACE(bh, "unmapped");
3289 ext4_get_block(inode, iblock, bh, 0);
3290 /* unmapped? It's a hole - nothing to do */
3291 if (!buffer_mapped(bh)) {
3292 BUFFER_TRACE(bh, "still unmapped");
3297 /* Ok, it's mapped. Make sure it's up-to-date */
3298 if (PageUptodate(page))
3299 set_buffer_uptodate(bh);
3301 if (!buffer_uptodate(bh)) {
3303 ll_rw_block(READ, 1, &bh);
3305 /* Uhhuh. Read error. Complain and punt.*/
3306 if (!buffer_uptodate(bh))
3310 if (ext4_should_journal_data(inode)) {
3311 BUFFER_TRACE(bh, "get write access");
3312 err = ext4_journal_get_write_access(handle, bh);
3317 zero_user(page, pos, range_to_discard);
3320 if (ext4_should_journal_data(inode)) {
3321 err = ext4_handle_dirty_metadata(handle, inode, bh);
3323 mark_buffer_dirty(bh);
3325 BUFFER_TRACE(bh, "Partial buffer zeroed");
3327 bh = bh->b_this_page;
3329 pos += range_to_discard;
3336 * ext4_block_truncate_page() zeroes out a mapping from file offset `from'
3337 * up to the end of the block which corresponds to `from'.
3338 * This required during truncate. We need to physically zero the tail end
3339 * of that block so it doesn't yield old data if the file is later grown.
3341 int ext4_block_truncate_page(handle_t *handle,
3342 struct address_space *mapping, loff_t from)
3344 unsigned offset = from & (PAGE_CACHE_SIZE-1);
3347 struct inode *inode = mapping->host;
3349 blocksize = inode->i_sb->s_blocksize;
3350 length = blocksize - (offset & (blocksize - 1));
3352 return ext4_block_zero_page_range(handle, mapping, from, length);
3356 * ext4_block_zero_page_range() zeros out a mapping of length 'length'
3357 * starting from file offset 'from'. The range to be zero'd must
3358 * be contained with in one block. If the specified range exceeds
3359 * the end of the block it will be shortened to end of the block
3360 * that cooresponds to 'from'
3362 int ext4_block_zero_page_range(handle_t *handle,
3363 struct address_space *mapping, loff_t from, loff_t length)
3365 ext4_fsblk_t index = from >> PAGE_CACHE_SHIFT;
3366 unsigned offset = from & (PAGE_CACHE_SIZE-1);
3367 unsigned blocksize, max, pos;
3369 struct inode *inode = mapping->host;
3370 struct buffer_head *bh;
3374 page = find_or_create_page(mapping, from >> PAGE_CACHE_SHIFT,
3375 mapping_gfp_mask(mapping) & ~__GFP_FS);
3379 blocksize = inode->i_sb->s_blocksize;
3380 max = blocksize - (offset & (blocksize - 1));
3383 * correct length if it does not fall between
3384 * 'from' and the end of the block
3386 if (length > max || length < 0)
3389 iblock = index << (PAGE_CACHE_SHIFT - inode->i_sb->s_blocksize_bits);
3391 if (!page_has_buffers(page))
3392 create_empty_buffers(page, blocksize, 0);
3394 /* Find the buffer that contains "offset" */
3395 bh = page_buffers(page);
3397 while (offset >= pos) {
3398 bh = bh->b_this_page;
3404 if (buffer_freed(bh)) {
3405 BUFFER_TRACE(bh, "freed: skip");
3409 if (!buffer_mapped(bh)) {
3410 BUFFER_TRACE(bh, "unmapped");
3411 ext4_get_block(inode, iblock, bh, 0);
3412 /* unmapped? It's a hole - nothing to do */
3413 if (!buffer_mapped(bh)) {
3414 BUFFER_TRACE(bh, "still unmapped");
3419 /* Ok, it's mapped. Make sure it's up-to-date */
3420 if (PageUptodate(page))
3421 set_buffer_uptodate(bh);
3423 if (!buffer_uptodate(bh)) {
3425 ll_rw_block(READ, 1, &bh);
3427 /* Uhhuh. Read error. Complain and punt. */
3428 if (!buffer_uptodate(bh))
3432 if (ext4_should_journal_data(inode)) {
3433 BUFFER_TRACE(bh, "get write access");
3434 err = ext4_journal_get_write_access(handle, bh);
3439 zero_user(page, offset, length);
3441 BUFFER_TRACE(bh, "zeroed end of block");
3444 if (ext4_should_journal_data(inode)) {
3445 err = ext4_handle_dirty_metadata(handle, inode, bh);
3447 mark_buffer_dirty(bh);
3451 page_cache_release(page);
3455 int ext4_can_truncate(struct inode *inode)
3457 if (S_ISREG(inode->i_mode))
3459 if (S_ISDIR(inode->i_mode))
3461 if (S_ISLNK(inode->i_mode))
3462 return !ext4_inode_is_fast_symlink(inode);
3467 * ext4_punch_hole: punches a hole in a file by releaseing the blocks
3468 * associated with the given offset and length
3470 * @inode: File inode
3471 * @offset: The offset where the hole will begin
3472 * @len: The length of the hole
3474 * Returns: 0 on sucess or negative on failure
3477 int ext4_punch_hole(struct file *file, loff_t offset, loff_t length)
3479 struct inode *inode = file->f_path.dentry->d_inode;
3480 if (!S_ISREG(inode->i_mode))
3483 if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
3484 /* TODO: Add support for non extent hole punching */
3488 if (EXT4_SB(inode->i_sb)->s_cluster_ratio > 1) {
3489 /* TODO: Add support for bigalloc file systems */
3493 return ext4_ext_punch_hole(file, offset, length);
3499 * We block out ext4_get_block() block instantiations across the entire
3500 * transaction, and VFS/VM ensures that ext4_truncate() cannot run
3501 * simultaneously on behalf of the same inode.
3503 * As we work through the truncate and commmit bits of it to the journal there
3504 * is one core, guiding principle: the file's tree must always be consistent on
3505 * disk. We must be able to restart the truncate after a crash.
3507 * The file's tree may be transiently inconsistent in memory (although it
3508 * probably isn't), but whenever we close off and commit a journal transaction,
3509 * the contents of (the filesystem + the journal) must be consistent and
3510 * restartable. It's pretty simple, really: bottom up, right to left (although
3511 * left-to-right works OK too).
3513 * Note that at recovery time, journal replay occurs *before* the restart of
3514 * truncate against the orphan inode list.
3516 * The committed inode has the new, desired i_size (which is the same as
3517 * i_disksize in this case). After a crash, ext4_orphan_cleanup() will see
3518 * that this inode's truncate did not complete and it will again call
3519 * ext4_truncate() to have another go. So there will be instantiated blocks
3520 * to the right of the truncation point in a crashed ext4 filesystem. But
3521 * that's fine - as long as they are linked from the inode, the post-crash
3522 * ext4_truncate() run will find them and release them.
3524 void ext4_truncate(struct inode *inode)
3526 trace_ext4_truncate_enter(inode);
3528 if (!ext4_can_truncate(inode))
3531 ext4_clear_inode_flag(inode, EXT4_INODE_EOFBLOCKS);
3533 if (inode->i_size == 0 && !test_opt(inode->i_sb, NO_AUTO_DA_ALLOC))
3534 ext4_set_inode_state(inode, EXT4_STATE_DA_ALLOC_CLOSE);
3536 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3537 ext4_ext_truncate(inode);
3539 ext4_ind_truncate(inode);
3541 trace_ext4_truncate_exit(inode);
3545 * ext4_get_inode_loc returns with an extra refcount against the inode's
3546 * underlying buffer_head on success. If 'in_mem' is true, we have all
3547 * data in memory that is needed to recreate the on-disk version of this
3550 static int __ext4_get_inode_loc(struct inode *inode,
3551 struct ext4_iloc *iloc, int in_mem)
3553 struct ext4_group_desc *gdp;
3554 struct buffer_head *bh;
3555 struct super_block *sb = inode->i_sb;
3557 int inodes_per_block, inode_offset;
3560 if (!ext4_valid_inum(sb, inode->i_ino))
3563 iloc->block_group = (inode->i_ino - 1) / EXT4_INODES_PER_GROUP(sb);
3564 gdp = ext4_get_group_desc(sb, iloc->block_group, NULL);
3569 * Figure out the offset within the block group inode table
3571 inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
3572 inode_offset = ((inode->i_ino - 1) %
3573 EXT4_INODES_PER_GROUP(sb));
3574 block = ext4_inode_table(sb, gdp) + (inode_offset / inodes_per_block);
3575 iloc->offset = (inode_offset % inodes_per_block) * EXT4_INODE_SIZE(sb);
3577 bh = sb_getblk(sb, block);
3580 if (!buffer_uptodate(bh)) {
3584 * If the buffer has the write error flag, we have failed
3585 * to write out another inode in the same block. In this
3586 * case, we don't have to read the block because we may
3587 * read the old inode data successfully.
3589 if (buffer_write_io_error(bh) && !buffer_uptodate(bh))
3590 set_buffer_uptodate(bh);
3592 if (buffer_uptodate(bh)) {
3593 /* someone brought it uptodate while we waited */
3599 * If we have all information of the inode in memory and this
3600 * is the only valid inode in the block, we need not read the
3604 struct buffer_head *bitmap_bh;
3607 start = inode_offset & ~(inodes_per_block - 1);
3609 /* Is the inode bitmap in cache? */
3610 bitmap_bh = sb_getblk(sb, ext4_inode_bitmap(sb, gdp));
3615 * If the inode bitmap isn't in cache then the
3616 * optimisation may end up performing two reads instead
3617 * of one, so skip it.
3619 if (!buffer_uptodate(bitmap_bh)) {
3623 for (i = start; i < start + inodes_per_block; i++) {
3624 if (i == inode_offset)
3626 if (ext4_test_bit(i, bitmap_bh->b_data))
3630 if (i == start + inodes_per_block) {
3631 /* all other inodes are free, so skip I/O */
3632 memset(bh->b_data, 0, bh->b_size);
3633 set_buffer_uptodate(bh);
3641 * If we need to do any I/O, try to pre-readahead extra
3642 * blocks from the inode table.
3644 if (EXT4_SB(sb)->s_inode_readahead_blks) {
3645 ext4_fsblk_t b, end, table;
3648 table = ext4_inode_table(sb, gdp);
3649 /* s_inode_readahead_blks is always a power of 2 */
3650 b = block & ~(EXT4_SB(sb)->s_inode_readahead_blks-1);
3653 end = b + EXT4_SB(sb)->s_inode_readahead_blks;
3654 num = EXT4_INODES_PER_GROUP(sb);
3655 if (EXT4_HAS_RO_COMPAT_FEATURE(sb,
3656 EXT4_FEATURE_RO_COMPAT_GDT_CSUM))
3657 num -= ext4_itable_unused_count(sb, gdp);
3658 table += num / inodes_per_block;
3662 sb_breadahead(sb, b++);
3666 * There are other valid inodes in the buffer, this inode
3667 * has in-inode xattrs, or we don't have this inode in memory.
3668 * Read the block from disk.
3670 trace_ext4_load_inode(inode);
3672 bh->b_end_io = end_buffer_read_sync;
3673 submit_bh(READ | REQ_META | REQ_PRIO, bh);
3675 if (!buffer_uptodate(bh)) {
3676 EXT4_ERROR_INODE_BLOCK(inode, block,
3677 "unable to read itable block");
3687 int ext4_get_inode_loc(struct inode *inode, struct ext4_iloc *iloc)
3689 /* We have all inode data except xattrs in memory here. */
3690 return __ext4_get_inode_loc(inode, iloc,
3691 !ext4_test_inode_state(inode, EXT4_STATE_XATTR));
3694 void ext4_set_inode_flags(struct inode *inode)
3696 unsigned int flags = EXT4_I(inode)->i_flags;
3698 inode->i_flags &= ~(S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME|S_DIRSYNC);
3699 if (flags & EXT4_SYNC_FL)
3700 inode->i_flags |= S_SYNC;
3701 if (flags & EXT4_APPEND_FL)
3702 inode->i_flags |= S_APPEND;
3703 if (flags & EXT4_IMMUTABLE_FL)
3704 inode->i_flags |= S_IMMUTABLE;
3705 if (flags & EXT4_NOATIME_FL)
3706 inode->i_flags |= S_NOATIME;
3707 if (flags & EXT4_DIRSYNC_FL)
3708 inode->i_flags |= S_DIRSYNC;
3711 /* Propagate flags from i_flags to EXT4_I(inode)->i_flags */
3712 void ext4_get_inode_flags(struct ext4_inode_info *ei)
3714 unsigned int vfs_fl;
3715 unsigned long old_fl, new_fl;
3718 vfs_fl = ei->vfs_inode.i_flags;
3719 old_fl = ei->i_flags;
3720 new_fl = old_fl & ~(EXT4_SYNC_FL|EXT4_APPEND_FL|
3721 EXT4_IMMUTABLE_FL|EXT4_NOATIME_FL|
3723 if (vfs_fl & S_SYNC)
3724 new_fl |= EXT4_SYNC_FL;
3725 if (vfs_fl & S_APPEND)
3726 new_fl |= EXT4_APPEND_FL;
3727 if (vfs_fl & S_IMMUTABLE)
3728 new_fl |= EXT4_IMMUTABLE_FL;
3729 if (vfs_fl & S_NOATIME)
3730 new_fl |= EXT4_NOATIME_FL;
3731 if (vfs_fl & S_DIRSYNC)
3732 new_fl |= EXT4_DIRSYNC_FL;
3733 } while (cmpxchg(&ei->i_flags, old_fl, new_fl) != old_fl);
3736 static blkcnt_t ext4_inode_blocks(struct ext4_inode *raw_inode,
3737 struct ext4_inode_info *ei)
3740 struct inode *inode = &(ei->vfs_inode);
3741 struct super_block *sb = inode->i_sb;
3743 if (EXT4_HAS_RO_COMPAT_FEATURE(sb,
3744 EXT4_FEATURE_RO_COMPAT_HUGE_FILE)) {
3745 /* we are using combined 48 bit field */
3746 i_blocks = ((u64)le16_to_cpu(raw_inode->i_blocks_high)) << 32 |
3747 le32_to_cpu(raw_inode->i_blocks_lo);
3748 if (ext4_test_inode_flag(inode, EXT4_INODE_HUGE_FILE)) {
3749 /* i_blocks represent file system block size */
3750 return i_blocks << (inode->i_blkbits - 9);
3755 return le32_to_cpu(raw_inode->i_blocks_lo);
3759 struct inode *ext4_iget(struct super_block *sb, unsigned long ino)
3761 struct ext4_iloc iloc;
3762 struct ext4_inode *raw_inode;
3763 struct ext4_inode_info *ei;
3764 struct inode *inode;
3765 journal_t *journal = EXT4_SB(sb)->s_journal;
3769 inode = iget_locked(sb, ino);
3771 return ERR_PTR(-ENOMEM);
3772 if (!(inode->i_state & I_NEW))
3778 ret = __ext4_get_inode_loc(inode, &iloc, 0);
3781 raw_inode = ext4_raw_inode(&iloc);
3782 inode->i_mode = le16_to_cpu(raw_inode->i_mode);
3783 inode->i_uid = (uid_t)le16_to_cpu(raw_inode->i_uid_low);
3784 inode->i_gid = (gid_t)le16_to_cpu(raw_inode->i_gid_low);
3785 if (!(test_opt(inode->i_sb, NO_UID32))) {
3786 inode->i_uid |= le16_to_cpu(raw_inode->i_uid_high) << 16;
3787 inode->i_gid |= le16_to_cpu(raw_inode->i_gid_high) << 16;
3789 set_nlink(inode, le16_to_cpu(raw_inode->i_links_count));
3791 ext4_clear_state_flags(ei); /* Only relevant on 32-bit archs */
3792 ei->i_dir_start_lookup = 0;
3793 ei->i_dtime = le32_to_cpu(raw_inode->i_dtime);
3794 /* We now have enough fields to check if the inode was active or not.
3795 * This is needed because nfsd might try to access dead inodes
3796 * the test is that same one that e2fsck uses
3797 * NeilBrown 1999oct15
3799 if (inode->i_nlink == 0) {
3800 if (inode->i_mode == 0 ||
3801 !(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_ORPHAN_FS)) {
3802 /* this inode is deleted */
3806 /* The only unlinked inodes we let through here have
3807 * valid i_mode and are being read by the orphan
3808 * recovery code: that's fine, we're about to complete
3809 * the process of deleting those. */
3811 ei->i_flags = le32_to_cpu(raw_inode->i_flags);
3812 inode->i_blocks = ext4_inode_blocks(raw_inode, ei);
3813 ei->i_file_acl = le32_to_cpu(raw_inode->i_file_acl_lo);
3814 if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_64BIT))
3816 ((__u64)le16_to_cpu(raw_inode->i_file_acl_high)) << 32;
3817 inode->i_size = ext4_isize(raw_inode);
3818 ei->i_disksize = inode->i_size;
3820 ei->i_reserved_quota = 0;
3822 inode->i_generation = le32_to_cpu(raw_inode->i_generation);
3823 ei->i_block_group = iloc.block_group;
3824 ei->i_last_alloc_group = ~0;
3826 * NOTE! The in-memory inode i_data array is in little-endian order
3827 * even on big-endian machines: we do NOT byteswap the block numbers!
3829 for (block = 0; block < EXT4_N_BLOCKS; block++)
3830 ei->i_data[block] = raw_inode->i_block[block];
3831 INIT_LIST_HEAD(&ei->i_orphan);
3834 * Set transaction id's of transactions that have to be committed
3835 * to finish f[data]sync. We set them to currently running transaction
3836 * as we cannot be sure that the inode or some of its metadata isn't
3837 * part of the transaction - the inode could have been reclaimed and
3838 * now it is reread from disk.
3841 transaction_t *transaction;
3844 read_lock(&journal->j_state_lock);
3845 if (journal->j_running_transaction)
3846 transaction = journal->j_running_transaction;
3848 transaction = journal->j_committing_transaction;
3850 tid = transaction->t_tid;
3852 tid = journal->j_commit_sequence;
3853 read_unlock(&journal->j_state_lock);
3854 ei->i_sync_tid = tid;
3855 ei->i_datasync_tid = tid;
3858 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
3859 ei->i_extra_isize = le16_to_cpu(raw_inode->i_extra_isize);
3860 if (EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize >
3861 EXT4_INODE_SIZE(inode->i_sb)) {
3865 if (ei->i_extra_isize == 0) {
3866 /* The extra space is currently unused. Use it. */
3867 ei->i_extra_isize = sizeof(struct ext4_inode) -
3868 EXT4_GOOD_OLD_INODE_SIZE;
3870 __le32 *magic = (void *)raw_inode +
3871 EXT4_GOOD_OLD_INODE_SIZE +
3873 if (*magic == cpu_to_le32(EXT4_XATTR_MAGIC))
3874 ext4_set_inode_state(inode, EXT4_STATE_XATTR);
3877 ei->i_extra_isize = 0;
3879 EXT4_INODE_GET_XTIME(i_ctime, inode, raw_inode);
3880 EXT4_INODE_GET_XTIME(i_mtime, inode, raw_inode);
3881 EXT4_INODE_GET_XTIME(i_atime, inode, raw_inode);
3882 EXT4_EINODE_GET_XTIME(i_crtime, ei, raw_inode);
3884 inode->i_version = le32_to_cpu(raw_inode->i_disk_version);
3885 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
3886 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
3888 (__u64)(le32_to_cpu(raw_inode->i_version_hi)) << 32;
3892 if (ei->i_file_acl &&
3893 !ext4_data_block_valid(EXT4_SB(sb), ei->i_file_acl, 1)) {
3894 EXT4_ERROR_INODE(inode, "bad extended attribute block %llu",
3898 } else if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
3899 if (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
3900 (S_ISLNK(inode->i_mode) &&
3901 !ext4_inode_is_fast_symlink(inode)))
3902 /* Validate extent which is part of inode */
3903 ret = ext4_ext_check_inode(inode);
3904 } else if (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
3905 (S_ISLNK(inode->i_mode) &&
3906 !ext4_inode_is_fast_symlink(inode))) {
3907 /* Validate block references which are part of inode */
3908 ret = ext4_ind_check_inode(inode);
3913 if (S_ISREG(inode->i_mode)) {
3914 inode->i_op = &ext4_file_inode_operations;
3915 inode->i_fop = &ext4_file_operations;
3916 ext4_set_aops(inode);
3917 } else if (S_ISDIR(inode->i_mode)) {
3918 inode->i_op = &ext4_dir_inode_operations;
3919 inode->i_fop = &ext4_dir_operations;
3920 } else if (S_ISLNK(inode->i_mode)) {
3921 if (ext4_inode_is_fast_symlink(inode)) {
3922 inode->i_op = &ext4_fast_symlink_inode_operations;
3923 nd_terminate_link(ei->i_data, inode->i_size,
3924 sizeof(ei->i_data) - 1);
3926 inode->i_op = &ext4_symlink_inode_operations;
3927 ext4_set_aops(inode);
3929 } else if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode) ||
3930 S_ISFIFO(inode->i_mode) || S_ISSOCK(inode->i_mode)) {
3931 inode->i_op = &ext4_special_inode_operations;
3932 if (raw_inode->i_block[0])
3933 init_special_inode(inode, inode->i_mode,
3934 old_decode_dev(le32_to_cpu(raw_inode->i_block[0])));
3936 init_special_inode(inode, inode->i_mode,
3937 new_decode_dev(le32_to_cpu(raw_inode->i_block[1])));
3940 EXT4_ERROR_INODE(inode, "bogus i_mode (%o)", inode->i_mode);
3944 ext4_set_inode_flags(inode);
3945 unlock_new_inode(inode);
3951 return ERR_PTR(ret);
3954 static int ext4_inode_blocks_set(handle_t *handle,
3955 struct ext4_inode *raw_inode,
3956 struct ext4_inode_info *ei)
3958 struct inode *inode = &(ei->vfs_inode);
3959 u64 i_blocks = inode->i_blocks;
3960 struct super_block *sb = inode->i_sb;
3962 if (i_blocks <= ~0U) {
3964 * i_blocks can be represnted in a 32 bit variable
3965 * as multiple of 512 bytes
3967 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
3968 raw_inode->i_blocks_high = 0;
3969 ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
3972 if (!EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_HUGE_FILE))
3975 if (i_blocks <= 0xffffffffffffULL) {
3977 * i_blocks can be represented in a 48 bit variable
3978 * as multiple of 512 bytes
3980 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
3981 raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
3982 ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
3984 ext4_set_inode_flag(inode, EXT4_INODE_HUGE_FILE);
3985 /* i_block is stored in file system block size */
3986 i_blocks = i_blocks >> (inode->i_blkbits - 9);
3987 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
3988 raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
3994 * Post the struct inode info into an on-disk inode location in the
3995 * buffer-cache. This gobbles the caller's reference to the
3996 * buffer_head in the inode location struct.
3998 * The caller must have write access to iloc->bh.
4000 static int ext4_do_update_inode(handle_t *handle,
4001 struct inode *inode,
4002 struct ext4_iloc *iloc)
4004 struct ext4_inode *raw_inode = ext4_raw_inode(iloc);
4005 struct ext4_inode_info *ei = EXT4_I(inode);
4006 struct buffer_head *bh = iloc->bh;
4007 int err = 0, rc, block;
4008 int need_datasync = 0;
4010 /* For fields not not tracking in the in-memory inode,
4011 * initialise them to zero for new inodes. */
4012 if (ext4_test_inode_state(inode, EXT4_STATE_NEW))
4013 memset(raw_inode, 0, EXT4_SB(inode->i_sb)->s_inode_size);
4015 ext4_get_inode_flags(ei);
4016 raw_inode->i_mode = cpu_to_le16(inode->i_mode);
4017 if (!(test_opt(inode->i_sb, NO_UID32))) {
4018 raw_inode->i_uid_low = cpu_to_le16(low_16_bits(inode->i_uid));
4019 raw_inode->i_gid_low = cpu_to_le16(low_16_bits(inode->i_gid));
4021 * Fix up interoperability with old kernels. Otherwise, old inodes get
4022 * re-used with the upper 16 bits of the uid/gid intact
4025 raw_inode->i_uid_high =
4026 cpu_to_le16(high_16_bits(inode->i_uid));
4027 raw_inode->i_gid_high =
4028 cpu_to_le16(high_16_bits(inode->i_gid));
4030 raw_inode->i_uid_high = 0;
4031 raw_inode->i_gid_high = 0;
4034 raw_inode->i_uid_low =
4035 cpu_to_le16(fs_high2lowuid(inode->i_uid));
4036 raw_inode->i_gid_low =
4037 cpu_to_le16(fs_high2lowgid(inode->i_gid));
4038 raw_inode->i_uid_high = 0;
4039 raw_inode->i_gid_high = 0;
4041 raw_inode->i_links_count = cpu_to_le16(inode->i_nlink);
4043 EXT4_INODE_SET_XTIME(i_ctime, inode, raw_inode);
4044 EXT4_INODE_SET_XTIME(i_mtime, inode, raw_inode);
4045 EXT4_INODE_SET_XTIME(i_atime, inode, raw_inode);
4046 EXT4_EINODE_SET_XTIME(i_crtime, ei, raw_inode);
4048 if (ext4_inode_blocks_set(handle, raw_inode, ei))
4050 raw_inode->i_dtime = cpu_to_le32(ei->i_dtime);
4051 raw_inode->i_flags = cpu_to_le32(ei->i_flags & 0xFFFFFFFF);
4052 if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
4053 cpu_to_le32(EXT4_OS_HURD))
4054 raw_inode->i_file_acl_high =
4055 cpu_to_le16(ei->i_file_acl >> 32);
4056 raw_inode->i_file_acl_lo = cpu_to_le32(ei->i_file_acl);
4057 if (ei->i_disksize != ext4_isize(raw_inode)) {
4058 ext4_isize_set(raw_inode, ei->i_disksize);
4061 if (ei->i_disksize > 0x7fffffffULL) {
4062 struct super_block *sb = inode->i_sb;
4063 if (!EXT4_HAS_RO_COMPAT_FEATURE(sb,
4064 EXT4_FEATURE_RO_COMPAT_LARGE_FILE) ||
4065 EXT4_SB(sb)->s_es->s_rev_level ==
4066 cpu_to_le32(EXT4_GOOD_OLD_REV)) {
4067 /* If this is the first large file
4068 * created, add a flag to the superblock.
4070 err = ext4_journal_get_write_access(handle,
4071 EXT4_SB(sb)->s_sbh);
4074 ext4_update_dynamic_rev(sb);
4075 EXT4_SET_RO_COMPAT_FEATURE(sb,
4076 EXT4_FEATURE_RO_COMPAT_LARGE_FILE);
4078 ext4_handle_sync(handle);
4079 err = ext4_handle_dirty_metadata(handle, NULL,
4080 EXT4_SB(sb)->s_sbh);
4083 raw_inode->i_generation = cpu_to_le32(inode->i_generation);
4084 if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) {
4085 if (old_valid_dev(inode->i_rdev)) {
4086 raw_inode->i_block[0] =
4087 cpu_to_le32(old_encode_dev(inode->i_rdev));
4088 raw_inode->i_block[1] = 0;
4090 raw_inode->i_block[0] = 0;
4091 raw_inode->i_block[1] =
4092 cpu_to_le32(new_encode_dev(inode->i_rdev));
4093 raw_inode->i_block[2] = 0;
4096 for (block = 0; block < EXT4_N_BLOCKS; block++)
4097 raw_inode->i_block[block] = ei->i_data[block];
4099 raw_inode->i_disk_version = cpu_to_le32(inode->i_version);
4100 if (ei->i_extra_isize) {
4101 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
4102 raw_inode->i_version_hi =
4103 cpu_to_le32(inode->i_version >> 32);
4104 raw_inode->i_extra_isize = cpu_to_le16(ei->i_extra_isize);
4107 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
4108 rc = ext4_handle_dirty_metadata(handle, NULL, bh);
4111 ext4_clear_inode_state(inode, EXT4_STATE_NEW);
4113 ext4_update_inode_fsync_trans(handle, inode, need_datasync);
4116 ext4_std_error(inode->i_sb, err);
4121 * ext4_write_inode()
4123 * We are called from a few places:
4125 * - Within generic_file_write() for O_SYNC files.
4126 * Here, there will be no transaction running. We wait for any running
4127 * trasnaction to commit.
4129 * - Within sys_sync(), kupdate and such.
4130 * We wait on commit, if tol to.
4132 * - Within prune_icache() (PF_MEMALLOC == true)
4133 * Here we simply return. We can't afford to block kswapd on the
4136 * In all cases it is actually safe for us to return without doing anything,
4137 * because the inode has been copied into a raw inode buffer in
4138 * ext4_mark_inode_dirty(). This is a correctness thing for O_SYNC and for
4141 * Note that we are absolutely dependent upon all inode dirtiers doing the
4142 * right thing: they *must* call mark_inode_dirty() after dirtying info in
4143 * which we are interested.
4145 * It would be a bug for them to not do this. The code:
4147 * mark_inode_dirty(inode)
4149 * inode->i_size = expr;
4151 * is in error because a kswapd-driven write_inode() could occur while
4152 * `stuff()' is running, and the new i_size will be lost. Plus the inode
4153 * will no longer be on the superblock's dirty inode list.
4155 int ext4_write_inode(struct inode *inode, struct writeback_control *wbc)
4159 if (current->flags & PF_MEMALLOC)
4162 if (EXT4_SB(inode->i_sb)->s_journal) {
4163 if (ext4_journal_current_handle()) {
4164 jbd_debug(1, "called recursively, non-PF_MEMALLOC!\n");
4169 if (wbc->sync_mode != WB_SYNC_ALL)
4172 err = ext4_force_commit(inode->i_sb);
4174 struct ext4_iloc iloc;
4176 err = __ext4_get_inode_loc(inode, &iloc, 0);
4179 if (wbc->sync_mode == WB_SYNC_ALL)
4180 sync_dirty_buffer(iloc.bh);
4181 if (buffer_req(iloc.bh) && !buffer_uptodate(iloc.bh)) {
4182 EXT4_ERROR_INODE_BLOCK(inode, iloc.bh->b_blocknr,
4183 "IO error syncing inode");
4194 * Called from notify_change.
4196 * We want to trap VFS attempts to truncate the file as soon as
4197 * possible. In particular, we want to make sure that when the VFS
4198 * shrinks i_size, we put the inode on the orphan list and modify
4199 * i_disksize immediately, so that during the subsequent flushing of
4200 * dirty pages and freeing of disk blocks, we can guarantee that any
4201 * commit will leave the blocks being flushed in an unused state on
4202 * disk. (On recovery, the inode will get truncated and the blocks will
4203 * be freed, so we have a strong guarantee that no future commit will
4204 * leave these blocks visible to the user.)
4206 * Another thing we have to assure is that if we are in ordered mode
4207 * and inode is still attached to the committing transaction, we must
4208 * we start writeout of all the dirty pages which are being truncated.
4209 * This way we are sure that all the data written in the previous
4210 * transaction are already on disk (truncate waits for pages under
4213 * Called with inode->i_mutex down.
4215 int ext4_setattr(struct dentry *dentry, struct iattr *attr)
4217 struct inode *inode = dentry->d_inode;
4220 const unsigned int ia_valid = attr->ia_valid;
4222 error = inode_change_ok(inode, attr);
4226 if (is_quota_modification(inode, attr))
4227 dquot_initialize(inode);
4228 if ((ia_valid & ATTR_UID && attr->ia_uid != inode->i_uid) ||
4229 (ia_valid & ATTR_GID && attr->ia_gid != inode->i_gid)) {
4232 /* (user+group)*(old+new) structure, inode write (sb,
4233 * inode block, ? - but truncate inode update has it) */
4234 handle = ext4_journal_start(inode, (EXT4_MAXQUOTAS_INIT_BLOCKS(inode->i_sb)+
4235 EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb))+3);
4236 if (IS_ERR(handle)) {
4237 error = PTR_ERR(handle);
4240 error = dquot_transfer(inode, attr);
4242 ext4_journal_stop(handle);
4245 /* Update corresponding info in inode so that everything is in
4246 * one transaction */
4247 if (attr->ia_valid & ATTR_UID)
4248 inode->i_uid = attr->ia_uid;
4249 if (attr->ia_valid & ATTR_GID)
4250 inode->i_gid = attr->ia_gid;
4251 error = ext4_mark_inode_dirty(handle, inode);
4252 ext4_journal_stop(handle);
4255 if (attr->ia_valid & ATTR_SIZE) {
4256 inode_dio_wait(inode);
4258 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
4259 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4261 if (attr->ia_size > sbi->s_bitmap_maxbytes)
4266 if (S_ISREG(inode->i_mode) &&
4267 attr->ia_valid & ATTR_SIZE &&
4268 (attr->ia_size < inode->i_size)) {
4271 handle = ext4_journal_start(inode, 3);
4272 if (IS_ERR(handle)) {
4273 error = PTR_ERR(handle);
4276 if (ext4_handle_valid(handle)) {
4277 error = ext4_orphan_add(handle, inode);
4280 EXT4_I(inode)->i_disksize = attr->ia_size;
4281 rc = ext4_mark_inode_dirty(handle, inode);
4284 ext4_journal_stop(handle);
4286 if (ext4_should_order_data(inode)) {
4287 error = ext4_begin_ordered_truncate(inode,
4290 /* Do as much error cleanup as possible */
4291 handle = ext4_journal_start(inode, 3);
4292 if (IS_ERR(handle)) {
4293 ext4_orphan_del(NULL, inode);
4296 ext4_orphan_del(handle, inode);
4298 ext4_journal_stop(handle);
4304 if (attr->ia_valid & ATTR_SIZE) {
4305 if (attr->ia_size != i_size_read(inode)) {
4306 truncate_setsize(inode, attr->ia_size);
4307 ext4_truncate(inode);
4308 } else if (ext4_test_inode_flag(inode, EXT4_INODE_EOFBLOCKS))
4309 ext4_truncate(inode);
4313 setattr_copy(inode, attr);
4314 mark_inode_dirty(inode);
4318 * If the call to ext4_truncate failed to get a transaction handle at
4319 * all, we need to clean up the in-core orphan list manually.
4321 if (orphan && inode->i_nlink)
4322 ext4_orphan_del(NULL, inode);
4324 if (!rc && (ia_valid & ATTR_MODE))
4325 rc = ext4_acl_chmod(inode);
4328 ext4_std_error(inode->i_sb, error);
4334 int ext4_getattr(struct vfsmount *mnt, struct dentry *dentry,
4337 struct inode *inode;
4338 unsigned long long delalloc_blocks;
4340 inode = dentry->d_inode;
4341 generic_fillattr(inode, stat);
4344 * We can't update i_blocks if the block allocation is delayed
4345 * otherwise in the case of system crash before the real block
4346 * allocation is done, we will have i_blocks inconsistent with
4347 * on-disk file blocks.
4348 * We always keep i_blocks updated together with real
4349 * allocation. But to not confuse with user, stat
4350 * will return the blocks that include the delayed allocation
4351 * blocks for this file.
4353 delalloc_blocks = EXT4_I(inode)->i_reserved_data_blocks;
4355 stat->blocks += delalloc_blocks << (inode->i_sb->s_blocksize_bits-9);
4359 static int ext4_index_trans_blocks(struct inode *inode, int nrblocks, int chunk)
4361 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
4362 return ext4_ind_trans_blocks(inode, nrblocks, chunk);
4363 return ext4_ext_index_trans_blocks(inode, nrblocks, chunk);
4367 * Account for index blocks, block groups bitmaps and block group
4368 * descriptor blocks if modify datablocks and index blocks
4369 * worse case, the indexs blocks spread over different block groups
4371 * If datablocks are discontiguous, they are possible to spread over
4372 * different block groups too. If they are contiuguous, with flexbg,
4373 * they could still across block group boundary.
4375 * Also account for superblock, inode, quota and xattr blocks
4377 static int ext4_meta_trans_blocks(struct inode *inode, int nrblocks, int chunk)
4379 ext4_group_t groups, ngroups = ext4_get_groups_count(inode->i_sb);
4385 * How many index blocks need to touch to modify nrblocks?
4386 * The "Chunk" flag indicating whether the nrblocks is
4387 * physically contiguous on disk
4389 * For Direct IO and fallocate, they calls get_block to allocate
4390 * one single extent at a time, so they could set the "Chunk" flag
4392 idxblocks = ext4_index_trans_blocks(inode, nrblocks, chunk);
4397 * Now let's see how many group bitmaps and group descriptors need
4407 if (groups > ngroups)
4409 if (groups > EXT4_SB(inode->i_sb)->s_gdb_count)
4410 gdpblocks = EXT4_SB(inode->i_sb)->s_gdb_count;
4412 /* bitmaps and block group descriptor blocks */
4413 ret += groups + gdpblocks;
4415 /* Blocks for super block, inode, quota and xattr blocks */
4416 ret += EXT4_META_TRANS_BLOCKS(inode->i_sb);
4422 * Calculate the total number of credits to reserve to fit
4423 * the modification of a single pages into a single transaction,
4424 * which may include multiple chunks of block allocations.
4426 * This could be called via ext4_write_begin()
4428 * We need to consider the worse case, when
4429 * one new block per extent.
4431 int ext4_writepage_trans_blocks(struct inode *inode)
4433 int bpp = ext4_journal_blocks_per_page(inode);
4436 ret = ext4_meta_trans_blocks(inode, bpp, 0);
4438 /* Account for data blocks for journalled mode */
4439 if (ext4_should_journal_data(inode))
4445 * Calculate the journal credits for a chunk of data modification.
4447 * This is called from DIO, fallocate or whoever calling
4448 * ext4_map_blocks() to map/allocate a chunk of contiguous disk blocks.
4450 * journal buffers for data blocks are not included here, as DIO
4451 * and fallocate do no need to journal data buffers.
4453 int ext4_chunk_trans_blocks(struct inode *inode, int nrblocks)
4455 return ext4_meta_trans_blocks(inode, nrblocks, 1);
4459 * The caller must have previously called ext4_reserve_inode_write().
4460 * Give this, we know that the caller already has write access to iloc->bh.
4462 int ext4_mark_iloc_dirty(handle_t *handle,
4463 struct inode *inode, struct ext4_iloc *iloc)
4467 if (test_opt(inode->i_sb, I_VERSION))
4468 inode_inc_iversion(inode);
4470 /* the do_update_inode consumes one bh->b_count */
4473 /* ext4_do_update_inode() does jbd2_journal_dirty_metadata */
4474 err = ext4_do_update_inode(handle, inode, iloc);
4480 * On success, We end up with an outstanding reference count against
4481 * iloc->bh. This _must_ be cleaned up later.
4485 ext4_reserve_inode_write(handle_t *handle, struct inode *inode,
4486 struct ext4_iloc *iloc)
4490 err = ext4_get_inode_loc(inode, iloc);
4492 BUFFER_TRACE(iloc->bh, "get_write_access");
4493 err = ext4_journal_get_write_access(handle, iloc->bh);
4499 ext4_std_error(inode->i_sb, err);
4504 * Expand an inode by new_extra_isize bytes.
4505 * Returns 0 on success or negative error number on failure.
4507 static int ext4_expand_extra_isize(struct inode *inode,
4508 unsigned int new_extra_isize,
4509 struct ext4_iloc iloc,
4512 struct ext4_inode *raw_inode;
4513 struct ext4_xattr_ibody_header *header;
4515 if (EXT4_I(inode)->i_extra_isize >= new_extra_isize)
4518 raw_inode = ext4_raw_inode(&iloc);
4520 header = IHDR(inode, raw_inode);
4522 /* No extended attributes present */
4523 if (!ext4_test_inode_state(inode, EXT4_STATE_XATTR) ||
4524 header->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC)) {
4525 memset((void *)raw_inode + EXT4_GOOD_OLD_INODE_SIZE, 0,
4527 EXT4_I(inode)->i_extra_isize = new_extra_isize;
4531 /* try to expand with EAs present */
4532 return ext4_expand_extra_isize_ea(inode, new_extra_isize,
4537 * What we do here is to mark the in-core inode as clean with respect to inode
4538 * dirtiness (it may still be data-dirty).
4539 * This means that the in-core inode may be reaped by prune_icache
4540 * without having to perform any I/O. This is a very good thing,
4541 * because *any* task may call prune_icache - even ones which
4542 * have a transaction open against a different journal.
4544 * Is this cheating? Not really. Sure, we haven't written the
4545 * inode out, but prune_icache isn't a user-visible syncing function.
4546 * Whenever the user wants stuff synced (sys_sync, sys_msync, sys_fsync)
4547 * we start and wait on commits.
4549 * Is this efficient/effective? Well, we're being nice to the system
4550 * by cleaning up our inodes proactively so they can be reaped
4551 * without I/O. But we are potentially leaving up to five seconds'
4552 * worth of inodes floating about which prune_icache wants us to
4553 * write out. One way to fix that would be to get prune_icache()
4554 * to do a write_super() to free up some memory. It has the desired
4557 int ext4_mark_inode_dirty(handle_t *handle, struct inode *inode)
4559 struct ext4_iloc iloc;
4560 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4561 static unsigned int mnt_count;
4565 trace_ext4_mark_inode_dirty(inode, _RET_IP_);
4566 err = ext4_reserve_inode_write(handle, inode, &iloc);
4567 if (ext4_handle_valid(handle) &&
4568 EXT4_I(inode)->i_extra_isize < sbi->s_want_extra_isize &&
4569 !ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND)) {
4571 * We need extra buffer credits since we may write into EA block
4572 * with this same handle. If journal_extend fails, then it will
4573 * only result in a minor loss of functionality for that inode.
4574 * If this is felt to be critical, then e2fsck should be run to
4575 * force a large enough s_min_extra_isize.
4577 if ((jbd2_journal_extend(handle,
4578 EXT4_DATA_TRANS_BLOCKS(inode->i_sb))) == 0) {
4579 ret = ext4_expand_extra_isize(inode,
4580 sbi->s_want_extra_isize,
4583 ext4_set_inode_state(inode,
4584 EXT4_STATE_NO_EXPAND);
4586 le16_to_cpu(sbi->s_es->s_mnt_count)) {
4587 ext4_warning(inode->i_sb,
4588 "Unable to expand inode %lu. Delete"
4589 " some EAs or run e2fsck.",
4592 le16_to_cpu(sbi->s_es->s_mnt_count);
4598 err = ext4_mark_iloc_dirty(handle, inode, &iloc);
4603 * ext4_dirty_inode() is called from __mark_inode_dirty()
4605 * We're really interested in the case where a file is being extended.
4606 * i_size has been changed by generic_commit_write() and we thus need
4607 * to include the updated inode in the current transaction.
4609 * Also, dquot_alloc_block() will always dirty the inode when blocks
4610 * are allocated to the file.
4612 * If the inode is marked synchronous, we don't honour that here - doing
4613 * so would cause a commit on atime updates, which we don't bother doing.
4614 * We handle synchronous inodes at the highest possible level.
4616 void ext4_dirty_inode(struct inode *inode, int flags)
4620 handle = ext4_journal_start(inode, 2);
4624 ext4_mark_inode_dirty(handle, inode);
4626 ext4_journal_stop(handle);
4633 * Bind an inode's backing buffer_head into this transaction, to prevent
4634 * it from being flushed to disk early. Unlike
4635 * ext4_reserve_inode_write, this leaves behind no bh reference and
4636 * returns no iloc structure, so the caller needs to repeat the iloc
4637 * lookup to mark the inode dirty later.
4639 static int ext4_pin_inode(handle_t *handle, struct inode *inode)
4641 struct ext4_iloc iloc;
4645 err = ext4_get_inode_loc(inode, &iloc);
4647 BUFFER_TRACE(iloc.bh, "get_write_access");
4648 err = jbd2_journal_get_write_access(handle, iloc.bh);
4650 err = ext4_handle_dirty_metadata(handle,
4656 ext4_std_error(inode->i_sb, err);
4661 int ext4_change_inode_journal_flag(struct inode *inode, int val)
4668 * We have to be very careful here: changing a data block's
4669 * journaling status dynamically is dangerous. If we write a
4670 * data block to the journal, change the status and then delete
4671 * that block, we risk forgetting to revoke the old log record
4672 * from the journal and so a subsequent replay can corrupt data.
4673 * So, first we make sure that the journal is empty and that
4674 * nobody is changing anything.
4677 journal = EXT4_JOURNAL(inode);
4680 if (is_journal_aborted(journal))
4683 jbd2_journal_lock_updates(journal);
4684 jbd2_journal_flush(journal);
4687 * OK, there are no updates running now, and all cached data is
4688 * synced to disk. We are now in a completely consistent state
4689 * which doesn't have anything in the journal, and we know that
4690 * no filesystem updates are running, so it is safe to modify
4691 * the inode's in-core data-journaling state flag now.
4695 ext4_set_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
4697 ext4_clear_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
4698 ext4_set_aops(inode);
4700 jbd2_journal_unlock_updates(journal);
4702 /* Finally we can mark the inode as dirty. */
4704 handle = ext4_journal_start(inode, 1);
4706 return PTR_ERR(handle);
4708 err = ext4_mark_inode_dirty(handle, inode);
4709 ext4_handle_sync(handle);
4710 ext4_journal_stop(handle);
4711 ext4_std_error(inode->i_sb, err);
4716 static int ext4_bh_unmapped(handle_t *handle, struct buffer_head *bh)
4718 return !buffer_mapped(bh);
4721 int ext4_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
4723 struct page *page = vmf->page;
4727 struct file *file = vma->vm_file;
4728 struct inode *inode = file->f_path.dentry->d_inode;
4729 struct address_space *mapping = inode->i_mapping;
4731 get_block_t *get_block;
4735 * This check is racy but catches the common case. We rely on
4736 * __block_page_mkwrite() to do a reliable check.
4738 vfs_check_frozen(inode->i_sb, SB_FREEZE_WRITE);
4739 /* Delalloc case is easy... */
4740 if (test_opt(inode->i_sb, DELALLOC) &&
4741 !ext4_should_journal_data(inode) &&
4742 !ext4_nonda_switch(inode->i_sb)) {
4744 ret = __block_page_mkwrite(vma, vmf,
4745 ext4_da_get_block_prep);
4746 } while (ret == -ENOSPC &&
4747 ext4_should_retry_alloc(inode->i_sb, &retries));
4752 size = i_size_read(inode);
4753 /* Page got truncated from under us? */
4754 if (page->mapping != mapping || page_offset(page) > size) {
4756 ret = VM_FAULT_NOPAGE;
4760 if (page->index == size >> PAGE_CACHE_SHIFT)
4761 len = size & ~PAGE_CACHE_MASK;
4763 len = PAGE_CACHE_SIZE;
4765 * Return if we have all the buffers mapped. This avoids the need to do
4766 * journal_start/journal_stop which can block and take a long time
4768 if (page_has_buffers(page)) {
4769 if (!walk_page_buffers(NULL, page_buffers(page), 0, len, NULL,
4770 ext4_bh_unmapped)) {
4771 /* Wait so that we don't change page under IO */
4772 wait_on_page_writeback(page);
4773 ret = VM_FAULT_LOCKED;
4778 /* OK, we need to fill the hole... */
4779 if (ext4_should_dioread_nolock(inode))
4780 get_block = ext4_get_block_write;
4782 get_block = ext4_get_block;
4784 handle = ext4_journal_start(inode, ext4_writepage_trans_blocks(inode));
4785 if (IS_ERR(handle)) {
4786 ret = VM_FAULT_SIGBUS;
4789 ret = __block_page_mkwrite(vma, vmf, get_block);
4790 if (!ret && ext4_should_journal_data(inode)) {
4791 if (walk_page_buffers(handle, page_buffers(page), 0,
4792 PAGE_CACHE_SIZE, NULL, do_journal_get_write_access)) {
4794 ret = VM_FAULT_SIGBUS;
4795 ext4_journal_stop(handle);
4798 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
4800 ext4_journal_stop(handle);
4801 if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
4804 ret = block_page_mkwrite_return(ret);