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
22 #include <linux/time.h>
23 #include <linux/jbd2.h>
24 #include <linux/highuid.h>
25 #include <linux/pagemap.h>
26 #include <linux/quotaops.h>
27 #include <linux/string.h>
28 #include <linux/buffer_head.h>
29 #include <linux/writeback.h>
30 #include <linux/pagevec.h>
31 #include <linux/mpage.h>
32 #include <linux/namei.h>
33 #include <linux/uio.h>
34 #include <linux/bio.h>
35 #include <linux/workqueue.h>
36 #include <linux/kernel.h>
37 #include <linux/printk.h>
38 #include <linux/slab.h>
39 #include <linux/ratelimit.h>
40 #include <linux/aio.h>
42 #include "ext4_jbd2.h"
47 #include <trace/events/ext4.h>
49 #define MPAGE_DA_EXTENT_TAIL 0x01
51 static __u32 ext4_inode_csum(struct inode *inode, struct ext4_inode *raw,
52 struct ext4_inode_info *ei)
54 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
59 csum_lo = raw->i_checksum_lo;
60 raw->i_checksum_lo = 0;
61 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
62 EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi)) {
63 csum_hi = raw->i_checksum_hi;
64 raw->i_checksum_hi = 0;
67 csum = ext4_chksum(sbi, ei->i_csum_seed, (__u8 *)raw,
68 EXT4_INODE_SIZE(inode->i_sb));
70 raw->i_checksum_lo = csum_lo;
71 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
72 EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi))
73 raw->i_checksum_hi = csum_hi;
78 static int ext4_inode_csum_verify(struct inode *inode, struct ext4_inode *raw,
79 struct ext4_inode_info *ei)
81 __u32 provided, calculated;
83 if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
84 cpu_to_le32(EXT4_OS_LINUX) ||
85 !EXT4_HAS_RO_COMPAT_FEATURE(inode->i_sb,
86 EXT4_FEATURE_RO_COMPAT_METADATA_CSUM))
89 provided = le16_to_cpu(raw->i_checksum_lo);
90 calculated = ext4_inode_csum(inode, raw, ei);
91 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
92 EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi))
93 provided |= ((__u32)le16_to_cpu(raw->i_checksum_hi)) << 16;
97 return provided == calculated;
100 static void ext4_inode_csum_set(struct inode *inode, struct ext4_inode *raw,
101 struct ext4_inode_info *ei)
105 if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
106 cpu_to_le32(EXT4_OS_LINUX) ||
107 !EXT4_HAS_RO_COMPAT_FEATURE(inode->i_sb,
108 EXT4_FEATURE_RO_COMPAT_METADATA_CSUM))
111 csum = ext4_inode_csum(inode, raw, ei);
112 raw->i_checksum_lo = cpu_to_le16(csum & 0xFFFF);
113 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
114 EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi))
115 raw->i_checksum_hi = cpu_to_le16(csum >> 16);
118 static inline int ext4_begin_ordered_truncate(struct inode *inode,
121 trace_ext4_begin_ordered_truncate(inode, new_size);
123 * If jinode is zero, then we never opened the file for
124 * writing, so there's no need to call
125 * jbd2_journal_begin_ordered_truncate() since there's no
126 * outstanding writes we need to flush.
128 if (!EXT4_I(inode)->jinode)
130 return jbd2_journal_begin_ordered_truncate(EXT4_JOURNAL(inode),
131 EXT4_I(inode)->jinode,
135 static void ext4_invalidatepage(struct page *page, unsigned long offset);
136 static int __ext4_journalled_writepage(struct page *page, unsigned int len);
137 static int ext4_bh_delay_or_unwritten(handle_t *handle, struct buffer_head *bh);
138 static int ext4_discard_partial_page_buffers_no_lock(handle_t *handle,
139 struct inode *inode, struct page *page, loff_t from,
140 loff_t length, int flags);
143 * Test whether an inode is a fast symlink.
145 static int ext4_inode_is_fast_symlink(struct inode *inode)
147 int ea_blocks = EXT4_I(inode)->i_file_acl ?
148 (inode->i_sb->s_blocksize >> 9) : 0;
150 return (S_ISLNK(inode->i_mode) && inode->i_blocks - ea_blocks == 0);
154 * Restart the transaction associated with *handle. This does a commit,
155 * so before we call here everything must be consistently dirtied against
158 int ext4_truncate_restart_trans(handle_t *handle, struct inode *inode,
164 * Drop i_data_sem to avoid deadlock with ext4_map_blocks. At this
165 * moment, get_block can be called only for blocks inside i_size since
166 * page cache has been already dropped and writes are blocked by
167 * i_mutex. So we can safely drop the i_data_sem here.
169 BUG_ON(EXT4_JOURNAL(inode) == NULL);
170 jbd_debug(2, "restarting handle %p\n", handle);
171 up_write(&EXT4_I(inode)->i_data_sem);
172 ret = ext4_journal_restart(handle, nblocks);
173 down_write(&EXT4_I(inode)->i_data_sem);
174 ext4_discard_preallocations(inode);
180 * Called at the last iput() if i_nlink is zero.
182 void ext4_evict_inode(struct inode *inode)
187 trace_ext4_evict_inode(inode);
189 ext4_ioend_wait(inode);
191 if (inode->i_nlink) {
193 * When journalling data dirty buffers are tracked only in the
194 * journal. So although mm thinks everything is clean and
195 * ready for reaping the inode might still have some pages to
196 * write in the running transaction or waiting to be
197 * checkpointed. Thus calling jbd2_journal_invalidatepage()
198 * (via truncate_inode_pages()) to discard these buffers can
199 * cause data loss. Also even if we did not discard these
200 * buffers, we would have no way to find them after the inode
201 * is reaped and thus user could see stale data if he tries to
202 * read them before the transaction is checkpointed. So be
203 * careful and force everything to disk here... We use
204 * ei->i_datasync_tid to store the newest transaction
205 * containing inode's data.
207 * Note that directories do not have this problem because they
208 * don't use page cache.
210 if (ext4_should_journal_data(inode) &&
211 (S_ISLNK(inode->i_mode) || S_ISREG(inode->i_mode))) {
212 journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
213 tid_t commit_tid = EXT4_I(inode)->i_datasync_tid;
215 jbd2_log_start_commit(journal, commit_tid);
216 jbd2_log_wait_commit(journal, commit_tid);
217 filemap_write_and_wait(&inode->i_data);
219 truncate_inode_pages(&inode->i_data, 0);
223 if (!is_bad_inode(inode))
224 dquot_initialize(inode);
226 if (ext4_should_order_data(inode))
227 ext4_begin_ordered_truncate(inode, 0);
228 truncate_inode_pages(&inode->i_data, 0);
230 if (is_bad_inode(inode))
234 * Protect us against freezing - iput() caller didn't have to have any
235 * protection against it
237 sb_start_intwrite(inode->i_sb);
238 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE,
239 ext4_blocks_for_truncate(inode)+3);
240 if (IS_ERR(handle)) {
241 ext4_std_error(inode->i_sb, PTR_ERR(handle));
243 * If we're going to skip the normal cleanup, we still need to
244 * make sure that the in-core orphan linked list is properly
247 ext4_orphan_del(NULL, inode);
248 sb_end_intwrite(inode->i_sb);
253 ext4_handle_sync(handle);
255 err = ext4_mark_inode_dirty(handle, inode);
257 ext4_warning(inode->i_sb,
258 "couldn't mark inode dirty (err %d)", err);
262 ext4_truncate(inode);
265 * ext4_ext_truncate() doesn't reserve any slop when it
266 * restarts journal transactions; therefore there may not be
267 * enough credits left in the handle to remove the inode from
268 * the orphan list and set the dtime field.
270 if (!ext4_handle_has_enough_credits(handle, 3)) {
271 err = ext4_journal_extend(handle, 3);
273 err = ext4_journal_restart(handle, 3);
275 ext4_warning(inode->i_sb,
276 "couldn't extend journal (err %d)", err);
278 ext4_journal_stop(handle);
279 ext4_orphan_del(NULL, inode);
280 sb_end_intwrite(inode->i_sb);
286 * Kill off the orphan record which ext4_truncate created.
287 * AKPM: I think this can be inside the above `if'.
288 * Note that ext4_orphan_del() has to be able to cope with the
289 * deletion of a non-existent orphan - this is because we don't
290 * know if ext4_truncate() actually created an orphan record.
291 * (Well, we could do this if we need to, but heck - it works)
293 ext4_orphan_del(handle, inode);
294 EXT4_I(inode)->i_dtime = get_seconds();
297 * One subtle ordering requirement: if anything has gone wrong
298 * (transaction abort, IO errors, whatever), then we can still
299 * do these next steps (the fs will already have been marked as
300 * having errors), but we can't free the inode if the mark_dirty
303 if (ext4_mark_inode_dirty(handle, inode))
304 /* If that failed, just do the required in-core inode clear. */
305 ext4_clear_inode(inode);
307 ext4_free_inode(handle, inode);
308 ext4_journal_stop(handle);
309 sb_end_intwrite(inode->i_sb);
312 ext4_clear_inode(inode); /* We must guarantee clearing of inode... */
316 qsize_t *ext4_get_reserved_space(struct inode *inode)
318 return &EXT4_I(inode)->i_reserved_quota;
323 * Calculate the number of metadata blocks need to reserve
324 * to allocate a block located at @lblock
326 static int ext4_calc_metadata_amount(struct inode *inode, ext4_lblk_t lblock)
328 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
329 return ext4_ext_calc_metadata_amount(inode, lblock);
331 return ext4_ind_calc_metadata_amount(inode, lblock);
335 * Called with i_data_sem down, which is important since we can call
336 * ext4_discard_preallocations() from here.
338 void ext4_da_update_reserve_space(struct inode *inode,
339 int used, int quota_claim)
341 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
342 struct ext4_inode_info *ei = EXT4_I(inode);
344 spin_lock(&ei->i_block_reservation_lock);
345 trace_ext4_da_update_reserve_space(inode, used, quota_claim);
346 if (unlikely(used > ei->i_reserved_data_blocks)) {
347 ext4_warning(inode->i_sb, "%s: ino %lu, used %d "
348 "with only %d reserved data blocks",
349 __func__, inode->i_ino, used,
350 ei->i_reserved_data_blocks);
352 used = ei->i_reserved_data_blocks;
355 if (unlikely(ei->i_allocated_meta_blocks > ei->i_reserved_meta_blocks)) {
356 ext4_warning(inode->i_sb, "ino %lu, allocated %d "
357 "with only %d reserved metadata blocks "
358 "(releasing %d blocks with reserved %d data blocks)",
359 inode->i_ino, ei->i_allocated_meta_blocks,
360 ei->i_reserved_meta_blocks, used,
361 ei->i_reserved_data_blocks);
363 ei->i_allocated_meta_blocks = ei->i_reserved_meta_blocks;
366 /* Update per-inode reservations */
367 ei->i_reserved_data_blocks -= used;
368 ei->i_reserved_meta_blocks -= ei->i_allocated_meta_blocks;
369 percpu_counter_sub(&sbi->s_dirtyclusters_counter,
370 used + ei->i_allocated_meta_blocks);
371 ei->i_allocated_meta_blocks = 0;
373 if (ei->i_reserved_data_blocks == 0) {
375 * We can release all of the reserved metadata blocks
376 * only when we have written all of the delayed
379 percpu_counter_sub(&sbi->s_dirtyclusters_counter,
380 ei->i_reserved_meta_blocks);
381 ei->i_reserved_meta_blocks = 0;
382 ei->i_da_metadata_calc_len = 0;
384 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
386 /* Update quota subsystem for data blocks */
388 dquot_claim_block(inode, EXT4_C2B(sbi, used));
391 * We did fallocate with an offset that is already delayed
392 * allocated. So on delayed allocated writeback we should
393 * not re-claim the quota for fallocated blocks.
395 dquot_release_reservation_block(inode, EXT4_C2B(sbi, used));
399 * If we have done all the pending block allocations and if
400 * there aren't any writers on the inode, we can discard the
401 * inode's preallocations.
403 if ((ei->i_reserved_data_blocks == 0) &&
404 (atomic_read(&inode->i_writecount) == 0))
405 ext4_discard_preallocations(inode);
408 static int __check_block_validity(struct inode *inode, const char *func,
410 struct ext4_map_blocks *map)
412 if (!ext4_data_block_valid(EXT4_SB(inode->i_sb), map->m_pblk,
414 ext4_error_inode(inode, func, line, map->m_pblk,
415 "lblock %lu mapped to illegal pblock "
416 "(length %d)", (unsigned long) map->m_lblk,
423 #define check_block_validity(inode, map) \
424 __check_block_validity((inode), __func__, __LINE__, (map))
427 * Return the number of contiguous dirty pages in a given inode
428 * starting at page frame idx.
430 static pgoff_t ext4_num_dirty_pages(struct inode *inode, pgoff_t idx,
431 unsigned int max_pages)
433 struct address_space *mapping = inode->i_mapping;
437 int i, nr_pages, done = 0;
441 pagevec_init(&pvec, 0);
444 nr_pages = pagevec_lookup_tag(&pvec, mapping, &index,
446 (pgoff_t)PAGEVEC_SIZE);
449 for (i = 0; i < nr_pages; i++) {
450 struct page *page = pvec.pages[i];
451 struct buffer_head *bh, *head;
454 if (unlikely(page->mapping != mapping) ||
456 PageWriteback(page) ||
457 page->index != idx) {
462 if (page_has_buffers(page)) {
463 bh = head = page_buffers(page);
465 if (!buffer_delay(bh) &&
466 !buffer_unwritten(bh))
468 bh = bh->b_this_page;
469 } while (!done && (bh != head));
476 if (num >= max_pages) {
481 pagevec_release(&pvec);
487 * The ext4_map_blocks() function tries to look up the requested blocks,
488 * and returns if the blocks are already mapped.
490 * Otherwise it takes the write lock of the i_data_sem and allocate blocks
491 * and store the allocated blocks in the result buffer head and mark it
494 * If file type is extents based, it will call ext4_ext_map_blocks(),
495 * Otherwise, call with ext4_ind_map_blocks() to handle indirect mapping
498 * On success, it returns the number of blocks being mapped or allocate.
499 * if create==0 and the blocks are pre-allocated and uninitialized block,
500 * the result buffer head is unmapped. If the create ==1, it will make sure
501 * the buffer head is mapped.
503 * It returns 0 if plain look up failed (blocks have not been allocated), in
504 * that case, buffer head is unmapped
506 * It returns the error in case of allocation failure.
508 int ext4_map_blocks(handle_t *handle, struct inode *inode,
509 struct ext4_map_blocks *map, int flags)
511 struct extent_status es;
515 ext_debug("ext4_map_blocks(): inode %lu, flag %d, max_blocks %u,"
516 "logical block %lu\n", inode->i_ino, flags, map->m_len,
517 (unsigned long) map->m_lblk);
519 /* Lookup extent status tree firstly */
520 if (ext4_es_lookup_extent(inode, map->m_lblk, &es)) {
521 if (ext4_es_is_written(&es) || ext4_es_is_unwritten(&es)) {
522 map->m_pblk = ext4_es_pblock(&es) +
523 map->m_lblk - es.es_lblk;
524 map->m_flags |= ext4_es_is_written(&es) ?
525 EXT4_MAP_MAPPED : EXT4_MAP_UNWRITTEN;
526 retval = es.es_len - (map->m_lblk - es.es_lblk);
527 if (retval > map->m_len)
530 } else if (ext4_es_is_delayed(&es) || ext4_es_is_hole(&es)) {
539 * Try to see if we can get the block without requesting a new
542 if (!(flags & EXT4_GET_BLOCKS_NO_LOCK))
543 down_read((&EXT4_I(inode)->i_data_sem));
544 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
545 retval = ext4_ext_map_blocks(handle, inode, map, flags &
546 EXT4_GET_BLOCKS_KEEP_SIZE);
548 retval = ext4_ind_map_blocks(handle, inode, map, flags &
549 EXT4_GET_BLOCKS_KEEP_SIZE);
553 unsigned long long status;
555 status = map->m_flags & EXT4_MAP_UNWRITTEN ?
556 EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
557 if (!(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) &&
558 ext4_find_delalloc_range(inode, map->m_lblk,
559 map->m_lblk + map->m_len - 1))
560 status |= EXTENT_STATUS_DELAYED;
561 ret = ext4_es_insert_extent(inode, map->m_lblk,
562 map->m_len, map->m_pblk, status);
566 if (!(flags & EXT4_GET_BLOCKS_NO_LOCK))
567 up_read((&EXT4_I(inode)->i_data_sem));
570 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
571 int ret = check_block_validity(inode, map);
576 /* If it is only a block(s) look up */
577 if ((flags & EXT4_GET_BLOCKS_CREATE) == 0)
581 * Returns if the blocks have already allocated
583 * Note that if blocks have been preallocated
584 * ext4_ext_get_block() returns the create = 0
585 * with buffer head unmapped.
587 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED)
591 * Here we clear m_flags because after allocating an new extent,
592 * it will be set again.
594 map->m_flags &= ~EXT4_MAP_FLAGS;
597 * New blocks allocate and/or writing to uninitialized extent
598 * will possibly result in updating i_data, so we take
599 * the write lock of i_data_sem, and call get_blocks()
600 * with create == 1 flag.
602 down_write((&EXT4_I(inode)->i_data_sem));
605 * if the caller is from delayed allocation writeout path
606 * we have already reserved fs blocks for allocation
607 * let the underlying get_block() function know to
608 * avoid double accounting
610 if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
611 ext4_set_inode_state(inode, EXT4_STATE_DELALLOC_RESERVED);
613 * We need to check for EXT4 here because migrate
614 * could have changed the inode type in between
616 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
617 retval = ext4_ext_map_blocks(handle, inode, map, flags);
619 retval = ext4_ind_map_blocks(handle, inode, map, flags);
621 if (retval > 0 && map->m_flags & EXT4_MAP_NEW) {
623 * We allocated new blocks which will result in
624 * i_data's format changing. Force the migrate
625 * to fail by clearing migrate flags
627 ext4_clear_inode_state(inode, EXT4_STATE_EXT_MIGRATE);
631 * Update reserved blocks/metadata blocks after successful
632 * block allocation which had been deferred till now. We don't
633 * support fallocate for non extent files. So we can update
634 * reserve space here.
637 (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE))
638 ext4_da_update_reserve_space(inode, retval, 1);
640 if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
641 ext4_clear_inode_state(inode, EXT4_STATE_DELALLOC_RESERVED);
645 unsigned long long status;
647 status = map->m_flags & EXT4_MAP_UNWRITTEN ?
648 EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
649 if (!(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) &&
650 ext4_find_delalloc_range(inode, map->m_lblk,
651 map->m_lblk + map->m_len - 1))
652 status |= EXTENT_STATUS_DELAYED;
653 ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
654 map->m_pblk, status);
659 up_write((&EXT4_I(inode)->i_data_sem));
660 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
661 int ret = check_block_validity(inode, map);
668 /* Maximum number of blocks we map for direct IO at once. */
669 #define DIO_MAX_BLOCKS 4096
671 static int _ext4_get_block(struct inode *inode, sector_t iblock,
672 struct buffer_head *bh, int flags)
674 handle_t *handle = ext4_journal_current_handle();
675 struct ext4_map_blocks map;
676 int ret = 0, started = 0;
679 if (ext4_has_inline_data(inode))
683 map.m_len = bh->b_size >> inode->i_blkbits;
685 if (flags && !(flags & EXT4_GET_BLOCKS_NO_LOCK) && !handle) {
686 /* Direct IO write... */
687 if (map.m_len > DIO_MAX_BLOCKS)
688 map.m_len = DIO_MAX_BLOCKS;
689 dio_credits = ext4_chunk_trans_blocks(inode, map.m_len);
690 handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS,
692 if (IS_ERR(handle)) {
693 ret = PTR_ERR(handle);
699 ret = ext4_map_blocks(handle, inode, &map, flags);
701 map_bh(bh, inode->i_sb, map.m_pblk);
702 bh->b_state = (bh->b_state & ~EXT4_MAP_FLAGS) | map.m_flags;
703 bh->b_size = inode->i_sb->s_blocksize * map.m_len;
707 ext4_journal_stop(handle);
711 int ext4_get_block(struct inode *inode, sector_t iblock,
712 struct buffer_head *bh, int create)
714 return _ext4_get_block(inode, iblock, bh,
715 create ? EXT4_GET_BLOCKS_CREATE : 0);
719 * `handle' can be NULL if create is zero
721 struct buffer_head *ext4_getblk(handle_t *handle, struct inode *inode,
722 ext4_lblk_t block, int create, int *errp)
724 struct ext4_map_blocks map;
725 struct buffer_head *bh;
728 J_ASSERT(handle != NULL || create == 0);
732 err = ext4_map_blocks(handle, inode, &map,
733 create ? EXT4_GET_BLOCKS_CREATE : 0);
735 /* ensure we send some value back into *errp */
738 if (create && err == 0)
739 err = -ENOSPC; /* should never happen */
745 bh = sb_getblk(inode->i_sb, map.m_pblk);
750 if (map.m_flags & EXT4_MAP_NEW) {
751 J_ASSERT(create != 0);
752 J_ASSERT(handle != NULL);
755 * Now that we do not always journal data, we should
756 * keep in mind whether this should always journal the
757 * new buffer as metadata. For now, regular file
758 * writes use ext4_get_block instead, so it's not a
762 BUFFER_TRACE(bh, "call get_create_access");
763 fatal = ext4_journal_get_create_access(handle, bh);
764 if (!fatal && !buffer_uptodate(bh)) {
765 memset(bh->b_data, 0, inode->i_sb->s_blocksize);
766 set_buffer_uptodate(bh);
769 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
770 err = ext4_handle_dirty_metadata(handle, inode, bh);
774 BUFFER_TRACE(bh, "not a new buffer");
784 struct buffer_head *ext4_bread(handle_t *handle, struct inode *inode,
785 ext4_lblk_t block, int create, int *err)
787 struct buffer_head *bh;
789 bh = ext4_getblk(handle, inode, block, create, err);
792 if (buffer_uptodate(bh))
794 ll_rw_block(READ | REQ_META | REQ_PRIO, 1, &bh);
796 if (buffer_uptodate(bh))
803 int ext4_walk_page_buffers(handle_t *handle,
804 struct buffer_head *head,
808 int (*fn)(handle_t *handle,
809 struct buffer_head *bh))
811 struct buffer_head *bh;
812 unsigned block_start, block_end;
813 unsigned blocksize = head->b_size;
815 struct buffer_head *next;
817 for (bh = head, block_start = 0;
818 ret == 0 && (bh != head || !block_start);
819 block_start = block_end, bh = next) {
820 next = bh->b_this_page;
821 block_end = block_start + blocksize;
822 if (block_end <= from || block_start >= to) {
823 if (partial && !buffer_uptodate(bh))
827 err = (*fn)(handle, bh);
835 * To preserve ordering, it is essential that the hole instantiation and
836 * the data write be encapsulated in a single transaction. We cannot
837 * close off a transaction and start a new one between the ext4_get_block()
838 * and the commit_write(). So doing the jbd2_journal_start at the start of
839 * prepare_write() is the right place.
841 * Also, this function can nest inside ext4_writepage(). In that case, we
842 * *know* that ext4_writepage() has generated enough buffer credits to do the
843 * whole page. So we won't block on the journal in that case, which is good,
844 * because the caller may be PF_MEMALLOC.
846 * By accident, ext4 can be reentered when a transaction is open via
847 * quota file writes. If we were to commit the transaction while thus
848 * reentered, there can be a deadlock - we would be holding a quota
849 * lock, and the commit would never complete if another thread had a
850 * transaction open and was blocking on the quota lock - a ranking
853 * So what we do is to rely on the fact that jbd2_journal_stop/journal_start
854 * will _not_ run commit under these circumstances because handle->h_ref
855 * is elevated. We'll still have enough credits for the tiny quotafile
858 int do_journal_get_write_access(handle_t *handle,
859 struct buffer_head *bh)
861 int dirty = buffer_dirty(bh);
864 if (!buffer_mapped(bh) || buffer_freed(bh))
867 * __block_write_begin() could have dirtied some buffers. Clean
868 * the dirty bit as jbd2_journal_get_write_access() could complain
869 * otherwise about fs integrity issues. Setting of the dirty bit
870 * by __block_write_begin() isn't a real problem here as we clear
871 * the bit before releasing a page lock and thus writeback cannot
872 * ever write the buffer.
875 clear_buffer_dirty(bh);
876 ret = ext4_journal_get_write_access(handle, bh);
878 ret = ext4_handle_dirty_metadata(handle, NULL, bh);
882 static int ext4_get_block_write_nolock(struct inode *inode, sector_t iblock,
883 struct buffer_head *bh_result, int create);
884 static int ext4_write_begin(struct file *file, struct address_space *mapping,
885 loff_t pos, unsigned len, unsigned flags,
886 struct page **pagep, void **fsdata)
888 struct inode *inode = mapping->host;
889 int ret, needed_blocks;
896 trace_ext4_write_begin(inode, pos, len, flags);
898 * Reserve one block more for addition to orphan list in case
899 * we allocate blocks but write fails for some reason
901 needed_blocks = ext4_writepage_trans_blocks(inode) + 1;
902 index = pos >> PAGE_CACHE_SHIFT;
903 from = pos & (PAGE_CACHE_SIZE - 1);
906 if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
907 ret = ext4_try_to_write_inline_data(mapping, inode, pos, len,
916 * grab_cache_page_write_begin() can take a long time if the
917 * system is thrashing due to memory pressure, or if the page
918 * is being written back. So grab it first before we start
919 * the transaction handle. This also allows us to allocate
920 * the page (if needed) without using GFP_NOFS.
923 page = grab_cache_page_write_begin(mapping, index, flags);
929 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE, needed_blocks);
930 if (IS_ERR(handle)) {
931 page_cache_release(page);
932 return PTR_ERR(handle);
936 if (page->mapping != mapping) {
937 /* The page got truncated from under us */
939 page_cache_release(page);
940 ext4_journal_stop(handle);
943 wait_on_page_writeback(page);
945 if (ext4_should_dioread_nolock(inode))
946 ret = __block_write_begin(page, pos, len, ext4_get_block_write);
948 ret = __block_write_begin(page, pos, len, ext4_get_block);
950 if (!ret && ext4_should_journal_data(inode)) {
951 ret = ext4_walk_page_buffers(handle, page_buffers(page),
953 do_journal_get_write_access);
959 * __block_write_begin may have instantiated a few blocks
960 * outside i_size. Trim these off again. Don't need
961 * i_size_read because we hold i_mutex.
963 * Add inode to orphan list in case we crash before
966 if (pos + len > inode->i_size && ext4_can_truncate(inode))
967 ext4_orphan_add(handle, inode);
969 ext4_journal_stop(handle);
970 if (pos + len > inode->i_size) {
971 ext4_truncate_failed_write(inode);
973 * If truncate failed early the inode might
974 * still be on the orphan list; we need to
975 * make sure the inode is removed from the
976 * orphan list in that case.
979 ext4_orphan_del(NULL, inode);
982 if (ret == -ENOSPC &&
983 ext4_should_retry_alloc(inode->i_sb, &retries))
985 page_cache_release(page);
992 /* For write_end() in data=journal mode */
993 static int write_end_fn(handle_t *handle, struct buffer_head *bh)
995 if (!buffer_mapped(bh) || buffer_freed(bh))
997 set_buffer_uptodate(bh);
998 return ext4_handle_dirty_metadata(handle, NULL, bh);
1001 static int ext4_generic_write_end(struct file *file,
1002 struct address_space *mapping,
1003 loff_t pos, unsigned len, unsigned copied,
1004 struct page *page, void *fsdata)
1006 int i_size_changed = 0;
1007 struct inode *inode = mapping->host;
1008 handle_t *handle = ext4_journal_current_handle();
1010 if (ext4_has_inline_data(inode))
1011 copied = ext4_write_inline_data_end(inode, pos, len,
1014 copied = block_write_end(file, mapping, pos,
1015 len, copied, page, fsdata);
1018 * No need to use i_size_read() here, the i_size
1019 * cannot change under us because we hold i_mutex.
1021 * But it's important to update i_size while still holding page lock:
1022 * page writeout could otherwise come in and zero beyond i_size.
1024 if (pos + copied > inode->i_size) {
1025 i_size_write(inode, pos + copied);
1029 if (pos + copied > EXT4_I(inode)->i_disksize) {
1030 /* We need to mark inode dirty even if
1031 * new_i_size is less that inode->i_size
1032 * bu greater than i_disksize.(hint delalloc)
1034 ext4_update_i_disksize(inode, (pos + copied));
1038 page_cache_release(page);
1041 * Don't mark the inode dirty under page lock. First, it unnecessarily
1042 * makes the holding time of page lock longer. Second, it forces lock
1043 * ordering of page lock and transaction start for journaling
1047 ext4_mark_inode_dirty(handle, inode);
1053 * We need to pick up the new inode size which generic_commit_write gave us
1054 * `file' can be NULL - eg, when called from page_symlink().
1056 * ext4 never places buffers on inode->i_mapping->private_list. metadata
1057 * buffers are managed internally.
1059 static int ext4_ordered_write_end(struct file *file,
1060 struct address_space *mapping,
1061 loff_t pos, unsigned len, unsigned copied,
1062 struct page *page, void *fsdata)
1064 handle_t *handle = ext4_journal_current_handle();
1065 struct inode *inode = mapping->host;
1068 trace_ext4_ordered_write_end(inode, pos, len, copied);
1069 ret = ext4_jbd2_file_inode(handle, inode);
1072 ret2 = ext4_generic_write_end(file, mapping, pos, len, copied,
1075 if (pos + len > inode->i_size && ext4_can_truncate(inode))
1076 /* if we have allocated more blocks and copied
1077 * less. We will have blocks allocated outside
1078 * inode->i_size. So truncate them
1080 ext4_orphan_add(handle, inode);
1085 page_cache_release(page);
1088 ret2 = ext4_journal_stop(handle);
1092 if (pos + len > inode->i_size) {
1093 ext4_truncate_failed_write(inode);
1095 * If truncate failed early the inode might still be
1096 * on the orphan list; we need to make sure the inode
1097 * is removed from the orphan list in that case.
1100 ext4_orphan_del(NULL, inode);
1104 return ret ? ret : copied;
1107 static int ext4_writeback_write_end(struct file *file,
1108 struct address_space *mapping,
1109 loff_t pos, unsigned len, unsigned copied,
1110 struct page *page, void *fsdata)
1112 handle_t *handle = ext4_journal_current_handle();
1113 struct inode *inode = mapping->host;
1116 trace_ext4_writeback_write_end(inode, pos, len, copied);
1117 ret2 = ext4_generic_write_end(file, mapping, pos, len, copied,
1120 if (pos + len > inode->i_size && ext4_can_truncate(inode))
1121 /* if we have allocated more blocks and copied
1122 * less. We will have blocks allocated outside
1123 * inode->i_size. So truncate them
1125 ext4_orphan_add(handle, inode);
1130 ret2 = ext4_journal_stop(handle);
1134 if (pos + len > inode->i_size) {
1135 ext4_truncate_failed_write(inode);
1137 * If truncate failed early the inode might still be
1138 * on the orphan list; we need to make sure the inode
1139 * is removed from the orphan list in that case.
1142 ext4_orphan_del(NULL, inode);
1145 return ret ? ret : copied;
1148 static int ext4_journalled_write_end(struct file *file,
1149 struct address_space *mapping,
1150 loff_t pos, unsigned len, unsigned copied,
1151 struct page *page, void *fsdata)
1153 handle_t *handle = ext4_journal_current_handle();
1154 struct inode *inode = mapping->host;
1160 trace_ext4_journalled_write_end(inode, pos, len, copied);
1161 from = pos & (PAGE_CACHE_SIZE - 1);
1164 BUG_ON(!ext4_handle_valid(handle));
1166 if (ext4_has_inline_data(inode))
1167 copied = ext4_write_inline_data_end(inode, pos, len,
1171 if (!PageUptodate(page))
1173 page_zero_new_buffers(page, from+copied, to);
1176 ret = ext4_walk_page_buffers(handle, page_buffers(page), from,
1177 to, &partial, write_end_fn);
1179 SetPageUptodate(page);
1181 new_i_size = pos + copied;
1182 if (new_i_size > inode->i_size)
1183 i_size_write(inode, pos+copied);
1184 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
1185 EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
1186 if (new_i_size > EXT4_I(inode)->i_disksize) {
1187 ext4_update_i_disksize(inode, new_i_size);
1188 ret2 = ext4_mark_inode_dirty(handle, inode);
1194 page_cache_release(page);
1195 if (pos + len > inode->i_size && ext4_can_truncate(inode))
1196 /* if we have allocated more blocks and copied
1197 * less. We will have blocks allocated outside
1198 * inode->i_size. So truncate them
1200 ext4_orphan_add(handle, inode);
1202 ret2 = ext4_journal_stop(handle);
1205 if (pos + len > inode->i_size) {
1206 ext4_truncate_failed_write(inode);
1208 * If truncate failed early the inode might still be
1209 * on the orphan list; we need to make sure the inode
1210 * is removed from the orphan list in that case.
1213 ext4_orphan_del(NULL, inode);
1216 return ret ? ret : copied;
1220 * Reserve a single cluster located at lblock
1222 static int ext4_da_reserve_space(struct inode *inode, ext4_lblk_t lblock)
1225 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1226 struct ext4_inode_info *ei = EXT4_I(inode);
1227 unsigned int md_needed;
1229 ext4_lblk_t save_last_lblock;
1233 * We will charge metadata quota at writeout time; this saves
1234 * us from metadata over-estimation, though we may go over by
1235 * a small amount in the end. Here we just reserve for data.
1237 ret = dquot_reserve_block(inode, EXT4_C2B(sbi, 1));
1242 * recalculate the amount of metadata blocks to reserve
1243 * in order to allocate nrblocks
1244 * worse case is one extent per block
1247 spin_lock(&ei->i_block_reservation_lock);
1249 * ext4_calc_metadata_amount() has side effects, which we have
1250 * to be prepared undo if we fail to claim space.
1252 save_len = ei->i_da_metadata_calc_len;
1253 save_last_lblock = ei->i_da_metadata_calc_last_lblock;
1254 md_needed = EXT4_NUM_B2C(sbi,
1255 ext4_calc_metadata_amount(inode, lblock));
1256 trace_ext4_da_reserve_space(inode, md_needed);
1259 * We do still charge estimated metadata to the sb though;
1260 * we cannot afford to run out of free blocks.
1262 if (ext4_claim_free_clusters(sbi, md_needed + 1, 0)) {
1263 ei->i_da_metadata_calc_len = save_len;
1264 ei->i_da_metadata_calc_last_lblock = save_last_lblock;
1265 spin_unlock(&ei->i_block_reservation_lock);
1266 if (ext4_should_retry_alloc(inode->i_sb, &retries)) {
1270 dquot_release_reservation_block(inode, EXT4_C2B(sbi, 1));
1273 ei->i_reserved_data_blocks++;
1274 ei->i_reserved_meta_blocks += md_needed;
1275 spin_unlock(&ei->i_block_reservation_lock);
1277 return 0; /* success */
1280 static void ext4_da_release_space(struct inode *inode, int to_free)
1282 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1283 struct ext4_inode_info *ei = EXT4_I(inode);
1286 return; /* Nothing to release, exit */
1288 spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
1290 trace_ext4_da_release_space(inode, to_free);
1291 if (unlikely(to_free > ei->i_reserved_data_blocks)) {
1293 * if there aren't enough reserved blocks, then the
1294 * counter is messed up somewhere. Since this
1295 * function is called from invalidate page, it's
1296 * harmless to return without any action.
1298 ext4_warning(inode->i_sb, "ext4_da_release_space: "
1299 "ino %lu, to_free %d with only %d reserved "
1300 "data blocks", inode->i_ino, to_free,
1301 ei->i_reserved_data_blocks);
1303 to_free = ei->i_reserved_data_blocks;
1305 ei->i_reserved_data_blocks -= to_free;
1307 if (ei->i_reserved_data_blocks == 0) {
1309 * We can release all of the reserved metadata blocks
1310 * only when we have written all of the delayed
1311 * allocation blocks.
1312 * Note that in case of bigalloc, i_reserved_meta_blocks,
1313 * i_reserved_data_blocks, etc. refer to number of clusters.
1315 percpu_counter_sub(&sbi->s_dirtyclusters_counter,
1316 ei->i_reserved_meta_blocks);
1317 ei->i_reserved_meta_blocks = 0;
1318 ei->i_da_metadata_calc_len = 0;
1321 /* update fs dirty data blocks counter */
1322 percpu_counter_sub(&sbi->s_dirtyclusters_counter, to_free);
1324 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
1326 dquot_release_reservation_block(inode, EXT4_C2B(sbi, to_free));
1329 static void ext4_da_page_release_reservation(struct page *page,
1330 unsigned long offset)
1333 struct buffer_head *head, *bh;
1334 unsigned int curr_off = 0;
1335 struct inode *inode = page->mapping->host;
1336 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1340 head = page_buffers(page);
1343 unsigned int next_off = curr_off + bh->b_size;
1345 if ((offset <= curr_off) && (buffer_delay(bh))) {
1347 clear_buffer_delay(bh);
1349 curr_off = next_off;
1350 } while ((bh = bh->b_this_page) != head);
1353 lblk = page->index << (PAGE_CACHE_SHIFT - inode->i_blkbits);
1354 ext4_es_remove_extent(inode, lblk, to_release);
1357 /* If we have released all the blocks belonging to a cluster, then we
1358 * need to release the reserved space for that cluster. */
1359 num_clusters = EXT4_NUM_B2C(sbi, to_release);
1360 while (num_clusters > 0) {
1361 lblk = (page->index << (PAGE_CACHE_SHIFT - inode->i_blkbits)) +
1362 ((num_clusters - 1) << sbi->s_cluster_bits);
1363 if (sbi->s_cluster_ratio == 1 ||
1364 !ext4_find_delalloc_cluster(inode, lblk))
1365 ext4_da_release_space(inode, 1);
1372 * Delayed allocation stuff
1376 * mpage_da_submit_io - walks through extent of pages and try to write
1377 * them with writepage() call back
1379 * @mpd->inode: inode
1380 * @mpd->first_page: first page of the extent
1381 * @mpd->next_page: page after the last page of the extent
1383 * By the time mpage_da_submit_io() is called we expect all blocks
1384 * to be allocated. this may be wrong if allocation failed.
1386 * As pages are already locked by write_cache_pages(), we can't use it
1388 static int mpage_da_submit_io(struct mpage_da_data *mpd,
1389 struct ext4_map_blocks *map)
1391 struct pagevec pvec;
1392 unsigned long index, end;
1393 int ret = 0, err, nr_pages, i;
1394 struct inode *inode = mpd->inode;
1395 struct address_space *mapping = inode->i_mapping;
1396 loff_t size = i_size_read(inode);
1397 unsigned int len, block_start;
1398 struct buffer_head *bh, *page_bufs = NULL;
1399 sector_t pblock = 0, cur_logical = 0;
1400 struct ext4_io_submit io_submit;
1402 BUG_ON(mpd->next_page <= mpd->first_page);
1403 memset(&io_submit, 0, sizeof(io_submit));
1405 * We need to start from the first_page to the next_page - 1
1406 * to make sure we also write the mapped dirty buffer_heads.
1407 * If we look at mpd->b_blocknr we would only be looking
1408 * at the currently mapped buffer_heads.
1410 index = mpd->first_page;
1411 end = mpd->next_page - 1;
1413 pagevec_init(&pvec, 0);
1414 while (index <= end) {
1415 nr_pages = pagevec_lookup(&pvec, mapping, index, PAGEVEC_SIZE);
1418 for (i = 0; i < nr_pages; i++) {
1420 struct page *page = pvec.pages[i];
1422 index = page->index;
1426 if (index == size >> PAGE_CACHE_SHIFT)
1427 len = size & ~PAGE_CACHE_MASK;
1429 len = PAGE_CACHE_SIZE;
1431 cur_logical = index << (PAGE_CACHE_SHIFT -
1433 pblock = map->m_pblk + (cur_logical -
1438 BUG_ON(!PageLocked(page));
1439 BUG_ON(PageWriteback(page));
1441 bh = page_bufs = page_buffers(page);
1444 if (map && (cur_logical >= map->m_lblk) &&
1445 (cur_logical <= (map->m_lblk +
1446 (map->m_len - 1)))) {
1447 if (buffer_delay(bh)) {
1448 clear_buffer_delay(bh);
1449 bh->b_blocknr = pblock;
1451 if (buffer_unwritten(bh) ||
1453 BUG_ON(bh->b_blocknr != pblock);
1454 if (map->m_flags & EXT4_MAP_UNINIT)
1455 set_buffer_uninit(bh);
1456 clear_buffer_unwritten(bh);
1460 * skip page if block allocation undone and
1463 if (ext4_bh_delay_or_unwritten(NULL, bh))
1465 bh = bh->b_this_page;
1466 block_start += bh->b_size;
1469 } while (bh != page_bufs);
1476 clear_page_dirty_for_io(page);
1477 err = ext4_bio_write_page(&io_submit, page, len,
1480 mpd->pages_written++;
1482 * In error case, we have to continue because
1483 * remaining pages are still locked
1488 pagevec_release(&pvec);
1490 ext4_io_submit(&io_submit);
1494 static void ext4_da_block_invalidatepages(struct mpage_da_data *mpd)
1498 struct pagevec pvec;
1499 struct inode *inode = mpd->inode;
1500 struct address_space *mapping = inode->i_mapping;
1501 ext4_lblk_t start, last;
1503 index = mpd->first_page;
1504 end = mpd->next_page - 1;
1506 start = index << (PAGE_CACHE_SHIFT - inode->i_blkbits);
1507 last = end << (PAGE_CACHE_SHIFT - inode->i_blkbits);
1508 ext4_es_remove_extent(inode, start, last - start + 1);
1510 pagevec_init(&pvec, 0);
1511 while (index <= end) {
1512 nr_pages = pagevec_lookup(&pvec, mapping, index, PAGEVEC_SIZE);
1515 for (i = 0; i < nr_pages; i++) {
1516 struct page *page = pvec.pages[i];
1517 if (page->index > end)
1519 BUG_ON(!PageLocked(page));
1520 BUG_ON(PageWriteback(page));
1521 block_invalidatepage(page, 0);
1522 ClearPageUptodate(page);
1525 index = pvec.pages[nr_pages - 1]->index + 1;
1526 pagevec_release(&pvec);
1531 static void ext4_print_free_blocks(struct inode *inode)
1533 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1534 struct super_block *sb = inode->i_sb;
1536 ext4_msg(sb, KERN_CRIT, "Total free blocks count %lld",
1537 EXT4_C2B(EXT4_SB(inode->i_sb),
1538 ext4_count_free_clusters(inode->i_sb)));
1539 ext4_msg(sb, KERN_CRIT, "Free/Dirty block details");
1540 ext4_msg(sb, KERN_CRIT, "free_blocks=%lld",
1541 (long long) EXT4_C2B(EXT4_SB(inode->i_sb),
1542 percpu_counter_sum(&sbi->s_freeclusters_counter)));
1543 ext4_msg(sb, KERN_CRIT, "dirty_blocks=%lld",
1544 (long long) EXT4_C2B(EXT4_SB(inode->i_sb),
1545 percpu_counter_sum(&sbi->s_dirtyclusters_counter)));
1546 ext4_msg(sb, KERN_CRIT, "Block reservation details");
1547 ext4_msg(sb, KERN_CRIT, "i_reserved_data_blocks=%u",
1548 EXT4_I(inode)->i_reserved_data_blocks);
1549 ext4_msg(sb, KERN_CRIT, "i_reserved_meta_blocks=%u",
1550 EXT4_I(inode)->i_reserved_meta_blocks);
1555 * mpage_da_map_and_submit - go through given space, map them
1556 * if necessary, and then submit them for I/O
1558 * @mpd - bh describing space
1560 * The function skips space we know is already mapped to disk blocks.
1563 static void mpage_da_map_and_submit(struct mpage_da_data *mpd)
1565 int err, blks, get_blocks_flags;
1566 struct ext4_map_blocks map, *mapp = NULL;
1567 sector_t next = mpd->b_blocknr;
1568 unsigned max_blocks = mpd->b_size >> mpd->inode->i_blkbits;
1569 loff_t disksize = EXT4_I(mpd->inode)->i_disksize;
1570 handle_t *handle = NULL;
1573 * If the blocks are mapped already, or we couldn't accumulate
1574 * any blocks, then proceed immediately to the submission stage.
1576 if ((mpd->b_size == 0) ||
1577 ((mpd->b_state & (1 << BH_Mapped)) &&
1578 !(mpd->b_state & (1 << BH_Delay)) &&
1579 !(mpd->b_state & (1 << BH_Unwritten))))
1582 handle = ext4_journal_current_handle();
1586 * Call ext4_map_blocks() to allocate any delayed allocation
1587 * blocks, or to convert an uninitialized extent to be
1588 * initialized (in the case where we have written into
1589 * one or more preallocated blocks).
1591 * We pass in the magic EXT4_GET_BLOCKS_DELALLOC_RESERVE to
1592 * indicate that we are on the delayed allocation path. This
1593 * affects functions in many different parts of the allocation
1594 * call path. This flag exists primarily because we don't
1595 * want to change *many* call functions, so ext4_map_blocks()
1596 * will set the EXT4_STATE_DELALLOC_RESERVED flag once the
1597 * inode's allocation semaphore is taken.
1599 * If the blocks in questions were delalloc blocks, set
1600 * EXT4_GET_BLOCKS_DELALLOC_RESERVE so the delalloc accounting
1601 * variables are updated after the blocks have been allocated.
1604 map.m_len = max_blocks;
1605 get_blocks_flags = EXT4_GET_BLOCKS_CREATE;
1606 if (ext4_should_dioread_nolock(mpd->inode))
1607 get_blocks_flags |= EXT4_GET_BLOCKS_IO_CREATE_EXT;
1608 if (mpd->b_state & (1 << BH_Delay))
1609 get_blocks_flags |= EXT4_GET_BLOCKS_DELALLOC_RESERVE;
1611 blks = ext4_map_blocks(handle, mpd->inode, &map, get_blocks_flags);
1613 struct super_block *sb = mpd->inode->i_sb;
1617 * If get block returns EAGAIN or ENOSPC and there
1618 * appears to be free blocks we will just let
1619 * mpage_da_submit_io() unlock all of the pages.
1624 if (err == -ENOSPC && ext4_count_free_clusters(sb)) {
1630 * get block failure will cause us to loop in
1631 * writepages, because a_ops->writepage won't be able
1632 * to make progress. The page will be redirtied by
1633 * writepage and writepages will again try to write
1636 if (!(EXT4_SB(sb)->s_mount_flags & EXT4_MF_FS_ABORTED)) {
1637 ext4_msg(sb, KERN_CRIT,
1638 "delayed block allocation failed for inode %lu "
1639 "at logical offset %llu with max blocks %zd "
1640 "with error %d", mpd->inode->i_ino,
1641 (unsigned long long) next,
1642 mpd->b_size >> mpd->inode->i_blkbits, err);
1643 ext4_msg(sb, KERN_CRIT,
1644 "This should not happen!! Data will be lost");
1646 ext4_print_free_blocks(mpd->inode);
1648 /* invalidate all the pages */
1649 ext4_da_block_invalidatepages(mpd);
1651 /* Mark this page range as having been completed */
1658 if (map.m_flags & EXT4_MAP_NEW) {
1659 struct block_device *bdev = mpd->inode->i_sb->s_bdev;
1662 for (i = 0; i < map.m_len; i++)
1663 unmap_underlying_metadata(bdev, map.m_pblk + i);
1667 * Update on-disk size along with block allocation.
1669 disksize = ((loff_t) next + blks) << mpd->inode->i_blkbits;
1670 if (disksize > i_size_read(mpd->inode))
1671 disksize = i_size_read(mpd->inode);
1672 if (disksize > EXT4_I(mpd->inode)->i_disksize) {
1673 ext4_update_i_disksize(mpd->inode, disksize);
1674 err = ext4_mark_inode_dirty(handle, mpd->inode);
1676 ext4_error(mpd->inode->i_sb,
1677 "Failed to mark inode %lu dirty",
1682 mpage_da_submit_io(mpd, mapp);
1686 #define BH_FLAGS ((1 << BH_Uptodate) | (1 << BH_Mapped) | \
1687 (1 << BH_Delay) | (1 << BH_Unwritten))
1690 * mpage_add_bh_to_extent - try to add one more block to extent of blocks
1692 * @mpd->lbh - extent of blocks
1693 * @logical - logical number of the block in the file
1694 * @b_state - b_state of the buffer head added
1696 * the function is used to collect contig. blocks in same state
1698 static void mpage_add_bh_to_extent(struct mpage_da_data *mpd, sector_t logical,
1699 unsigned long b_state)
1702 int blkbits = mpd->inode->i_blkbits;
1703 int nrblocks = mpd->b_size >> blkbits;
1706 * XXX Don't go larger than mballoc is willing to allocate
1707 * This is a stopgap solution. We eventually need to fold
1708 * mpage_da_submit_io() into this function and then call
1709 * ext4_map_blocks() multiple times in a loop
1711 if (nrblocks >= (8*1024*1024 >> blkbits))
1714 /* check if the reserved journal credits might overflow */
1715 if (!ext4_test_inode_flag(mpd->inode, EXT4_INODE_EXTENTS)) {
1716 if (nrblocks >= EXT4_MAX_TRANS_DATA) {
1718 * With non-extent format we are limited by the journal
1719 * credit available. Total credit needed to insert
1720 * nrblocks contiguous blocks is dependent on the
1721 * nrblocks. So limit nrblocks.
1727 * First block in the extent
1729 if (mpd->b_size == 0) {
1730 mpd->b_blocknr = logical;
1731 mpd->b_size = 1 << blkbits;
1732 mpd->b_state = b_state & BH_FLAGS;
1736 next = mpd->b_blocknr + nrblocks;
1738 * Can we merge the block to our big extent?
1740 if (logical == next && (b_state & BH_FLAGS) == mpd->b_state) {
1741 mpd->b_size += 1 << blkbits;
1747 * We couldn't merge the block to our extent, so we
1748 * need to flush current extent and start new one
1750 mpage_da_map_and_submit(mpd);
1754 static int ext4_bh_delay_or_unwritten(handle_t *handle, struct buffer_head *bh)
1756 return (buffer_delay(bh) || buffer_unwritten(bh)) && buffer_dirty(bh);
1760 * This function is grabs code from the very beginning of
1761 * ext4_map_blocks, but assumes that the caller is from delayed write
1762 * time. This function looks up the requested blocks and sets the
1763 * buffer delay bit under the protection of i_data_sem.
1765 static int ext4_da_map_blocks(struct inode *inode, sector_t iblock,
1766 struct ext4_map_blocks *map,
1767 struct buffer_head *bh)
1769 struct extent_status es;
1771 sector_t invalid_block = ~((sector_t) 0xffff);
1773 if (invalid_block < ext4_blocks_count(EXT4_SB(inode->i_sb)->s_es))
1777 ext_debug("ext4_da_map_blocks(): inode %lu, max_blocks %u,"
1778 "logical block %lu\n", inode->i_ino, map->m_len,
1779 (unsigned long) map->m_lblk);
1781 /* Lookup extent status tree firstly */
1782 if (ext4_es_lookup_extent(inode, iblock, &es)) {
1784 if (ext4_es_is_hole(&es)) {
1786 down_read((&EXT4_I(inode)->i_data_sem));
1791 * Delayed extent could be allocated by fallocate.
1792 * So we need to check it.
1794 if (ext4_es_is_delayed(&es) && !ext4_es_is_unwritten(&es)) {
1795 map_bh(bh, inode->i_sb, invalid_block);
1797 set_buffer_delay(bh);
1801 map->m_pblk = ext4_es_pblock(&es) + iblock - es.es_lblk;
1802 retval = es.es_len - (iblock - es.es_lblk);
1803 if (retval > map->m_len)
1804 retval = map->m_len;
1805 map->m_len = retval;
1806 if (ext4_es_is_written(&es))
1807 map->m_flags |= EXT4_MAP_MAPPED;
1808 else if (ext4_es_is_unwritten(&es))
1809 map->m_flags |= EXT4_MAP_UNWRITTEN;
1817 * Try to see if we can get the block without requesting a new
1818 * file system block.
1820 down_read((&EXT4_I(inode)->i_data_sem));
1821 if (ext4_has_inline_data(inode)) {
1823 * We will soon create blocks for this page, and let
1824 * us pretend as if the blocks aren't allocated yet.
1825 * In case of clusters, we have to handle the work
1826 * of mapping from cluster so that the reserved space
1827 * is calculated properly.
1829 if ((EXT4_SB(inode->i_sb)->s_cluster_ratio > 1) &&
1830 ext4_find_delalloc_cluster(inode, map->m_lblk))
1831 map->m_flags |= EXT4_MAP_FROM_CLUSTER;
1833 } else if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
1834 retval = ext4_ext_map_blocks(NULL, inode, map,
1835 EXT4_GET_BLOCKS_NO_PUT_HOLE);
1837 retval = ext4_ind_map_blocks(NULL, inode, map,
1838 EXT4_GET_BLOCKS_NO_PUT_HOLE);
1844 * XXX: __block_prepare_write() unmaps passed block,
1847 /* If the block was allocated from previously allocated cluster,
1848 * then we dont need to reserve it again. */
1849 if (!(map->m_flags & EXT4_MAP_FROM_CLUSTER)) {
1850 ret = ext4_da_reserve_space(inode, iblock);
1852 /* not enough space to reserve */
1858 ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
1859 ~0, EXTENT_STATUS_DELAYED);
1865 /* Clear EXT4_MAP_FROM_CLUSTER flag since its purpose is served
1866 * and it should not appear on the bh->b_state.
1868 map->m_flags &= ~EXT4_MAP_FROM_CLUSTER;
1870 map_bh(bh, inode->i_sb, invalid_block);
1872 set_buffer_delay(bh);
1873 } else if (retval > 0) {
1875 unsigned long long status;
1877 status = map->m_flags & EXT4_MAP_UNWRITTEN ?
1878 EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
1879 ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
1880 map->m_pblk, status);
1886 up_read((&EXT4_I(inode)->i_data_sem));
1892 * This is a special get_blocks_t callback which is used by
1893 * ext4_da_write_begin(). It will either return mapped block or
1894 * reserve space for a single block.
1896 * For delayed buffer_head we have BH_Mapped, BH_New, BH_Delay set.
1897 * We also have b_blocknr = -1 and b_bdev initialized properly
1899 * For unwritten buffer_head we have BH_Mapped, BH_New, BH_Unwritten set.
1900 * We also have b_blocknr = physicalblock mapping unwritten extent and b_bdev
1901 * initialized properly.
1903 int ext4_da_get_block_prep(struct inode *inode, sector_t iblock,
1904 struct buffer_head *bh, int create)
1906 struct ext4_map_blocks map;
1909 BUG_ON(create == 0);
1910 BUG_ON(bh->b_size != inode->i_sb->s_blocksize);
1912 map.m_lblk = iblock;
1916 * first, we need to know whether the block is allocated already
1917 * preallocated blocks are unmapped but should treated
1918 * the same as allocated blocks.
1920 ret = ext4_da_map_blocks(inode, iblock, &map, bh);
1924 map_bh(bh, inode->i_sb, map.m_pblk);
1925 bh->b_state = (bh->b_state & ~EXT4_MAP_FLAGS) | map.m_flags;
1927 if (buffer_unwritten(bh)) {
1928 /* A delayed write to unwritten bh should be marked
1929 * new and mapped. Mapped ensures that we don't do
1930 * get_block multiple times when we write to the same
1931 * offset and new ensures that we do proper zero out
1932 * for partial write.
1935 set_buffer_mapped(bh);
1940 static int bget_one(handle_t *handle, struct buffer_head *bh)
1946 static int bput_one(handle_t *handle, struct buffer_head *bh)
1952 static int __ext4_journalled_writepage(struct page *page,
1955 struct address_space *mapping = page->mapping;
1956 struct inode *inode = mapping->host;
1957 struct buffer_head *page_bufs = NULL;
1958 handle_t *handle = NULL;
1959 int ret = 0, err = 0;
1960 int inline_data = ext4_has_inline_data(inode);
1961 struct buffer_head *inode_bh = NULL;
1963 ClearPageChecked(page);
1966 BUG_ON(page->index != 0);
1967 BUG_ON(len > ext4_get_max_inline_size(inode));
1968 inode_bh = ext4_journalled_write_inline_data(inode, len, page);
1969 if (inode_bh == NULL)
1972 page_bufs = page_buffers(page);
1977 ext4_walk_page_buffers(handle, page_bufs, 0, len,
1980 /* As soon as we unlock the page, it can go away, but we have
1981 * references to buffers so we are safe */
1984 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
1985 ext4_writepage_trans_blocks(inode));
1986 if (IS_ERR(handle)) {
1987 ret = PTR_ERR(handle);
1991 BUG_ON(!ext4_handle_valid(handle));
1994 ret = ext4_journal_get_write_access(handle, inode_bh);
1996 err = ext4_handle_dirty_metadata(handle, inode, inode_bh);
1999 ret = ext4_walk_page_buffers(handle, page_bufs, 0, len, NULL,
2000 do_journal_get_write_access);
2002 err = ext4_walk_page_buffers(handle, page_bufs, 0, len, NULL,
2007 EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
2008 err = ext4_journal_stop(handle);
2012 if (!ext4_has_inline_data(inode))
2013 ext4_walk_page_buffers(handle, page_bufs, 0, len,
2015 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
2022 * Note that we don't need to start a transaction unless we're journaling data
2023 * because we should have holes filled from ext4_page_mkwrite(). We even don't
2024 * need to file the inode to the transaction's list in ordered mode because if
2025 * we are writing back data added by write(), the inode is already there and if
2026 * we are writing back data modified via mmap(), no one guarantees in which
2027 * transaction the data will hit the disk. In case we are journaling data, we
2028 * cannot start transaction directly because transaction start ranks above page
2029 * lock so we have to do some magic.
2031 * This function can get called via...
2032 * - ext4_da_writepages after taking page lock (have journal handle)
2033 * - journal_submit_inode_data_buffers (no journal handle)
2034 * - shrink_page_list via the kswapd/direct reclaim (no journal handle)
2035 * - grab_page_cache when doing write_begin (have journal handle)
2037 * We don't do any block allocation in this function. If we have page with
2038 * multiple blocks we need to write those buffer_heads that are mapped. This
2039 * is important for mmaped based write. So if we do with blocksize 1K
2040 * truncate(f, 1024);
2041 * a = mmap(f, 0, 4096);
2043 * truncate(f, 4096);
2044 * we have in the page first buffer_head mapped via page_mkwrite call back
2045 * but other buffer_heads would be unmapped but dirty (dirty done via the
2046 * do_wp_page). So writepage should write the first block. If we modify
2047 * the mmap area beyond 1024 we will again get a page_fault and the
2048 * page_mkwrite callback will do the block allocation and mark the
2049 * buffer_heads mapped.
2051 * We redirty the page if we have any buffer_heads that is either delay or
2052 * unwritten in the page.
2054 * We can get recursively called as show below.
2056 * ext4_writepage() -> kmalloc() -> __alloc_pages() -> page_launder() ->
2059 * But since we don't do any block allocation we should not deadlock.
2060 * Page also have the dirty flag cleared so we don't get recurive page_lock.
2062 static int ext4_writepage(struct page *page,
2063 struct writeback_control *wbc)
2068 struct buffer_head *page_bufs = NULL;
2069 struct inode *inode = page->mapping->host;
2070 struct ext4_io_submit io_submit;
2072 trace_ext4_writepage(page);
2073 size = i_size_read(inode);
2074 if (page->index == size >> PAGE_CACHE_SHIFT)
2075 len = size & ~PAGE_CACHE_MASK;
2077 len = PAGE_CACHE_SIZE;
2079 page_bufs = page_buffers(page);
2081 * We cannot do block allocation or other extent handling in this
2082 * function. If there are buffers needing that, we have to redirty
2083 * the page. But we may reach here when we do a journal commit via
2084 * journal_submit_inode_data_buffers() and in that case we must write
2085 * allocated buffers to achieve data=ordered mode guarantees.
2087 if (ext4_walk_page_buffers(NULL, page_bufs, 0, len, NULL,
2088 ext4_bh_delay_or_unwritten)) {
2089 redirty_page_for_writepage(wbc, page);
2090 if (current->flags & PF_MEMALLOC) {
2092 * For memory cleaning there's no point in writing only
2093 * some buffers. So just bail out. Warn if we came here
2094 * from direct reclaim.
2096 WARN_ON_ONCE((current->flags & (PF_MEMALLOC|PF_KSWAPD))
2103 if (PageChecked(page) && ext4_should_journal_data(inode))
2105 * It's mmapped pagecache. Add buffers and journal it. There
2106 * doesn't seem much point in redirtying the page here.
2108 return __ext4_journalled_writepage(page, len);
2110 memset(&io_submit, 0, sizeof(io_submit));
2111 ret = ext4_bio_write_page(&io_submit, page, len, wbc);
2112 ext4_io_submit(&io_submit);
2117 * This is called via ext4_da_writepages() to
2118 * calculate the total number of credits to reserve to fit
2119 * a single extent allocation into a single transaction,
2120 * ext4_da_writpeages() will loop calling this before
2121 * the block allocation.
2124 static int ext4_da_writepages_trans_blocks(struct inode *inode)
2126 int max_blocks = EXT4_I(inode)->i_reserved_data_blocks;
2129 * With non-extent format the journal credit needed to
2130 * insert nrblocks contiguous block is dependent on
2131 * number of contiguous block. So we will limit
2132 * number of contiguous block to a sane value
2134 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) &&
2135 (max_blocks > EXT4_MAX_TRANS_DATA))
2136 max_blocks = EXT4_MAX_TRANS_DATA;
2138 return ext4_chunk_trans_blocks(inode, max_blocks);
2142 * write_cache_pages_da - walk the list of dirty pages of the given
2143 * address space and accumulate pages that need writing, and call
2144 * mpage_da_map_and_submit to map a single contiguous memory region
2145 * and then write them.
2147 static int write_cache_pages_da(handle_t *handle,
2148 struct address_space *mapping,
2149 struct writeback_control *wbc,
2150 struct mpage_da_data *mpd,
2151 pgoff_t *done_index)
2153 struct buffer_head *bh, *head;
2154 struct inode *inode = mapping->host;
2155 struct pagevec pvec;
2156 unsigned int nr_pages;
2159 long nr_to_write = wbc->nr_to_write;
2160 int i, tag, ret = 0;
2162 memset(mpd, 0, sizeof(struct mpage_da_data));
2165 pagevec_init(&pvec, 0);
2166 index = wbc->range_start >> PAGE_CACHE_SHIFT;
2167 end = wbc->range_end >> PAGE_CACHE_SHIFT;
2169 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
2170 tag = PAGECACHE_TAG_TOWRITE;
2172 tag = PAGECACHE_TAG_DIRTY;
2174 *done_index = index;
2175 while (index <= end) {
2176 nr_pages = pagevec_lookup_tag(&pvec, mapping, &index, tag,
2177 min(end - index, (pgoff_t)PAGEVEC_SIZE-1) + 1);
2181 for (i = 0; i < nr_pages; i++) {
2182 struct page *page = pvec.pages[i];
2185 * At this point, the page may be truncated or
2186 * invalidated (changing page->mapping to NULL), or
2187 * even swizzled back from swapper_space to tmpfs file
2188 * mapping. However, page->index will not change
2189 * because we have a reference on the page.
2191 if (page->index > end)
2194 *done_index = page->index + 1;
2197 * If we can't merge this page, and we have
2198 * accumulated an contiguous region, write it
2200 if ((mpd->next_page != page->index) &&
2201 (mpd->next_page != mpd->first_page)) {
2202 mpage_da_map_and_submit(mpd);
2203 goto ret_extent_tail;
2209 * If the page is no longer dirty, or its
2210 * mapping no longer corresponds to inode we
2211 * are writing (which means it has been
2212 * truncated or invalidated), or the page is
2213 * already under writeback and we are not
2214 * doing a data integrity writeback, skip the page
2216 if (!PageDirty(page) ||
2217 (PageWriteback(page) &&
2218 (wbc->sync_mode == WB_SYNC_NONE)) ||
2219 unlikely(page->mapping != mapping)) {
2224 wait_on_page_writeback(page);
2225 BUG_ON(PageWriteback(page));
2228 * If we have inline data and arrive here, it means that
2229 * we will soon create the block for the 1st page, so
2230 * we'd better clear the inline data here.
2232 if (ext4_has_inline_data(inode)) {
2233 BUG_ON(ext4_test_inode_state(inode,
2234 EXT4_STATE_MAY_INLINE_DATA));
2235 ext4_destroy_inline_data(handle, inode);
2238 if (mpd->next_page != page->index)
2239 mpd->first_page = page->index;
2240 mpd->next_page = page->index + 1;
2241 logical = (sector_t) page->index <<
2242 (PAGE_CACHE_SHIFT - inode->i_blkbits);
2244 /* Add all dirty buffers to mpd */
2245 head = page_buffers(page);
2248 BUG_ON(buffer_locked(bh));
2250 * We need to try to allocate unmapped blocks
2251 * in the same page. Otherwise we won't make
2252 * progress with the page in ext4_writepage
2254 if (ext4_bh_delay_or_unwritten(NULL, bh)) {
2255 mpage_add_bh_to_extent(mpd, logical,
2258 goto ret_extent_tail;
2259 } else if (buffer_dirty(bh) &&
2260 buffer_mapped(bh)) {
2262 * mapped dirty buffer. We need to
2263 * update the b_state because we look
2264 * at b_state in mpage_da_map_blocks.
2265 * We don't update b_size because if we
2266 * find an unmapped buffer_head later
2267 * we need to use the b_state flag of
2270 if (mpd->b_size == 0)
2272 bh->b_state & BH_FLAGS;
2275 } while ((bh = bh->b_this_page) != head);
2277 if (nr_to_write > 0) {
2279 if (nr_to_write == 0 &&
2280 wbc->sync_mode == WB_SYNC_NONE)
2282 * We stop writing back only if we are
2283 * not doing integrity sync. In case of
2284 * integrity sync we have to keep going
2285 * because someone may be concurrently
2286 * dirtying pages, and we might have
2287 * synced a lot of newly appeared dirty
2288 * pages, but have not synced all of the
2294 pagevec_release(&pvec);
2299 ret = MPAGE_DA_EXTENT_TAIL;
2301 pagevec_release(&pvec);
2307 static int ext4_da_writepages(struct address_space *mapping,
2308 struct writeback_control *wbc)
2311 int range_whole = 0;
2312 handle_t *handle = NULL;
2313 struct mpage_da_data mpd;
2314 struct inode *inode = mapping->host;
2315 int pages_written = 0;
2316 unsigned int max_pages;
2317 int range_cyclic, cycled = 1, io_done = 0;
2318 int needed_blocks, ret = 0;
2319 long desired_nr_to_write, nr_to_writebump = 0;
2320 loff_t range_start = wbc->range_start;
2321 struct ext4_sb_info *sbi = EXT4_SB(mapping->host->i_sb);
2322 pgoff_t done_index = 0;
2324 struct blk_plug plug;
2326 trace_ext4_da_writepages(inode, wbc);
2329 * No pages to write? This is mainly a kludge to avoid starting
2330 * a transaction for special inodes like journal inode on last iput()
2331 * because that could violate lock ordering on umount
2333 if (!mapping->nrpages || !mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
2337 * If the filesystem has aborted, it is read-only, so return
2338 * right away instead of dumping stack traces later on that
2339 * will obscure the real source of the problem. We test
2340 * EXT4_MF_FS_ABORTED instead of sb->s_flag's MS_RDONLY because
2341 * the latter could be true if the filesystem is mounted
2342 * read-only, and in that case, ext4_da_writepages should
2343 * *never* be called, so if that ever happens, we would want
2346 if (unlikely(sbi->s_mount_flags & EXT4_MF_FS_ABORTED))
2349 if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
2352 range_cyclic = wbc->range_cyclic;
2353 if (wbc->range_cyclic) {
2354 index = mapping->writeback_index;
2357 wbc->range_start = index << PAGE_CACHE_SHIFT;
2358 wbc->range_end = LLONG_MAX;
2359 wbc->range_cyclic = 0;
2362 index = wbc->range_start >> PAGE_CACHE_SHIFT;
2363 end = wbc->range_end >> PAGE_CACHE_SHIFT;
2367 * This works around two forms of stupidity. The first is in
2368 * the writeback code, which caps the maximum number of pages
2369 * written to be 1024 pages. This is wrong on multiple
2370 * levels; different architectues have a different page size,
2371 * which changes the maximum amount of data which gets
2372 * written. Secondly, 4 megabytes is way too small. XFS
2373 * forces this value to be 16 megabytes by multiplying
2374 * nr_to_write parameter by four, and then relies on its
2375 * allocator to allocate larger extents to make them
2376 * contiguous. Unfortunately this brings us to the second
2377 * stupidity, which is that ext4's mballoc code only allocates
2378 * at most 2048 blocks. So we force contiguous writes up to
2379 * the number of dirty blocks in the inode, or
2380 * sbi->max_writeback_mb_bump whichever is smaller.
2382 max_pages = sbi->s_max_writeback_mb_bump << (20 - PAGE_CACHE_SHIFT);
2383 if (!range_cyclic && range_whole) {
2384 if (wbc->nr_to_write == LONG_MAX)
2385 desired_nr_to_write = wbc->nr_to_write;
2387 desired_nr_to_write = wbc->nr_to_write * 8;
2389 desired_nr_to_write = ext4_num_dirty_pages(inode, index,
2391 if (desired_nr_to_write > max_pages)
2392 desired_nr_to_write = max_pages;
2394 if (wbc->nr_to_write < desired_nr_to_write) {
2395 nr_to_writebump = desired_nr_to_write - wbc->nr_to_write;
2396 wbc->nr_to_write = desired_nr_to_write;
2400 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
2401 tag_pages_for_writeback(mapping, index, end);
2403 blk_start_plug(&plug);
2404 while (!ret && wbc->nr_to_write > 0) {
2407 * we insert one extent at a time. So we need
2408 * credit needed for single extent allocation.
2409 * journalled mode is currently not supported
2412 BUG_ON(ext4_should_journal_data(inode));
2413 needed_blocks = ext4_da_writepages_trans_blocks(inode);
2415 /* start a new transaction*/
2416 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
2418 if (IS_ERR(handle)) {
2419 ret = PTR_ERR(handle);
2420 ext4_msg(inode->i_sb, KERN_CRIT, "%s: jbd2_start: "
2421 "%ld pages, ino %lu; err %d", __func__,
2422 wbc->nr_to_write, inode->i_ino, ret);
2423 blk_finish_plug(&plug);
2424 goto out_writepages;
2428 * Now call write_cache_pages_da() to find the next
2429 * contiguous region of logical blocks that need
2430 * blocks to be allocated by ext4 and submit them.
2432 ret = write_cache_pages_da(handle, mapping,
2433 wbc, &mpd, &done_index);
2435 * If we have a contiguous extent of pages and we
2436 * haven't done the I/O yet, map the blocks and submit
2439 if (!mpd.io_done && mpd.next_page != mpd.first_page) {
2440 mpage_da_map_and_submit(&mpd);
2441 ret = MPAGE_DA_EXTENT_TAIL;
2443 trace_ext4_da_write_pages(inode, &mpd);
2444 wbc->nr_to_write -= mpd.pages_written;
2446 ext4_journal_stop(handle);
2448 if ((mpd.retval == -ENOSPC) && sbi->s_journal) {
2449 /* commit the transaction which would
2450 * free blocks released in the transaction
2453 jbd2_journal_force_commit_nested(sbi->s_journal);
2455 } else if (ret == MPAGE_DA_EXTENT_TAIL) {
2457 * Got one extent now try with rest of the pages.
2458 * If mpd.retval is set -EIO, journal is aborted.
2459 * So we don't need to write any more.
2461 pages_written += mpd.pages_written;
2464 } else if (wbc->nr_to_write)
2466 * There is no more writeout needed
2467 * or we requested for a noblocking writeout
2468 * and we found the device congested
2472 blk_finish_plug(&plug);
2473 if (!io_done && !cycled) {
2476 wbc->range_start = index << PAGE_CACHE_SHIFT;
2477 wbc->range_end = mapping->writeback_index - 1;
2482 wbc->range_cyclic = range_cyclic;
2483 if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
2485 * set the writeback_index so that range_cyclic
2486 * mode will write it back later
2488 mapping->writeback_index = done_index;
2491 wbc->nr_to_write -= nr_to_writebump;
2492 wbc->range_start = range_start;
2493 trace_ext4_da_writepages_result(inode, wbc, ret, pages_written);
2497 static int ext4_nonda_switch(struct super_block *sb)
2499 s64 free_blocks, dirty_blocks;
2500 struct ext4_sb_info *sbi = EXT4_SB(sb);
2503 * switch to non delalloc mode if we are running low
2504 * on free block. The free block accounting via percpu
2505 * counters can get slightly wrong with percpu_counter_batch getting
2506 * accumulated on each CPU without updating global counters
2507 * Delalloc need an accurate free block accounting. So switch
2508 * to non delalloc when we are near to error range.
2510 free_blocks = EXT4_C2B(sbi,
2511 percpu_counter_read_positive(&sbi->s_freeclusters_counter));
2512 dirty_blocks = percpu_counter_read_positive(&sbi->s_dirtyclusters_counter);
2514 * Start pushing delalloc when 1/2 of free blocks are dirty.
2516 if (dirty_blocks && (free_blocks < 2 * dirty_blocks))
2517 try_to_writeback_inodes_sb(sb, WB_REASON_FS_FREE_SPACE);
2519 if (2 * free_blocks < 3 * dirty_blocks ||
2520 free_blocks < (dirty_blocks + EXT4_FREECLUSTERS_WATERMARK)) {
2522 * free block count is less than 150% of dirty blocks
2523 * or free blocks is less than watermark
2530 static int ext4_da_write_begin(struct file *file, struct address_space *mapping,
2531 loff_t pos, unsigned len, unsigned flags,
2532 struct page **pagep, void **fsdata)
2534 int ret, retries = 0;
2537 struct inode *inode = mapping->host;
2540 index = pos >> PAGE_CACHE_SHIFT;
2542 if (ext4_nonda_switch(inode->i_sb)) {
2543 *fsdata = (void *)FALL_BACK_TO_NONDELALLOC;
2544 return ext4_write_begin(file, mapping, pos,
2545 len, flags, pagep, fsdata);
2547 *fsdata = (void *)0;
2548 trace_ext4_da_write_begin(inode, pos, len, flags);
2550 if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
2551 ret = ext4_da_write_inline_data_begin(mapping, inode,
2561 * grab_cache_page_write_begin() can take a long time if the
2562 * system is thrashing due to memory pressure, or if the page
2563 * is being written back. So grab it first before we start
2564 * the transaction handle. This also allows us to allocate
2565 * the page (if needed) without using GFP_NOFS.
2568 page = grab_cache_page_write_begin(mapping, index, flags);
2574 * With delayed allocation, we don't log the i_disksize update
2575 * if there is delayed block allocation. But we still need
2576 * to journalling the i_disksize update if writes to the end
2577 * of file which has an already mapped buffer.
2580 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE, 1);
2581 if (IS_ERR(handle)) {
2582 page_cache_release(page);
2583 return PTR_ERR(handle);
2587 if (page->mapping != mapping) {
2588 /* The page got truncated from under us */
2590 page_cache_release(page);
2591 ext4_journal_stop(handle);
2594 /* In case writeback began while the page was unlocked */
2595 wait_on_page_writeback(page);
2597 ret = __block_write_begin(page, pos, len, ext4_da_get_block_prep);
2600 ext4_journal_stop(handle);
2602 * block_write_begin may have instantiated a few blocks
2603 * outside i_size. Trim these off again. Don't need
2604 * i_size_read because we hold i_mutex.
2606 if (pos + len > inode->i_size)
2607 ext4_truncate_failed_write(inode);
2609 if (ret == -ENOSPC &&
2610 ext4_should_retry_alloc(inode->i_sb, &retries))
2613 page_cache_release(page);
2622 * Check if we should update i_disksize
2623 * when write to the end of file but not require block allocation
2625 static int ext4_da_should_update_i_disksize(struct page *page,
2626 unsigned long offset)
2628 struct buffer_head *bh;
2629 struct inode *inode = page->mapping->host;
2633 bh = page_buffers(page);
2634 idx = offset >> inode->i_blkbits;
2636 for (i = 0; i < idx; i++)
2637 bh = bh->b_this_page;
2639 if (!buffer_mapped(bh) || (buffer_delay(bh)) || buffer_unwritten(bh))
2644 static int ext4_da_write_end(struct file *file,
2645 struct address_space *mapping,
2646 loff_t pos, unsigned len, unsigned copied,
2647 struct page *page, void *fsdata)
2649 struct inode *inode = mapping->host;
2651 handle_t *handle = ext4_journal_current_handle();
2653 unsigned long start, end;
2654 int write_mode = (int)(unsigned long)fsdata;
2656 if (write_mode == FALL_BACK_TO_NONDELALLOC) {
2657 switch (ext4_inode_journal_mode(inode)) {
2658 case EXT4_INODE_ORDERED_DATA_MODE:
2659 return ext4_ordered_write_end(file, mapping, pos,
2660 len, copied, page, fsdata);
2661 case EXT4_INODE_WRITEBACK_DATA_MODE:
2662 return ext4_writeback_write_end(file, mapping, pos,
2663 len, copied, page, fsdata);
2669 trace_ext4_da_write_end(inode, pos, len, copied);
2670 start = pos & (PAGE_CACHE_SIZE - 1);
2671 end = start + copied - 1;
2674 * generic_write_end() will run mark_inode_dirty() if i_size
2675 * changes. So let's piggyback the i_disksize mark_inode_dirty
2678 new_i_size = pos + copied;
2679 if (copied && new_i_size > EXT4_I(inode)->i_disksize) {
2680 if (ext4_has_inline_data(inode) ||
2681 ext4_da_should_update_i_disksize(page, end)) {
2682 down_write(&EXT4_I(inode)->i_data_sem);
2683 if (new_i_size > EXT4_I(inode)->i_disksize)
2684 EXT4_I(inode)->i_disksize = new_i_size;
2685 up_write(&EXT4_I(inode)->i_data_sem);
2686 /* We need to mark inode dirty even if
2687 * new_i_size is less that inode->i_size
2688 * bu greater than i_disksize.(hint delalloc)
2690 ext4_mark_inode_dirty(handle, inode);
2694 if (write_mode != CONVERT_INLINE_DATA &&
2695 ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA) &&
2696 ext4_has_inline_data(inode))
2697 ret2 = ext4_da_write_inline_data_end(inode, pos, len, copied,
2700 ret2 = generic_write_end(file, mapping, pos, len, copied,
2706 ret2 = ext4_journal_stop(handle);
2710 return ret ? ret : copied;
2713 static void ext4_da_invalidatepage(struct page *page, unsigned long offset)
2716 * Drop reserved blocks
2718 BUG_ON(!PageLocked(page));
2719 if (!page_has_buffers(page))
2722 ext4_da_page_release_reservation(page, offset);
2725 ext4_invalidatepage(page, offset);
2731 * Force all delayed allocation blocks to be allocated for a given inode.
2733 int ext4_alloc_da_blocks(struct inode *inode)
2735 trace_ext4_alloc_da_blocks(inode);
2737 if (!EXT4_I(inode)->i_reserved_data_blocks &&
2738 !EXT4_I(inode)->i_reserved_meta_blocks)
2742 * We do something simple for now. The filemap_flush() will
2743 * also start triggering a write of the data blocks, which is
2744 * not strictly speaking necessary (and for users of
2745 * laptop_mode, not even desirable). However, to do otherwise
2746 * would require replicating code paths in:
2748 * ext4_da_writepages() ->
2749 * write_cache_pages() ---> (via passed in callback function)
2750 * __mpage_da_writepage() -->
2751 * mpage_add_bh_to_extent()
2752 * mpage_da_map_blocks()
2754 * The problem is that write_cache_pages(), located in
2755 * mm/page-writeback.c, marks pages clean in preparation for
2756 * doing I/O, which is not desirable if we're not planning on
2759 * We could call write_cache_pages(), and then redirty all of
2760 * the pages by calling redirty_page_for_writepage() but that
2761 * would be ugly in the extreme. So instead we would need to
2762 * replicate parts of the code in the above functions,
2763 * simplifying them because we wouldn't actually intend to
2764 * write out the pages, but rather only collect contiguous
2765 * logical block extents, call the multi-block allocator, and
2766 * then update the buffer heads with the block allocations.
2768 * For now, though, we'll cheat by calling filemap_flush(),
2769 * which will map the blocks, and start the I/O, but not
2770 * actually wait for the I/O to complete.
2772 return filemap_flush(inode->i_mapping);
2776 * bmap() is special. It gets used by applications such as lilo and by
2777 * the swapper to find the on-disk block of a specific piece of data.
2779 * Naturally, this is dangerous if the block concerned is still in the
2780 * journal. If somebody makes a swapfile on an ext4 data-journaling
2781 * filesystem and enables swap, then they may get a nasty shock when the
2782 * data getting swapped to that swapfile suddenly gets overwritten by
2783 * the original zero's written out previously to the journal and
2784 * awaiting writeback in the kernel's buffer cache.
2786 * So, if we see any bmap calls here on a modified, data-journaled file,
2787 * take extra steps to flush any blocks which might be in the cache.
2789 static sector_t ext4_bmap(struct address_space *mapping, sector_t block)
2791 struct inode *inode = mapping->host;
2796 * We can get here for an inline file via the FIBMAP ioctl
2798 if (ext4_has_inline_data(inode))
2801 if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY) &&
2802 test_opt(inode->i_sb, DELALLOC)) {
2804 * With delalloc we want to sync the file
2805 * so that we can make sure we allocate
2808 filemap_write_and_wait(mapping);
2811 if (EXT4_JOURNAL(inode) &&
2812 ext4_test_inode_state(inode, EXT4_STATE_JDATA)) {
2814 * This is a REALLY heavyweight approach, but the use of
2815 * bmap on dirty files is expected to be extremely rare:
2816 * only if we run lilo or swapon on a freshly made file
2817 * do we expect this to happen.
2819 * (bmap requires CAP_SYS_RAWIO so this does not
2820 * represent an unprivileged user DOS attack --- we'd be
2821 * in trouble if mortal users could trigger this path at
2824 * NB. EXT4_STATE_JDATA is not set on files other than
2825 * regular files. If somebody wants to bmap a directory
2826 * or symlink and gets confused because the buffer
2827 * hasn't yet been flushed to disk, they deserve
2828 * everything they get.
2831 ext4_clear_inode_state(inode, EXT4_STATE_JDATA);
2832 journal = EXT4_JOURNAL(inode);
2833 jbd2_journal_lock_updates(journal);
2834 err = jbd2_journal_flush(journal);
2835 jbd2_journal_unlock_updates(journal);
2841 return generic_block_bmap(mapping, block, ext4_get_block);
2844 static int ext4_readpage(struct file *file, struct page *page)
2847 struct inode *inode = page->mapping->host;
2849 trace_ext4_readpage(page);
2851 if (ext4_has_inline_data(inode))
2852 ret = ext4_readpage_inline(inode, page);
2855 return mpage_readpage(page, ext4_get_block);
2861 ext4_readpages(struct file *file, struct address_space *mapping,
2862 struct list_head *pages, unsigned nr_pages)
2864 struct inode *inode = mapping->host;
2866 /* If the file has inline data, no need to do readpages. */
2867 if (ext4_has_inline_data(inode))
2870 return mpage_readpages(mapping, pages, nr_pages, ext4_get_block);
2873 static void ext4_invalidatepage(struct page *page, unsigned long offset)
2875 trace_ext4_invalidatepage(page, offset);
2877 /* No journalling happens on data buffers when this function is used */
2878 WARN_ON(page_has_buffers(page) && buffer_jbd(page_buffers(page)));
2880 block_invalidatepage(page, offset);
2883 static int __ext4_journalled_invalidatepage(struct page *page,
2884 unsigned long offset)
2886 journal_t *journal = EXT4_JOURNAL(page->mapping->host);
2888 trace_ext4_journalled_invalidatepage(page, offset);
2891 * If it's a full truncate we just forget about the pending dirtying
2894 ClearPageChecked(page);
2896 return jbd2_journal_invalidatepage(journal, page, offset);
2899 /* Wrapper for aops... */
2900 static void ext4_journalled_invalidatepage(struct page *page,
2901 unsigned long offset)
2903 WARN_ON(__ext4_journalled_invalidatepage(page, offset) < 0);
2906 static int ext4_releasepage(struct page *page, gfp_t wait)
2908 journal_t *journal = EXT4_JOURNAL(page->mapping->host);
2910 trace_ext4_releasepage(page);
2912 WARN_ON(PageChecked(page));
2913 if (!page_has_buffers(page))
2916 return jbd2_journal_try_to_free_buffers(journal, page, wait);
2918 return try_to_free_buffers(page);
2922 * ext4_get_block used when preparing for a DIO write or buffer write.
2923 * We allocate an uinitialized extent if blocks haven't been allocated.
2924 * The extent will be converted to initialized after the IO is complete.
2926 int ext4_get_block_write(struct inode *inode, sector_t iblock,
2927 struct buffer_head *bh_result, int create)
2929 ext4_debug("ext4_get_block_write: inode %lu, create flag %d\n",
2930 inode->i_ino, create);
2931 return _ext4_get_block(inode, iblock, bh_result,
2932 EXT4_GET_BLOCKS_IO_CREATE_EXT);
2935 static int ext4_get_block_write_nolock(struct inode *inode, sector_t iblock,
2936 struct buffer_head *bh_result, int create)
2938 ext4_debug("ext4_get_block_write_nolock: inode %lu, create flag %d\n",
2939 inode->i_ino, create);
2940 return _ext4_get_block(inode, iblock, bh_result,
2941 EXT4_GET_BLOCKS_NO_LOCK);
2944 static void ext4_end_io_dio(struct kiocb *iocb, loff_t offset,
2945 ssize_t size, void *private, int ret,
2948 struct inode *inode = iocb->ki_filp->f_path.dentry->d_inode;
2949 ext4_io_end_t *io_end = iocb->private;
2951 /* if not async direct IO or dio with 0 bytes write, just return */
2952 if (!io_end || !size)
2955 ext_debug("ext4_end_io_dio(): io_end 0x%p "
2956 "for inode %lu, iocb 0x%p, offset %llu, size %zd\n",
2957 iocb->private, io_end->inode->i_ino, iocb, offset,
2960 iocb->private = NULL;
2962 /* if not aio dio with unwritten extents, just free io and return */
2963 if (!(io_end->flag & EXT4_IO_END_UNWRITTEN)) {
2964 ext4_free_io_end(io_end);
2966 inode_dio_done(inode);
2968 aio_complete(iocb, ret, 0);
2972 io_end->offset = offset;
2973 io_end->size = size;
2975 io_end->iocb = iocb;
2976 io_end->result = ret;
2979 ext4_add_complete_io(io_end);
2983 * For ext4 extent files, ext4 will do direct-io write to holes,
2984 * preallocated extents, and those write extend the file, no need to
2985 * fall back to buffered IO.
2987 * For holes, we fallocate those blocks, mark them as uninitialized
2988 * If those blocks were preallocated, we mark sure they are split, but
2989 * still keep the range to write as uninitialized.
2991 * The unwritten extents will be converted to written when DIO is completed.
2992 * For async direct IO, since the IO may still pending when return, we
2993 * set up an end_io call back function, which will do the conversion
2994 * when async direct IO completed.
2996 * If the O_DIRECT write will extend the file then add this inode to the
2997 * orphan list. So recovery will truncate it back to the original size
2998 * if the machine crashes during the write.
3001 static ssize_t ext4_ext_direct_IO(int rw, struct kiocb *iocb,
3002 const struct iovec *iov, loff_t offset,
3003 unsigned long nr_segs)
3005 struct file *file = iocb->ki_filp;
3006 struct inode *inode = file->f_mapping->host;
3008 size_t count = iov_length(iov, nr_segs);
3010 get_block_t *get_block_func = NULL;
3012 loff_t final_size = offset + count;
3014 /* Use the old path for reads and writes beyond i_size. */
3015 if (rw != WRITE || final_size > inode->i_size)
3016 return ext4_ind_direct_IO(rw, iocb, iov, offset, nr_segs);
3018 BUG_ON(iocb->private == NULL);
3020 /* If we do a overwrite dio, i_mutex locking can be released */
3021 overwrite = *((int *)iocb->private);
3024 atomic_inc(&inode->i_dio_count);
3025 down_read(&EXT4_I(inode)->i_data_sem);
3026 mutex_unlock(&inode->i_mutex);
3030 * We could direct write to holes and fallocate.
3032 * Allocated blocks to fill the hole are marked as
3033 * uninitialized to prevent parallel buffered read to expose
3034 * the stale data before DIO complete the data IO.
3036 * As to previously fallocated extents, ext4 get_block will
3037 * just simply mark the buffer mapped but still keep the
3038 * extents uninitialized.
3040 * For non AIO case, we will convert those unwritten extents
3041 * to written after return back from blockdev_direct_IO.
3043 * For async DIO, the conversion needs to be deferred when the
3044 * IO is completed. The ext4 end_io callback function will be
3045 * called to take care of the conversion work. Here for async
3046 * case, we allocate an io_end structure to hook to the iocb.
3048 iocb->private = NULL;
3049 ext4_inode_aio_set(inode, NULL);
3050 if (!is_sync_kiocb(iocb)) {
3051 ext4_io_end_t *io_end = ext4_init_io_end(inode, GFP_NOFS);
3056 io_end->flag |= EXT4_IO_END_DIRECT;
3057 iocb->private = io_end;
3059 * we save the io structure for current async direct
3060 * IO, so that later ext4_map_blocks() could flag the
3061 * io structure whether there is a unwritten extents
3062 * needs to be converted when IO is completed.
3064 ext4_inode_aio_set(inode, io_end);
3068 get_block_func = ext4_get_block_write_nolock;
3070 get_block_func = ext4_get_block_write;
3071 dio_flags = DIO_LOCKING;
3073 ret = __blockdev_direct_IO(rw, iocb, inode,
3074 inode->i_sb->s_bdev, iov,
3082 ext4_inode_aio_set(inode, NULL);
3084 * The io_end structure takes a reference to the inode, that
3085 * structure needs to be destroyed and the reference to the
3086 * inode need to be dropped, when IO is complete, even with 0
3087 * byte write, or failed.
3089 * In the successful AIO DIO case, the io_end structure will
3090 * be destroyed and the reference to the inode will be dropped
3091 * after the end_io call back function is called.
3093 * In the case there is 0 byte write, or error case, since VFS
3094 * direct IO won't invoke the end_io call back function, we
3095 * need to free the end_io structure here.
3097 if (ret != -EIOCBQUEUED && ret <= 0 && iocb->private) {
3098 ext4_free_io_end(iocb->private);
3099 iocb->private = NULL;
3100 } else if (ret > 0 && !overwrite && ext4_test_inode_state(inode,
3101 EXT4_STATE_DIO_UNWRITTEN)) {
3104 * for non AIO case, since the IO is already
3105 * completed, we could do the conversion right here
3107 err = ext4_convert_unwritten_extents(inode,
3111 ext4_clear_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN);
3115 /* take i_mutex locking again if we do a ovewrite dio */
3117 inode_dio_done(inode);
3118 up_read(&EXT4_I(inode)->i_data_sem);
3119 mutex_lock(&inode->i_mutex);
3125 static ssize_t ext4_direct_IO(int rw, struct kiocb *iocb,
3126 const struct iovec *iov, loff_t offset,
3127 unsigned long nr_segs)
3129 struct file *file = iocb->ki_filp;
3130 struct inode *inode = file->f_mapping->host;
3134 * If we are doing data journalling we don't support O_DIRECT
3136 if (ext4_should_journal_data(inode))
3139 /* Let buffer I/O handle the inline data case. */
3140 if (ext4_has_inline_data(inode))
3143 trace_ext4_direct_IO_enter(inode, offset, iov_length(iov, nr_segs), rw);
3144 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3145 ret = ext4_ext_direct_IO(rw, iocb, iov, offset, nr_segs);
3147 ret = ext4_ind_direct_IO(rw, iocb, iov, offset, nr_segs);
3148 trace_ext4_direct_IO_exit(inode, offset,
3149 iov_length(iov, nr_segs), rw, ret);
3154 * Pages can be marked dirty completely asynchronously from ext4's journalling
3155 * activity. By filemap_sync_pte(), try_to_unmap_one(), etc. We cannot do
3156 * much here because ->set_page_dirty is called under VFS locks. The page is
3157 * not necessarily locked.
3159 * We cannot just dirty the page and leave attached buffers clean, because the
3160 * buffers' dirty state is "definitive". We cannot just set the buffers dirty
3161 * or jbddirty because all the journalling code will explode.
3163 * So what we do is to mark the page "pending dirty" and next time writepage
3164 * is called, propagate that into the buffers appropriately.
3166 static int ext4_journalled_set_page_dirty(struct page *page)
3168 SetPageChecked(page);
3169 return __set_page_dirty_nobuffers(page);
3172 static const struct address_space_operations ext4_ordered_aops = {
3173 .readpage = ext4_readpage,
3174 .readpages = ext4_readpages,
3175 .writepage = ext4_writepage,
3176 .write_begin = ext4_write_begin,
3177 .write_end = ext4_ordered_write_end,
3179 .invalidatepage = ext4_invalidatepage,
3180 .releasepage = ext4_releasepage,
3181 .direct_IO = ext4_direct_IO,
3182 .migratepage = buffer_migrate_page,
3183 .is_partially_uptodate = block_is_partially_uptodate,
3184 .error_remove_page = generic_error_remove_page,
3187 static const struct address_space_operations ext4_writeback_aops = {
3188 .readpage = ext4_readpage,
3189 .readpages = ext4_readpages,
3190 .writepage = ext4_writepage,
3191 .write_begin = ext4_write_begin,
3192 .write_end = ext4_writeback_write_end,
3194 .invalidatepage = ext4_invalidatepage,
3195 .releasepage = ext4_releasepage,
3196 .direct_IO = ext4_direct_IO,
3197 .migratepage = buffer_migrate_page,
3198 .is_partially_uptodate = block_is_partially_uptodate,
3199 .error_remove_page = generic_error_remove_page,
3202 static const struct address_space_operations ext4_journalled_aops = {
3203 .readpage = ext4_readpage,
3204 .readpages = ext4_readpages,
3205 .writepage = ext4_writepage,
3206 .write_begin = ext4_write_begin,
3207 .write_end = ext4_journalled_write_end,
3208 .set_page_dirty = ext4_journalled_set_page_dirty,
3210 .invalidatepage = ext4_journalled_invalidatepage,
3211 .releasepage = ext4_releasepage,
3212 .direct_IO = ext4_direct_IO,
3213 .is_partially_uptodate = block_is_partially_uptodate,
3214 .error_remove_page = generic_error_remove_page,
3217 static const struct address_space_operations ext4_da_aops = {
3218 .readpage = ext4_readpage,
3219 .readpages = ext4_readpages,
3220 .writepage = ext4_writepage,
3221 .writepages = ext4_da_writepages,
3222 .write_begin = ext4_da_write_begin,
3223 .write_end = ext4_da_write_end,
3225 .invalidatepage = ext4_da_invalidatepage,
3226 .releasepage = ext4_releasepage,
3227 .direct_IO = ext4_direct_IO,
3228 .migratepage = buffer_migrate_page,
3229 .is_partially_uptodate = block_is_partially_uptodate,
3230 .error_remove_page = generic_error_remove_page,
3233 void ext4_set_aops(struct inode *inode)
3235 switch (ext4_inode_journal_mode(inode)) {
3236 case EXT4_INODE_ORDERED_DATA_MODE:
3237 if (test_opt(inode->i_sb, DELALLOC))
3238 inode->i_mapping->a_ops = &ext4_da_aops;
3240 inode->i_mapping->a_ops = &ext4_ordered_aops;
3242 case EXT4_INODE_WRITEBACK_DATA_MODE:
3243 if (test_opt(inode->i_sb, DELALLOC))
3244 inode->i_mapping->a_ops = &ext4_da_aops;
3246 inode->i_mapping->a_ops = &ext4_writeback_aops;
3248 case EXT4_INODE_JOURNAL_DATA_MODE:
3249 inode->i_mapping->a_ops = &ext4_journalled_aops;
3258 * ext4_discard_partial_page_buffers()
3259 * Wrapper function for ext4_discard_partial_page_buffers_no_lock.
3260 * This function finds and locks the page containing the offset
3261 * "from" and passes it to ext4_discard_partial_page_buffers_no_lock.
3262 * Calling functions that already have the page locked should call
3263 * ext4_discard_partial_page_buffers_no_lock directly.
3265 int ext4_discard_partial_page_buffers(handle_t *handle,
3266 struct address_space *mapping, loff_t from,
3267 loff_t length, int flags)
3269 struct inode *inode = mapping->host;
3273 page = find_or_create_page(mapping, from >> PAGE_CACHE_SHIFT,
3274 mapping_gfp_mask(mapping) & ~__GFP_FS);
3278 err = ext4_discard_partial_page_buffers_no_lock(handle, inode, page,
3279 from, length, flags);
3282 page_cache_release(page);
3287 * ext4_discard_partial_page_buffers_no_lock()
3288 * Zeros a page range of length 'length' starting from offset 'from'.
3289 * Buffer heads that correspond to the block aligned regions of the
3290 * zeroed range will be unmapped. Unblock aligned regions
3291 * will have the corresponding buffer head mapped if needed so that
3292 * that region of the page can be updated with the partial zero out.
3294 * This function assumes that the page has already been locked. The
3295 * The range to be discarded must be contained with in the given page.
3296 * If the specified range exceeds the end of the page it will be shortened
3297 * to the end of the page that corresponds to 'from'. This function is
3298 * appropriate for updating a page and it buffer heads to be unmapped and
3299 * zeroed for blocks that have been either released, or are going to be
3302 * handle: The journal handle
3303 * inode: The files inode
3304 * page: A locked page that contains the offset "from"
3305 * from: The starting byte offset (from the beginning of the file)
3306 * to begin discarding
3307 * len: The length of bytes to discard
3308 * flags: Optional flags that may be used:
3310 * EXT4_DISCARD_PARTIAL_PG_ZERO_UNMAPPED
3311 * Only zero the regions of the page whose buffer heads
3312 * have already been unmapped. This flag is appropriate
3313 * for updating the contents of a page whose blocks may
3314 * have already been released, and we only want to zero
3315 * out the regions that correspond to those released blocks.
3317 * Returns zero on success or negative on failure.
3319 static int ext4_discard_partial_page_buffers_no_lock(handle_t *handle,
3320 struct inode *inode, struct page *page, loff_t from,
3321 loff_t length, int flags)
3323 ext4_fsblk_t index = from >> PAGE_CACHE_SHIFT;
3324 unsigned int offset = from & (PAGE_CACHE_SIZE-1);
3325 unsigned int blocksize, max, pos;
3327 struct buffer_head *bh;
3330 blocksize = inode->i_sb->s_blocksize;
3331 max = PAGE_CACHE_SIZE - offset;
3333 if (index != page->index)
3337 * correct length if it does not fall between
3338 * 'from' and the end of the page
3340 if (length > max || length < 0)
3343 iblock = index << (PAGE_CACHE_SHIFT - inode->i_sb->s_blocksize_bits);
3345 if (!page_has_buffers(page))
3346 create_empty_buffers(page, blocksize, 0);
3348 /* Find the buffer that contains "offset" */
3349 bh = page_buffers(page);
3351 while (offset >= pos) {
3352 bh = bh->b_this_page;
3358 while (pos < offset + length) {
3359 unsigned int end_of_block, range_to_discard;
3363 /* The length of space left to zero and unmap */
3364 range_to_discard = offset + length - pos;
3366 /* The length of space until the end of the block */
3367 end_of_block = blocksize - (pos & (blocksize-1));
3370 * Do not unmap or zero past end of block
3371 * for this buffer head
3373 if (range_to_discard > end_of_block)
3374 range_to_discard = end_of_block;
3378 * Skip this buffer head if we are only zeroing unampped
3379 * regions of the page
3381 if (flags & EXT4_DISCARD_PARTIAL_PG_ZERO_UNMAPPED &&
3385 /* If the range is block aligned, unmap */
3386 if (range_to_discard == blocksize) {
3387 clear_buffer_dirty(bh);
3389 clear_buffer_mapped(bh);
3390 clear_buffer_req(bh);
3391 clear_buffer_new(bh);
3392 clear_buffer_delay(bh);
3393 clear_buffer_unwritten(bh);
3394 clear_buffer_uptodate(bh);
3395 zero_user(page, pos, range_to_discard);
3396 BUFFER_TRACE(bh, "Buffer discarded");
3401 * If this block is not completely contained in the range
3402 * to be discarded, then it is not going to be released. Because
3403 * we need to keep this block, we need to make sure this part
3404 * of the page is uptodate before we modify it by writeing
3405 * partial zeros on it.
3407 if (!buffer_mapped(bh)) {
3409 * Buffer head must be mapped before we can read
3412 BUFFER_TRACE(bh, "unmapped");
3413 ext4_get_block(inode, iblock, bh, 0);
3414 /* unmapped? It's a hole - nothing to do */
3415 if (!buffer_mapped(bh)) {
3416 BUFFER_TRACE(bh, "still unmapped");
3421 /* Ok, it's mapped. Make sure it's up-to-date */
3422 if (PageUptodate(page))
3423 set_buffer_uptodate(bh);
3425 if (!buffer_uptodate(bh)) {
3427 ll_rw_block(READ, 1, &bh);
3429 /* Uhhuh. Read error. Complain and punt.*/
3430 if (!buffer_uptodate(bh))
3434 if (ext4_should_journal_data(inode)) {
3435 BUFFER_TRACE(bh, "get write access");
3436 err = ext4_journal_get_write_access(handle, bh);
3441 zero_user(page, pos, range_to_discard);
3444 if (ext4_should_journal_data(inode)) {
3445 err = ext4_handle_dirty_metadata(handle, inode, bh);
3447 mark_buffer_dirty(bh);
3449 BUFFER_TRACE(bh, "Partial buffer zeroed");
3451 bh = bh->b_this_page;
3453 pos += range_to_discard;
3459 int ext4_can_truncate(struct inode *inode)
3461 if (S_ISREG(inode->i_mode))
3463 if (S_ISDIR(inode->i_mode))
3465 if (S_ISLNK(inode->i_mode))
3466 return !ext4_inode_is_fast_symlink(inode);
3471 * ext4_punch_hole: punches a hole in a file by releaseing the blocks
3472 * associated with the given offset and length
3474 * @inode: File inode
3475 * @offset: The offset where the hole will begin
3476 * @len: The length of the hole
3478 * Returns: 0 on success or negative on failure
3481 int ext4_punch_hole(struct file *file, loff_t offset, loff_t length)
3483 struct inode *inode = file->f_path.dentry->d_inode;
3484 if (!S_ISREG(inode->i_mode))
3487 if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3488 return ext4_ind_punch_hole(file, offset, length);
3490 if (EXT4_SB(inode->i_sb)->s_cluster_ratio > 1) {
3491 /* TODO: Add support for bigalloc file systems */
3495 trace_ext4_punch_hole(inode, offset, length);
3497 return ext4_ext_punch_hole(file, offset, length);
3503 * We block out ext4_get_block() block instantiations across the entire
3504 * transaction, and VFS/VM ensures that ext4_truncate() cannot run
3505 * simultaneously on behalf of the same inode.
3507 * As we work through the truncate and commit bits of it to the journal there
3508 * is one core, guiding principle: the file's tree must always be consistent on
3509 * disk. We must be able to restart the truncate after a crash.
3511 * The file's tree may be transiently inconsistent in memory (although it
3512 * probably isn't), but whenever we close off and commit a journal transaction,
3513 * the contents of (the filesystem + the journal) must be consistent and
3514 * restartable. It's pretty simple, really: bottom up, right to left (although
3515 * left-to-right works OK too).
3517 * Note that at recovery time, journal replay occurs *before* the restart of
3518 * truncate against the orphan inode list.
3520 * The committed inode has the new, desired i_size (which is the same as
3521 * i_disksize in this case). After a crash, ext4_orphan_cleanup() will see
3522 * that this inode's truncate did not complete and it will again call
3523 * ext4_truncate() to have another go. So there will be instantiated blocks
3524 * to the right of the truncation point in a crashed ext4 filesystem. But
3525 * that's fine - as long as they are linked from the inode, the post-crash
3526 * ext4_truncate() run will find them and release them.
3528 void ext4_truncate(struct inode *inode)
3530 trace_ext4_truncate_enter(inode);
3532 if (!ext4_can_truncate(inode))
3535 ext4_clear_inode_flag(inode, EXT4_INODE_EOFBLOCKS);
3537 if (inode->i_size == 0 && !test_opt(inode->i_sb, NO_AUTO_DA_ALLOC))
3538 ext4_set_inode_state(inode, EXT4_STATE_DA_ALLOC_CLOSE);
3540 if (ext4_has_inline_data(inode)) {
3543 ext4_inline_data_truncate(inode, &has_inline);
3548 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3549 ext4_ext_truncate(inode);
3551 ext4_ind_truncate(inode);
3553 trace_ext4_truncate_exit(inode);
3557 * ext4_get_inode_loc returns with an extra refcount against the inode's
3558 * underlying buffer_head on success. If 'in_mem' is true, we have all
3559 * data in memory that is needed to recreate the on-disk version of this
3562 static int __ext4_get_inode_loc(struct inode *inode,
3563 struct ext4_iloc *iloc, int in_mem)
3565 struct ext4_group_desc *gdp;
3566 struct buffer_head *bh;
3567 struct super_block *sb = inode->i_sb;
3569 int inodes_per_block, inode_offset;
3572 if (!ext4_valid_inum(sb, inode->i_ino))
3575 iloc->block_group = (inode->i_ino - 1) / EXT4_INODES_PER_GROUP(sb);
3576 gdp = ext4_get_group_desc(sb, iloc->block_group, NULL);
3581 * Figure out the offset within the block group inode table
3583 inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
3584 inode_offset = ((inode->i_ino - 1) %
3585 EXT4_INODES_PER_GROUP(sb));
3586 block = ext4_inode_table(sb, gdp) + (inode_offset / inodes_per_block);
3587 iloc->offset = (inode_offset % inodes_per_block) * EXT4_INODE_SIZE(sb);
3589 bh = sb_getblk(sb, block);
3592 if (!buffer_uptodate(bh)) {
3596 * If the buffer has the write error flag, we have failed
3597 * to write out another inode in the same block. In this
3598 * case, we don't have to read the block because we may
3599 * read the old inode data successfully.
3601 if (buffer_write_io_error(bh) && !buffer_uptodate(bh))
3602 set_buffer_uptodate(bh);
3604 if (buffer_uptodate(bh)) {
3605 /* someone brought it uptodate while we waited */
3611 * If we have all information of the inode in memory and this
3612 * is the only valid inode in the block, we need not read the
3616 struct buffer_head *bitmap_bh;
3619 start = inode_offset & ~(inodes_per_block - 1);
3621 /* Is the inode bitmap in cache? */
3622 bitmap_bh = sb_getblk(sb, ext4_inode_bitmap(sb, gdp));
3623 if (unlikely(!bitmap_bh))
3627 * If the inode bitmap isn't in cache then the
3628 * optimisation may end up performing two reads instead
3629 * of one, so skip it.
3631 if (!buffer_uptodate(bitmap_bh)) {
3635 for (i = start; i < start + inodes_per_block; i++) {
3636 if (i == inode_offset)
3638 if (ext4_test_bit(i, bitmap_bh->b_data))
3642 if (i == start + inodes_per_block) {
3643 /* all other inodes are free, so skip I/O */
3644 memset(bh->b_data, 0, bh->b_size);
3645 set_buffer_uptodate(bh);
3653 * If we need to do any I/O, try to pre-readahead extra
3654 * blocks from the inode table.
3656 if (EXT4_SB(sb)->s_inode_readahead_blks) {
3657 ext4_fsblk_t b, end, table;
3660 table = ext4_inode_table(sb, gdp);
3661 /* s_inode_readahead_blks is always a power of 2 */
3662 b = block & ~(EXT4_SB(sb)->s_inode_readahead_blks-1);
3665 end = b + EXT4_SB(sb)->s_inode_readahead_blks;
3666 num = EXT4_INODES_PER_GROUP(sb);
3667 if (ext4_has_group_desc_csum(sb))
3668 num -= ext4_itable_unused_count(sb, gdp);
3669 table += num / inodes_per_block;
3673 sb_breadahead(sb, b++);
3677 * There are other valid inodes in the buffer, this inode
3678 * has in-inode xattrs, or we don't have this inode in memory.
3679 * Read the block from disk.
3681 trace_ext4_load_inode(inode);
3683 bh->b_end_io = end_buffer_read_sync;
3684 submit_bh(READ | REQ_META | REQ_PRIO, bh);
3686 if (!buffer_uptodate(bh)) {
3687 EXT4_ERROR_INODE_BLOCK(inode, block,
3688 "unable to read itable block");
3698 int ext4_get_inode_loc(struct inode *inode, struct ext4_iloc *iloc)
3700 /* We have all inode data except xattrs in memory here. */
3701 return __ext4_get_inode_loc(inode, iloc,
3702 !ext4_test_inode_state(inode, EXT4_STATE_XATTR));
3705 void ext4_set_inode_flags(struct inode *inode)
3707 unsigned int flags = EXT4_I(inode)->i_flags;
3709 inode->i_flags &= ~(S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME|S_DIRSYNC);
3710 if (flags & EXT4_SYNC_FL)
3711 inode->i_flags |= S_SYNC;
3712 if (flags & EXT4_APPEND_FL)
3713 inode->i_flags |= S_APPEND;
3714 if (flags & EXT4_IMMUTABLE_FL)
3715 inode->i_flags |= S_IMMUTABLE;
3716 if (flags & EXT4_NOATIME_FL)
3717 inode->i_flags |= S_NOATIME;
3718 if (flags & EXT4_DIRSYNC_FL)
3719 inode->i_flags |= S_DIRSYNC;
3722 /* Propagate flags from i_flags to EXT4_I(inode)->i_flags */
3723 void ext4_get_inode_flags(struct ext4_inode_info *ei)
3725 unsigned int vfs_fl;
3726 unsigned long old_fl, new_fl;
3729 vfs_fl = ei->vfs_inode.i_flags;
3730 old_fl = ei->i_flags;
3731 new_fl = old_fl & ~(EXT4_SYNC_FL|EXT4_APPEND_FL|
3732 EXT4_IMMUTABLE_FL|EXT4_NOATIME_FL|
3734 if (vfs_fl & S_SYNC)
3735 new_fl |= EXT4_SYNC_FL;
3736 if (vfs_fl & S_APPEND)
3737 new_fl |= EXT4_APPEND_FL;
3738 if (vfs_fl & S_IMMUTABLE)
3739 new_fl |= EXT4_IMMUTABLE_FL;
3740 if (vfs_fl & S_NOATIME)
3741 new_fl |= EXT4_NOATIME_FL;
3742 if (vfs_fl & S_DIRSYNC)
3743 new_fl |= EXT4_DIRSYNC_FL;
3744 } while (cmpxchg(&ei->i_flags, old_fl, new_fl) != old_fl);
3747 static blkcnt_t ext4_inode_blocks(struct ext4_inode *raw_inode,
3748 struct ext4_inode_info *ei)
3751 struct inode *inode = &(ei->vfs_inode);
3752 struct super_block *sb = inode->i_sb;
3754 if (EXT4_HAS_RO_COMPAT_FEATURE(sb,
3755 EXT4_FEATURE_RO_COMPAT_HUGE_FILE)) {
3756 /* we are using combined 48 bit field */
3757 i_blocks = ((u64)le16_to_cpu(raw_inode->i_blocks_high)) << 32 |
3758 le32_to_cpu(raw_inode->i_blocks_lo);
3759 if (ext4_test_inode_flag(inode, EXT4_INODE_HUGE_FILE)) {
3760 /* i_blocks represent file system block size */
3761 return i_blocks << (inode->i_blkbits - 9);
3766 return le32_to_cpu(raw_inode->i_blocks_lo);
3770 static inline void ext4_iget_extra_inode(struct inode *inode,
3771 struct ext4_inode *raw_inode,
3772 struct ext4_inode_info *ei)
3774 __le32 *magic = (void *)raw_inode +
3775 EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize;
3776 if (*magic == cpu_to_le32(EXT4_XATTR_MAGIC)) {
3777 ext4_set_inode_state(inode, EXT4_STATE_XATTR);
3778 ext4_find_inline_data_nolock(inode);
3780 EXT4_I(inode)->i_inline_off = 0;
3783 struct inode *ext4_iget(struct super_block *sb, unsigned long ino)
3785 struct ext4_iloc iloc;
3786 struct ext4_inode *raw_inode;
3787 struct ext4_inode_info *ei;
3788 struct inode *inode;
3789 journal_t *journal = EXT4_SB(sb)->s_journal;
3795 inode = iget_locked(sb, ino);
3797 return ERR_PTR(-ENOMEM);
3798 if (!(inode->i_state & I_NEW))
3804 ret = __ext4_get_inode_loc(inode, &iloc, 0);
3807 raw_inode = ext4_raw_inode(&iloc);
3809 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
3810 ei->i_extra_isize = le16_to_cpu(raw_inode->i_extra_isize);
3811 if (EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize >
3812 EXT4_INODE_SIZE(inode->i_sb)) {
3813 EXT4_ERROR_INODE(inode, "bad extra_isize (%u != %u)",
3814 EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize,
3815 EXT4_INODE_SIZE(inode->i_sb));
3820 ei->i_extra_isize = 0;
3822 /* Precompute checksum seed for inode metadata */
3823 if (EXT4_HAS_RO_COMPAT_FEATURE(sb,
3824 EXT4_FEATURE_RO_COMPAT_METADATA_CSUM)) {
3825 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
3827 __le32 inum = cpu_to_le32(inode->i_ino);
3828 __le32 gen = raw_inode->i_generation;
3829 csum = ext4_chksum(sbi, sbi->s_csum_seed, (__u8 *)&inum,
3831 ei->i_csum_seed = ext4_chksum(sbi, csum, (__u8 *)&gen,
3835 if (!ext4_inode_csum_verify(inode, raw_inode, ei)) {
3836 EXT4_ERROR_INODE(inode, "checksum invalid");
3841 inode->i_mode = le16_to_cpu(raw_inode->i_mode);
3842 i_uid = (uid_t)le16_to_cpu(raw_inode->i_uid_low);
3843 i_gid = (gid_t)le16_to_cpu(raw_inode->i_gid_low);
3844 if (!(test_opt(inode->i_sb, NO_UID32))) {
3845 i_uid |= le16_to_cpu(raw_inode->i_uid_high) << 16;
3846 i_gid |= le16_to_cpu(raw_inode->i_gid_high) << 16;
3848 i_uid_write(inode, i_uid);
3849 i_gid_write(inode, i_gid);
3850 set_nlink(inode, le16_to_cpu(raw_inode->i_links_count));
3852 ext4_clear_state_flags(ei); /* Only relevant on 32-bit archs */
3853 ei->i_inline_off = 0;
3854 ei->i_dir_start_lookup = 0;
3855 ei->i_dtime = le32_to_cpu(raw_inode->i_dtime);
3856 /* We now have enough fields to check if the inode was active or not.
3857 * This is needed because nfsd might try to access dead inodes
3858 * the test is that same one that e2fsck uses
3859 * NeilBrown 1999oct15
3861 if (inode->i_nlink == 0) {
3862 if (inode->i_mode == 0 ||
3863 !(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_ORPHAN_FS)) {
3864 /* this inode is deleted */
3868 /* The only unlinked inodes we let through here have
3869 * valid i_mode and are being read by the orphan
3870 * recovery code: that's fine, we're about to complete
3871 * the process of deleting those. */
3873 ei->i_flags = le32_to_cpu(raw_inode->i_flags);
3874 inode->i_blocks = ext4_inode_blocks(raw_inode, ei);
3875 ei->i_file_acl = le32_to_cpu(raw_inode->i_file_acl_lo);
3876 if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_64BIT))
3878 ((__u64)le16_to_cpu(raw_inode->i_file_acl_high)) << 32;
3879 inode->i_size = ext4_isize(raw_inode);
3880 ei->i_disksize = inode->i_size;
3882 ei->i_reserved_quota = 0;
3884 inode->i_generation = le32_to_cpu(raw_inode->i_generation);
3885 ei->i_block_group = iloc.block_group;
3886 ei->i_last_alloc_group = ~0;
3888 * NOTE! The in-memory inode i_data array is in little-endian order
3889 * even on big-endian machines: we do NOT byteswap the block numbers!
3891 for (block = 0; block < EXT4_N_BLOCKS; block++)
3892 ei->i_data[block] = raw_inode->i_block[block];
3893 INIT_LIST_HEAD(&ei->i_orphan);
3896 * Set transaction id's of transactions that have to be committed
3897 * to finish f[data]sync. We set them to currently running transaction
3898 * as we cannot be sure that the inode or some of its metadata isn't
3899 * part of the transaction - the inode could have been reclaimed and
3900 * now it is reread from disk.
3903 transaction_t *transaction;
3906 read_lock(&journal->j_state_lock);
3907 if (journal->j_running_transaction)
3908 transaction = journal->j_running_transaction;
3910 transaction = journal->j_committing_transaction;
3912 tid = transaction->t_tid;
3914 tid = journal->j_commit_sequence;
3915 read_unlock(&journal->j_state_lock);
3916 ei->i_sync_tid = tid;
3917 ei->i_datasync_tid = tid;
3920 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
3921 if (ei->i_extra_isize == 0) {
3922 /* The extra space is currently unused. Use it. */
3923 ei->i_extra_isize = sizeof(struct ext4_inode) -
3924 EXT4_GOOD_OLD_INODE_SIZE;
3926 ext4_iget_extra_inode(inode, raw_inode, ei);
3930 EXT4_INODE_GET_XTIME(i_ctime, inode, raw_inode);
3931 EXT4_INODE_GET_XTIME(i_mtime, inode, raw_inode);
3932 EXT4_INODE_GET_XTIME(i_atime, inode, raw_inode);
3933 EXT4_EINODE_GET_XTIME(i_crtime, ei, raw_inode);
3935 inode->i_version = le32_to_cpu(raw_inode->i_disk_version);
3936 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
3937 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
3939 (__u64)(le32_to_cpu(raw_inode->i_version_hi)) << 32;
3943 if (ei->i_file_acl &&
3944 !ext4_data_block_valid(EXT4_SB(sb), ei->i_file_acl, 1)) {
3945 EXT4_ERROR_INODE(inode, "bad extended attribute block %llu",
3949 } else if (!ext4_has_inline_data(inode)) {
3950 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
3951 if ((S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
3952 (S_ISLNK(inode->i_mode) &&
3953 !ext4_inode_is_fast_symlink(inode))))
3954 /* Validate extent which is part of inode */
3955 ret = ext4_ext_check_inode(inode);
3956 } else if (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
3957 (S_ISLNK(inode->i_mode) &&
3958 !ext4_inode_is_fast_symlink(inode))) {
3959 /* Validate block references which are part of inode */
3960 ret = ext4_ind_check_inode(inode);
3966 if (S_ISREG(inode->i_mode)) {
3967 inode->i_op = &ext4_file_inode_operations;
3968 inode->i_fop = &ext4_file_operations;
3969 ext4_set_aops(inode);
3970 } else if (S_ISDIR(inode->i_mode)) {
3971 inode->i_op = &ext4_dir_inode_operations;
3972 inode->i_fop = &ext4_dir_operations;
3973 } else if (S_ISLNK(inode->i_mode)) {
3974 if (ext4_inode_is_fast_symlink(inode)) {
3975 inode->i_op = &ext4_fast_symlink_inode_operations;
3976 nd_terminate_link(ei->i_data, inode->i_size,
3977 sizeof(ei->i_data) - 1);
3979 inode->i_op = &ext4_symlink_inode_operations;
3980 ext4_set_aops(inode);
3982 } else if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode) ||
3983 S_ISFIFO(inode->i_mode) || S_ISSOCK(inode->i_mode)) {
3984 inode->i_op = &ext4_special_inode_operations;
3985 if (raw_inode->i_block[0])
3986 init_special_inode(inode, inode->i_mode,
3987 old_decode_dev(le32_to_cpu(raw_inode->i_block[0])));
3989 init_special_inode(inode, inode->i_mode,
3990 new_decode_dev(le32_to_cpu(raw_inode->i_block[1])));
3993 EXT4_ERROR_INODE(inode, "bogus i_mode (%o)", inode->i_mode);
3997 ext4_set_inode_flags(inode);
3998 unlock_new_inode(inode);
4004 return ERR_PTR(ret);
4007 static int ext4_inode_blocks_set(handle_t *handle,
4008 struct ext4_inode *raw_inode,
4009 struct ext4_inode_info *ei)
4011 struct inode *inode = &(ei->vfs_inode);
4012 u64 i_blocks = inode->i_blocks;
4013 struct super_block *sb = inode->i_sb;
4015 if (i_blocks <= ~0U) {
4017 * i_blocks can be represented in a 32 bit variable
4018 * as multiple of 512 bytes
4020 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
4021 raw_inode->i_blocks_high = 0;
4022 ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
4025 if (!EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_HUGE_FILE))
4028 if (i_blocks <= 0xffffffffffffULL) {
4030 * i_blocks can be represented in a 48 bit variable
4031 * as multiple of 512 bytes
4033 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
4034 raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
4035 ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
4037 ext4_set_inode_flag(inode, EXT4_INODE_HUGE_FILE);
4038 /* i_block is stored in file system block size */
4039 i_blocks = i_blocks >> (inode->i_blkbits - 9);
4040 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
4041 raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
4047 * Post the struct inode info into an on-disk inode location in the
4048 * buffer-cache. This gobbles the caller's reference to the
4049 * buffer_head in the inode location struct.
4051 * The caller must have write access to iloc->bh.
4053 static int ext4_do_update_inode(handle_t *handle,
4054 struct inode *inode,
4055 struct ext4_iloc *iloc)
4057 struct ext4_inode *raw_inode = ext4_raw_inode(iloc);
4058 struct ext4_inode_info *ei = EXT4_I(inode);
4059 struct buffer_head *bh = iloc->bh;
4060 int err = 0, rc, block;
4061 int need_datasync = 0;
4065 /* For fields not not tracking in the in-memory inode,
4066 * initialise them to zero for new inodes. */
4067 if (ext4_test_inode_state(inode, EXT4_STATE_NEW))
4068 memset(raw_inode, 0, EXT4_SB(inode->i_sb)->s_inode_size);
4070 ext4_get_inode_flags(ei);
4071 raw_inode->i_mode = cpu_to_le16(inode->i_mode);
4072 i_uid = i_uid_read(inode);
4073 i_gid = i_gid_read(inode);
4074 if (!(test_opt(inode->i_sb, NO_UID32))) {
4075 raw_inode->i_uid_low = cpu_to_le16(low_16_bits(i_uid));
4076 raw_inode->i_gid_low = cpu_to_le16(low_16_bits(i_gid));
4078 * Fix up interoperability with old kernels. Otherwise, old inodes get
4079 * re-used with the upper 16 bits of the uid/gid intact
4082 raw_inode->i_uid_high =
4083 cpu_to_le16(high_16_bits(i_uid));
4084 raw_inode->i_gid_high =
4085 cpu_to_le16(high_16_bits(i_gid));
4087 raw_inode->i_uid_high = 0;
4088 raw_inode->i_gid_high = 0;
4091 raw_inode->i_uid_low = cpu_to_le16(fs_high2lowuid(i_uid));
4092 raw_inode->i_gid_low = cpu_to_le16(fs_high2lowgid(i_gid));
4093 raw_inode->i_uid_high = 0;
4094 raw_inode->i_gid_high = 0;
4096 raw_inode->i_links_count = cpu_to_le16(inode->i_nlink);
4098 EXT4_INODE_SET_XTIME(i_ctime, inode, raw_inode);
4099 EXT4_INODE_SET_XTIME(i_mtime, inode, raw_inode);
4100 EXT4_INODE_SET_XTIME(i_atime, inode, raw_inode);
4101 EXT4_EINODE_SET_XTIME(i_crtime, ei, raw_inode);
4103 if (ext4_inode_blocks_set(handle, raw_inode, ei))
4105 raw_inode->i_dtime = cpu_to_le32(ei->i_dtime);
4106 raw_inode->i_flags = cpu_to_le32(ei->i_flags & 0xFFFFFFFF);
4107 if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
4108 cpu_to_le32(EXT4_OS_HURD))
4109 raw_inode->i_file_acl_high =
4110 cpu_to_le16(ei->i_file_acl >> 32);
4111 raw_inode->i_file_acl_lo = cpu_to_le32(ei->i_file_acl);
4112 if (ei->i_disksize != ext4_isize(raw_inode)) {
4113 ext4_isize_set(raw_inode, ei->i_disksize);
4116 if (ei->i_disksize > 0x7fffffffULL) {
4117 struct super_block *sb = inode->i_sb;
4118 if (!EXT4_HAS_RO_COMPAT_FEATURE(sb,
4119 EXT4_FEATURE_RO_COMPAT_LARGE_FILE) ||
4120 EXT4_SB(sb)->s_es->s_rev_level ==
4121 cpu_to_le32(EXT4_GOOD_OLD_REV)) {
4122 /* If this is the first large file
4123 * created, add a flag to the superblock.
4125 err = ext4_journal_get_write_access(handle,
4126 EXT4_SB(sb)->s_sbh);
4129 ext4_update_dynamic_rev(sb);
4130 EXT4_SET_RO_COMPAT_FEATURE(sb,
4131 EXT4_FEATURE_RO_COMPAT_LARGE_FILE);
4132 ext4_handle_sync(handle);
4133 err = ext4_handle_dirty_super(handle, sb);
4136 raw_inode->i_generation = cpu_to_le32(inode->i_generation);
4137 if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) {
4138 if (old_valid_dev(inode->i_rdev)) {
4139 raw_inode->i_block[0] =
4140 cpu_to_le32(old_encode_dev(inode->i_rdev));
4141 raw_inode->i_block[1] = 0;
4143 raw_inode->i_block[0] = 0;
4144 raw_inode->i_block[1] =
4145 cpu_to_le32(new_encode_dev(inode->i_rdev));
4146 raw_inode->i_block[2] = 0;
4148 } else if (!ext4_has_inline_data(inode)) {
4149 for (block = 0; block < EXT4_N_BLOCKS; block++)
4150 raw_inode->i_block[block] = ei->i_data[block];
4153 raw_inode->i_disk_version = cpu_to_le32(inode->i_version);
4154 if (ei->i_extra_isize) {
4155 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
4156 raw_inode->i_version_hi =
4157 cpu_to_le32(inode->i_version >> 32);
4158 raw_inode->i_extra_isize = cpu_to_le16(ei->i_extra_isize);
4161 ext4_inode_csum_set(inode, raw_inode, ei);
4163 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
4164 rc = ext4_handle_dirty_metadata(handle, NULL, bh);
4167 ext4_clear_inode_state(inode, EXT4_STATE_NEW);
4169 ext4_update_inode_fsync_trans(handle, inode, need_datasync);
4172 ext4_std_error(inode->i_sb, err);
4177 * ext4_write_inode()
4179 * We are called from a few places:
4181 * - Within generic_file_write() for O_SYNC files.
4182 * Here, there will be no transaction running. We wait for any running
4183 * transaction to commit.
4185 * - Within sys_sync(), kupdate and such.
4186 * We wait on commit, if tol to.
4188 * - Within prune_icache() (PF_MEMALLOC == true)
4189 * Here we simply return. We can't afford to block kswapd on the
4192 * In all cases it is actually safe for us to return without doing anything,
4193 * because the inode has been copied into a raw inode buffer in
4194 * ext4_mark_inode_dirty(). This is a correctness thing for O_SYNC and for
4197 * Note that we are absolutely dependent upon all inode dirtiers doing the
4198 * right thing: they *must* call mark_inode_dirty() after dirtying info in
4199 * which we are interested.
4201 * It would be a bug for them to not do this. The code:
4203 * mark_inode_dirty(inode)
4205 * inode->i_size = expr;
4207 * is in error because a kswapd-driven write_inode() could occur while
4208 * `stuff()' is running, and the new i_size will be lost. Plus the inode
4209 * will no longer be on the superblock's dirty inode list.
4211 int ext4_write_inode(struct inode *inode, struct writeback_control *wbc)
4215 if (current->flags & PF_MEMALLOC)
4218 if (EXT4_SB(inode->i_sb)->s_journal) {
4219 if (ext4_journal_current_handle()) {
4220 jbd_debug(1, "called recursively, non-PF_MEMALLOC!\n");
4225 if (wbc->sync_mode != WB_SYNC_ALL)
4228 err = ext4_force_commit(inode->i_sb);
4230 struct ext4_iloc iloc;
4232 err = __ext4_get_inode_loc(inode, &iloc, 0);
4235 if (wbc->sync_mode == WB_SYNC_ALL)
4236 sync_dirty_buffer(iloc.bh);
4237 if (buffer_req(iloc.bh) && !buffer_uptodate(iloc.bh)) {
4238 EXT4_ERROR_INODE_BLOCK(inode, iloc.bh->b_blocknr,
4239 "IO error syncing inode");
4248 * In data=journal mode ext4_journalled_invalidatepage() may fail to invalidate
4249 * buffers that are attached to a page stradding i_size and are undergoing
4250 * commit. In that case we have to wait for commit to finish and try again.
4252 static void ext4_wait_for_tail_page_commit(struct inode *inode)
4256 journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
4257 tid_t commit_tid = 0;
4260 offset = inode->i_size & (PAGE_CACHE_SIZE - 1);
4262 * All buffers in the last page remain valid? Then there's nothing to
4263 * do. We do the check mainly to optimize the common PAGE_CACHE_SIZE ==
4266 if (offset > PAGE_CACHE_SIZE - (1 << inode->i_blkbits))
4269 page = find_lock_page(inode->i_mapping,
4270 inode->i_size >> PAGE_CACHE_SHIFT);
4273 ret = __ext4_journalled_invalidatepage(page, offset);
4275 page_cache_release(page);
4279 read_lock(&journal->j_state_lock);
4280 if (journal->j_committing_transaction)
4281 commit_tid = journal->j_committing_transaction->t_tid;
4282 read_unlock(&journal->j_state_lock);
4284 jbd2_log_wait_commit(journal, commit_tid);
4291 * Called from notify_change.
4293 * We want to trap VFS attempts to truncate the file as soon as
4294 * possible. In particular, we want to make sure that when the VFS
4295 * shrinks i_size, we put the inode on the orphan list and modify
4296 * i_disksize immediately, so that during the subsequent flushing of
4297 * dirty pages and freeing of disk blocks, we can guarantee that any
4298 * commit will leave the blocks being flushed in an unused state on
4299 * disk. (On recovery, the inode will get truncated and the blocks will
4300 * be freed, so we have a strong guarantee that no future commit will
4301 * leave these blocks visible to the user.)
4303 * Another thing we have to assure is that if we are in ordered mode
4304 * and inode is still attached to the committing transaction, we must
4305 * we start writeout of all the dirty pages which are being truncated.
4306 * This way we are sure that all the data written in the previous
4307 * transaction are already on disk (truncate waits for pages under
4310 * Called with inode->i_mutex down.
4312 int ext4_setattr(struct dentry *dentry, struct iattr *attr)
4314 struct inode *inode = dentry->d_inode;
4317 const unsigned int ia_valid = attr->ia_valid;
4319 error = inode_change_ok(inode, attr);
4323 if (is_quota_modification(inode, attr))
4324 dquot_initialize(inode);
4325 if ((ia_valid & ATTR_UID && !uid_eq(attr->ia_uid, inode->i_uid)) ||
4326 (ia_valid & ATTR_GID && !gid_eq(attr->ia_gid, inode->i_gid))) {
4329 /* (user+group)*(old+new) structure, inode write (sb,
4330 * inode block, ? - but truncate inode update has it) */
4331 handle = ext4_journal_start(inode, EXT4_HT_QUOTA,
4332 (EXT4_MAXQUOTAS_INIT_BLOCKS(inode->i_sb) +
4333 EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb)) + 3);
4334 if (IS_ERR(handle)) {
4335 error = PTR_ERR(handle);
4338 error = dquot_transfer(inode, attr);
4340 ext4_journal_stop(handle);
4343 /* Update corresponding info in inode so that everything is in
4344 * one transaction */
4345 if (attr->ia_valid & ATTR_UID)
4346 inode->i_uid = attr->ia_uid;
4347 if (attr->ia_valid & ATTR_GID)
4348 inode->i_gid = attr->ia_gid;
4349 error = ext4_mark_inode_dirty(handle, inode);
4350 ext4_journal_stop(handle);
4353 if (attr->ia_valid & ATTR_SIZE) {
4355 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
4356 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4358 if (attr->ia_size > sbi->s_bitmap_maxbytes)
4363 if (S_ISREG(inode->i_mode) &&
4364 attr->ia_valid & ATTR_SIZE &&
4365 (attr->ia_size < inode->i_size)) {
4368 handle = ext4_journal_start(inode, EXT4_HT_INODE, 3);
4369 if (IS_ERR(handle)) {
4370 error = PTR_ERR(handle);
4373 if (ext4_handle_valid(handle)) {
4374 error = ext4_orphan_add(handle, inode);
4377 EXT4_I(inode)->i_disksize = attr->ia_size;
4378 rc = ext4_mark_inode_dirty(handle, inode);
4381 ext4_journal_stop(handle);
4383 if (ext4_should_order_data(inode)) {
4384 error = ext4_begin_ordered_truncate(inode,
4387 /* Do as much error cleanup as possible */
4388 handle = ext4_journal_start(inode,
4390 if (IS_ERR(handle)) {
4391 ext4_orphan_del(NULL, inode);
4394 ext4_orphan_del(handle, inode);
4396 ext4_journal_stop(handle);
4402 if (attr->ia_valid & ATTR_SIZE) {
4403 if (attr->ia_size != inode->i_size) {
4404 loff_t oldsize = inode->i_size;
4406 i_size_write(inode, attr->ia_size);
4408 * Blocks are going to be removed from the inode. Wait
4409 * for dio in flight. Temporarily disable
4410 * dioread_nolock to prevent livelock.
4413 if (!ext4_should_journal_data(inode)) {
4414 ext4_inode_block_unlocked_dio(inode);
4415 inode_dio_wait(inode);
4416 ext4_inode_resume_unlocked_dio(inode);
4418 ext4_wait_for_tail_page_commit(inode);
4421 * Truncate pagecache after we've waited for commit
4422 * in data=journal mode to make pages freeable.
4424 truncate_pagecache(inode, oldsize, inode->i_size);
4426 ext4_truncate(inode);
4430 setattr_copy(inode, attr);
4431 mark_inode_dirty(inode);
4435 * If the call to ext4_truncate failed to get a transaction handle at
4436 * all, we need to clean up the in-core orphan list manually.
4438 if (orphan && inode->i_nlink)
4439 ext4_orphan_del(NULL, inode);
4441 if (!rc && (ia_valid & ATTR_MODE))
4442 rc = ext4_acl_chmod(inode);
4445 ext4_std_error(inode->i_sb, error);
4451 int ext4_getattr(struct vfsmount *mnt, struct dentry *dentry,
4454 struct inode *inode;
4455 unsigned long delalloc_blocks;
4457 inode = dentry->d_inode;
4458 generic_fillattr(inode, stat);
4461 * We can't update i_blocks if the block allocation is delayed
4462 * otherwise in the case of system crash before the real block
4463 * allocation is done, we will have i_blocks inconsistent with
4464 * on-disk file blocks.
4465 * We always keep i_blocks updated together with real
4466 * allocation. But to not confuse with user, stat
4467 * will return the blocks that include the delayed allocation
4468 * blocks for this file.
4470 delalloc_blocks = EXT4_C2B(EXT4_SB(inode->i_sb),
4471 EXT4_I(inode)->i_reserved_data_blocks);
4473 stat->blocks += (delalloc_blocks << inode->i_sb->s_blocksize_bits)>>9;
4477 static int ext4_index_trans_blocks(struct inode *inode, int nrblocks, int chunk)
4479 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
4480 return ext4_ind_trans_blocks(inode, nrblocks, chunk);
4481 return ext4_ext_index_trans_blocks(inode, nrblocks, chunk);
4485 * Account for index blocks, block groups bitmaps and block group
4486 * descriptor blocks if modify datablocks and index blocks
4487 * worse case, the indexs blocks spread over different block groups
4489 * If datablocks are discontiguous, they are possible to spread over
4490 * different block groups too. If they are contiguous, with flexbg,
4491 * they could still across block group boundary.
4493 * Also account for superblock, inode, quota and xattr blocks
4495 static int ext4_meta_trans_blocks(struct inode *inode, int nrblocks, int chunk)
4497 ext4_group_t groups, ngroups = ext4_get_groups_count(inode->i_sb);
4503 * How many index blocks need to touch to modify nrblocks?
4504 * The "Chunk" flag indicating whether the nrblocks is
4505 * physically contiguous on disk
4507 * For Direct IO and fallocate, they calls get_block to allocate
4508 * one single extent at a time, so they could set the "Chunk" flag
4510 idxblocks = ext4_index_trans_blocks(inode, nrblocks, chunk);
4515 * Now let's see how many group bitmaps and group descriptors need
4525 if (groups > ngroups)
4527 if (groups > EXT4_SB(inode->i_sb)->s_gdb_count)
4528 gdpblocks = EXT4_SB(inode->i_sb)->s_gdb_count;
4530 /* bitmaps and block group descriptor blocks */
4531 ret += groups + gdpblocks;
4533 /* Blocks for super block, inode, quota and xattr blocks */
4534 ret += EXT4_META_TRANS_BLOCKS(inode->i_sb);
4540 * Calculate the total number of credits to reserve to fit
4541 * the modification of a single pages into a single transaction,
4542 * which may include multiple chunks of block allocations.
4544 * This could be called via ext4_write_begin()
4546 * We need to consider the worse case, when
4547 * one new block per extent.
4549 int ext4_writepage_trans_blocks(struct inode *inode)
4551 int bpp = ext4_journal_blocks_per_page(inode);
4554 ret = ext4_meta_trans_blocks(inode, bpp, 0);
4556 /* Account for data blocks for journalled mode */
4557 if (ext4_should_journal_data(inode))
4563 * Calculate the journal credits for a chunk of data modification.
4565 * This is called from DIO, fallocate or whoever calling
4566 * ext4_map_blocks() to map/allocate a chunk of contiguous disk blocks.
4568 * journal buffers for data blocks are not included here, as DIO
4569 * and fallocate do no need to journal data buffers.
4571 int ext4_chunk_trans_blocks(struct inode *inode, int nrblocks)
4573 return ext4_meta_trans_blocks(inode, nrblocks, 1);
4577 * The caller must have previously called ext4_reserve_inode_write().
4578 * Give this, we know that the caller already has write access to iloc->bh.
4580 int ext4_mark_iloc_dirty(handle_t *handle,
4581 struct inode *inode, struct ext4_iloc *iloc)
4585 if (IS_I_VERSION(inode))
4586 inode_inc_iversion(inode);
4588 /* the do_update_inode consumes one bh->b_count */
4591 /* ext4_do_update_inode() does jbd2_journal_dirty_metadata */
4592 err = ext4_do_update_inode(handle, inode, iloc);
4598 * On success, We end up with an outstanding reference count against
4599 * iloc->bh. This _must_ be cleaned up later.
4603 ext4_reserve_inode_write(handle_t *handle, struct inode *inode,
4604 struct ext4_iloc *iloc)
4608 err = ext4_get_inode_loc(inode, iloc);
4610 BUFFER_TRACE(iloc->bh, "get_write_access");
4611 err = ext4_journal_get_write_access(handle, iloc->bh);
4617 ext4_std_error(inode->i_sb, err);
4622 * Expand an inode by new_extra_isize bytes.
4623 * Returns 0 on success or negative error number on failure.
4625 static int ext4_expand_extra_isize(struct inode *inode,
4626 unsigned int new_extra_isize,
4627 struct ext4_iloc iloc,
4630 struct ext4_inode *raw_inode;
4631 struct ext4_xattr_ibody_header *header;
4633 if (EXT4_I(inode)->i_extra_isize >= new_extra_isize)
4636 raw_inode = ext4_raw_inode(&iloc);
4638 header = IHDR(inode, raw_inode);
4640 /* No extended attributes present */
4641 if (!ext4_test_inode_state(inode, EXT4_STATE_XATTR) ||
4642 header->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC)) {
4643 memset((void *)raw_inode + EXT4_GOOD_OLD_INODE_SIZE, 0,
4645 EXT4_I(inode)->i_extra_isize = new_extra_isize;
4649 /* try to expand with EAs present */
4650 return ext4_expand_extra_isize_ea(inode, new_extra_isize,
4655 * What we do here is to mark the in-core inode as clean with respect to inode
4656 * dirtiness (it may still be data-dirty).
4657 * This means that the in-core inode may be reaped by prune_icache
4658 * without having to perform any I/O. This is a very good thing,
4659 * because *any* task may call prune_icache - even ones which
4660 * have a transaction open against a different journal.
4662 * Is this cheating? Not really. Sure, we haven't written the
4663 * inode out, but prune_icache isn't a user-visible syncing function.
4664 * Whenever the user wants stuff synced (sys_sync, sys_msync, sys_fsync)
4665 * we start and wait on commits.
4667 int ext4_mark_inode_dirty(handle_t *handle, struct inode *inode)
4669 struct ext4_iloc iloc;
4670 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4671 static unsigned int mnt_count;
4675 trace_ext4_mark_inode_dirty(inode, _RET_IP_);
4676 err = ext4_reserve_inode_write(handle, inode, &iloc);
4677 if (ext4_handle_valid(handle) &&
4678 EXT4_I(inode)->i_extra_isize < sbi->s_want_extra_isize &&
4679 !ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND)) {
4681 * We need extra buffer credits since we may write into EA block
4682 * with this same handle. If journal_extend fails, then it will
4683 * only result in a minor loss of functionality for that inode.
4684 * If this is felt to be critical, then e2fsck should be run to
4685 * force a large enough s_min_extra_isize.
4687 if ((jbd2_journal_extend(handle,
4688 EXT4_DATA_TRANS_BLOCKS(inode->i_sb))) == 0) {
4689 ret = ext4_expand_extra_isize(inode,
4690 sbi->s_want_extra_isize,
4693 ext4_set_inode_state(inode,
4694 EXT4_STATE_NO_EXPAND);
4696 le16_to_cpu(sbi->s_es->s_mnt_count)) {
4697 ext4_warning(inode->i_sb,
4698 "Unable to expand inode %lu. Delete"
4699 " some EAs or run e2fsck.",
4702 le16_to_cpu(sbi->s_es->s_mnt_count);
4708 err = ext4_mark_iloc_dirty(handle, inode, &iloc);
4713 * ext4_dirty_inode() is called from __mark_inode_dirty()
4715 * We're really interested in the case where a file is being extended.
4716 * i_size has been changed by generic_commit_write() and we thus need
4717 * to include the updated inode in the current transaction.
4719 * Also, dquot_alloc_block() will always dirty the inode when blocks
4720 * are allocated to the file.
4722 * If the inode is marked synchronous, we don't honour that here - doing
4723 * so would cause a commit on atime updates, which we don't bother doing.
4724 * We handle synchronous inodes at the highest possible level.
4726 void ext4_dirty_inode(struct inode *inode, int flags)
4730 handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
4734 ext4_mark_inode_dirty(handle, inode);
4736 ext4_journal_stop(handle);
4743 * Bind an inode's backing buffer_head into this transaction, to prevent
4744 * it from being flushed to disk early. Unlike
4745 * ext4_reserve_inode_write, this leaves behind no bh reference and
4746 * returns no iloc structure, so the caller needs to repeat the iloc
4747 * lookup to mark the inode dirty later.
4749 static int ext4_pin_inode(handle_t *handle, struct inode *inode)
4751 struct ext4_iloc iloc;
4755 err = ext4_get_inode_loc(inode, &iloc);
4757 BUFFER_TRACE(iloc.bh, "get_write_access");
4758 err = jbd2_journal_get_write_access(handle, iloc.bh);
4760 err = ext4_handle_dirty_metadata(handle,
4766 ext4_std_error(inode->i_sb, err);
4771 int ext4_change_inode_journal_flag(struct inode *inode, int val)
4778 * We have to be very careful here: changing a data block's
4779 * journaling status dynamically is dangerous. If we write a
4780 * data block to the journal, change the status and then delete
4781 * that block, we risk forgetting to revoke the old log record
4782 * from the journal and so a subsequent replay can corrupt data.
4783 * So, first we make sure that the journal is empty and that
4784 * nobody is changing anything.
4787 journal = EXT4_JOURNAL(inode);
4790 if (is_journal_aborted(journal))
4792 /* We have to allocate physical blocks for delalloc blocks
4793 * before flushing journal. otherwise delalloc blocks can not
4794 * be allocated any more. even more truncate on delalloc blocks
4795 * could trigger BUG by flushing delalloc blocks in journal.
4796 * There is no delalloc block in non-journal data mode.
4798 if (val && test_opt(inode->i_sb, DELALLOC)) {
4799 err = ext4_alloc_da_blocks(inode);
4804 /* Wait for all existing dio workers */
4805 ext4_inode_block_unlocked_dio(inode);
4806 inode_dio_wait(inode);
4808 jbd2_journal_lock_updates(journal);
4811 * OK, there are no updates running now, and all cached data is
4812 * synced to disk. We are now in a completely consistent state
4813 * which doesn't have anything in the journal, and we know that
4814 * no filesystem updates are running, so it is safe to modify
4815 * the inode's in-core data-journaling state flag now.
4819 ext4_set_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
4821 jbd2_journal_flush(journal);
4822 ext4_clear_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
4824 ext4_set_aops(inode);
4826 jbd2_journal_unlock_updates(journal);
4827 ext4_inode_resume_unlocked_dio(inode);
4829 /* Finally we can mark the inode as dirty. */
4831 handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
4833 return PTR_ERR(handle);
4835 err = ext4_mark_inode_dirty(handle, inode);
4836 ext4_handle_sync(handle);
4837 ext4_journal_stop(handle);
4838 ext4_std_error(inode->i_sb, err);
4843 static int ext4_bh_unmapped(handle_t *handle, struct buffer_head *bh)
4845 return !buffer_mapped(bh);
4848 int ext4_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
4850 struct page *page = vmf->page;
4854 struct file *file = vma->vm_file;
4855 struct inode *inode = file->f_path.dentry->d_inode;
4856 struct address_space *mapping = inode->i_mapping;
4858 get_block_t *get_block;
4861 sb_start_pagefault(inode->i_sb);
4862 file_update_time(vma->vm_file);
4863 /* Delalloc case is easy... */
4864 if (test_opt(inode->i_sb, DELALLOC) &&
4865 !ext4_should_journal_data(inode) &&
4866 !ext4_nonda_switch(inode->i_sb)) {
4868 ret = __block_page_mkwrite(vma, vmf,
4869 ext4_da_get_block_prep);
4870 } while (ret == -ENOSPC &&
4871 ext4_should_retry_alloc(inode->i_sb, &retries));
4876 size = i_size_read(inode);
4877 /* Page got truncated from under us? */
4878 if (page->mapping != mapping || page_offset(page) > size) {
4880 ret = VM_FAULT_NOPAGE;
4884 if (page->index == size >> PAGE_CACHE_SHIFT)
4885 len = size & ~PAGE_CACHE_MASK;
4887 len = PAGE_CACHE_SIZE;
4889 * Return if we have all the buffers mapped. This avoids the need to do
4890 * journal_start/journal_stop which can block and take a long time
4892 if (page_has_buffers(page)) {
4893 if (!ext4_walk_page_buffers(NULL, page_buffers(page),
4895 ext4_bh_unmapped)) {
4896 /* Wait so that we don't change page under IO */
4897 wait_for_stable_page(page);
4898 ret = VM_FAULT_LOCKED;
4903 /* OK, we need to fill the hole... */
4904 if (ext4_should_dioread_nolock(inode))
4905 get_block = ext4_get_block_write;
4907 get_block = ext4_get_block;
4909 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
4910 ext4_writepage_trans_blocks(inode));
4911 if (IS_ERR(handle)) {
4912 ret = VM_FAULT_SIGBUS;
4915 ret = __block_page_mkwrite(vma, vmf, get_block);
4916 if (!ret && ext4_should_journal_data(inode)) {
4917 if (ext4_walk_page_buffers(handle, page_buffers(page), 0,
4918 PAGE_CACHE_SIZE, NULL, do_journal_get_write_access)) {
4920 ret = VM_FAULT_SIGBUS;
4921 ext4_journal_stop(handle);
4924 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
4926 ext4_journal_stop(handle);
4927 if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
4930 ret = block_page_mkwrite_return(ret);
4932 sb_end_pagefault(inode->i_sb);