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>
41 #include <linux/bitops.h>
43 #include "ext4_jbd2.h"
48 #include <trace/events/ext4.h>
50 #define MPAGE_DA_EXTENT_TAIL 0x01
52 static __u32 ext4_inode_csum(struct inode *inode, struct ext4_inode *raw,
53 struct ext4_inode_info *ei)
55 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
60 csum_lo = le16_to_cpu(raw->i_checksum_lo);
61 raw->i_checksum_lo = 0;
62 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
63 EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi)) {
64 csum_hi = le16_to_cpu(raw->i_checksum_hi);
65 raw->i_checksum_hi = 0;
68 csum = ext4_chksum(sbi, ei->i_csum_seed, (__u8 *)raw,
69 EXT4_INODE_SIZE(inode->i_sb));
71 raw->i_checksum_lo = cpu_to_le16(csum_lo);
72 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
73 EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi))
74 raw->i_checksum_hi = cpu_to_le16(csum_hi);
79 static int ext4_inode_csum_verify(struct inode *inode, struct ext4_inode *raw,
80 struct ext4_inode_info *ei)
82 __u32 provided, calculated;
84 if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
85 cpu_to_le32(EXT4_OS_LINUX) ||
86 !EXT4_HAS_RO_COMPAT_FEATURE(inode->i_sb,
87 EXT4_FEATURE_RO_COMPAT_METADATA_CSUM))
90 provided = le16_to_cpu(raw->i_checksum_lo);
91 calculated = ext4_inode_csum(inode, raw, ei);
92 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
93 EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi))
94 provided |= ((__u32)le16_to_cpu(raw->i_checksum_hi)) << 16;
98 return provided == calculated;
101 static void ext4_inode_csum_set(struct inode *inode, struct ext4_inode *raw,
102 struct ext4_inode_info *ei)
106 if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
107 cpu_to_le32(EXT4_OS_LINUX) ||
108 !EXT4_HAS_RO_COMPAT_FEATURE(inode->i_sb,
109 EXT4_FEATURE_RO_COMPAT_METADATA_CSUM))
112 csum = ext4_inode_csum(inode, raw, ei);
113 raw->i_checksum_lo = cpu_to_le16(csum & 0xFFFF);
114 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
115 EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi))
116 raw->i_checksum_hi = cpu_to_le16(csum >> 16);
119 static inline int ext4_begin_ordered_truncate(struct inode *inode,
122 trace_ext4_begin_ordered_truncate(inode, new_size);
124 * If jinode is zero, then we never opened the file for
125 * writing, so there's no need to call
126 * jbd2_journal_begin_ordered_truncate() since there's no
127 * outstanding writes we need to flush.
129 if (!EXT4_I(inode)->jinode)
131 return jbd2_journal_begin_ordered_truncate(EXT4_JOURNAL(inode),
132 EXT4_I(inode)->jinode,
136 static void ext4_invalidatepage(struct page *page, unsigned int offset,
137 unsigned int length);
138 static int __ext4_journalled_writepage(struct page *page, unsigned int len);
139 static int ext4_bh_delay_or_unwritten(handle_t *handle, struct buffer_head *bh);
140 static int ext4_meta_trans_blocks(struct inode *inode, int lblocks,
144 * Test whether an inode is a fast symlink.
146 static int ext4_inode_is_fast_symlink(struct inode *inode)
148 int ea_blocks = EXT4_I(inode)->i_file_acl ?
149 EXT4_CLUSTER_SIZE(inode->i_sb) >> 9 : 0;
151 return (S_ISLNK(inode->i_mode) && inode->i_blocks - ea_blocks == 0);
155 * Restart the transaction associated with *handle. This does a commit,
156 * so before we call here everything must be consistently dirtied against
159 int ext4_truncate_restart_trans(handle_t *handle, struct inode *inode,
165 * Drop i_data_sem to avoid deadlock with ext4_map_blocks. At this
166 * moment, get_block can be called only for blocks inside i_size since
167 * page cache has been already dropped and writes are blocked by
168 * i_mutex. So we can safely drop the i_data_sem here.
170 BUG_ON(EXT4_JOURNAL(inode) == NULL);
171 jbd_debug(2, "restarting handle %p\n", handle);
172 up_write(&EXT4_I(inode)->i_data_sem);
173 ret = ext4_journal_restart(handle, nblocks);
174 down_write(&EXT4_I(inode)->i_data_sem);
175 ext4_discard_preallocations(inode);
181 * Called at the last iput() if i_nlink is zero.
183 void ext4_evict_inode(struct inode *inode)
188 trace_ext4_evict_inode(inode);
190 if (inode->i_nlink) {
192 * When journalling data dirty buffers are tracked only in the
193 * journal. So although mm thinks everything is clean and
194 * ready for reaping the inode might still have some pages to
195 * write in the running transaction or waiting to be
196 * checkpointed. Thus calling jbd2_journal_invalidatepage()
197 * (via truncate_inode_pages()) to discard these buffers can
198 * cause data loss. Also even if we did not discard these
199 * buffers, we would have no way to find them after the inode
200 * is reaped and thus user could see stale data if he tries to
201 * read them before the transaction is checkpointed. So be
202 * careful and force everything to disk here... We use
203 * ei->i_datasync_tid to store the newest transaction
204 * containing inode's data.
206 * Note that directories do not have this problem because they
207 * don't use page cache.
209 if (ext4_should_journal_data(inode) &&
210 (S_ISLNK(inode->i_mode) || S_ISREG(inode->i_mode)) &&
211 inode->i_ino != EXT4_JOURNAL_INO) {
212 journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
213 tid_t commit_tid = EXT4_I(inode)->i_datasync_tid;
215 jbd2_complete_transaction(journal, commit_tid);
216 filemap_write_and_wait(&inode->i_data);
218 truncate_inode_pages(&inode->i_data, 0);
220 WARN_ON(atomic_read(&EXT4_I(inode)->i_ioend_count));
224 if (!is_bad_inode(inode))
225 dquot_initialize(inode);
227 if (ext4_should_order_data(inode))
228 ext4_begin_ordered_truncate(inode, 0);
229 truncate_inode_pages(&inode->i_data, 0);
231 WARN_ON(atomic_read(&EXT4_I(inode)->i_ioend_count));
232 if (is_bad_inode(inode))
236 * Protect us against freezing - iput() caller didn't have to have any
237 * protection against it
239 sb_start_intwrite(inode->i_sb);
240 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE,
241 ext4_blocks_for_truncate(inode)+3);
242 if (IS_ERR(handle)) {
243 ext4_std_error(inode->i_sb, PTR_ERR(handle));
245 * If we're going to skip the normal cleanup, we still need to
246 * make sure that the in-core orphan linked list is properly
249 ext4_orphan_del(NULL, inode);
250 sb_end_intwrite(inode->i_sb);
255 ext4_handle_sync(handle);
257 err = ext4_mark_inode_dirty(handle, inode);
259 ext4_warning(inode->i_sb,
260 "couldn't mark inode dirty (err %d)", err);
264 ext4_truncate(inode);
267 * ext4_ext_truncate() doesn't reserve any slop when it
268 * restarts journal transactions; therefore there may not be
269 * enough credits left in the handle to remove the inode from
270 * the orphan list and set the dtime field.
272 if (!ext4_handle_has_enough_credits(handle, 3)) {
273 err = ext4_journal_extend(handle, 3);
275 err = ext4_journal_restart(handle, 3);
277 ext4_warning(inode->i_sb,
278 "couldn't extend journal (err %d)", err);
280 ext4_journal_stop(handle);
281 ext4_orphan_del(NULL, inode);
282 sb_end_intwrite(inode->i_sb);
288 * Kill off the orphan record which ext4_truncate created.
289 * AKPM: I think this can be inside the above `if'.
290 * Note that ext4_orphan_del() has to be able to cope with the
291 * deletion of a non-existent orphan - this is because we don't
292 * know if ext4_truncate() actually created an orphan record.
293 * (Well, we could do this if we need to, but heck - it works)
295 ext4_orphan_del(handle, inode);
296 EXT4_I(inode)->i_dtime = get_seconds();
299 * One subtle ordering requirement: if anything has gone wrong
300 * (transaction abort, IO errors, whatever), then we can still
301 * do these next steps (the fs will already have been marked as
302 * having errors), but we can't free the inode if the mark_dirty
305 if (ext4_mark_inode_dirty(handle, inode))
306 /* If that failed, just do the required in-core inode clear. */
307 ext4_clear_inode(inode);
309 ext4_free_inode(handle, inode);
310 ext4_journal_stop(handle);
311 sb_end_intwrite(inode->i_sb);
314 ext4_clear_inode(inode); /* We must guarantee clearing of inode... */
318 qsize_t *ext4_get_reserved_space(struct inode *inode)
320 return &EXT4_I(inode)->i_reserved_quota;
325 * Calculate the number of metadata blocks need to reserve
326 * to allocate a block located at @lblock
328 static int ext4_calc_metadata_amount(struct inode *inode, ext4_lblk_t lblock)
330 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
331 return ext4_ext_calc_metadata_amount(inode, lblock);
333 return ext4_ind_calc_metadata_amount(inode, lblock);
337 * Called with i_data_sem down, which is important since we can call
338 * ext4_discard_preallocations() from here.
340 void ext4_da_update_reserve_space(struct inode *inode,
341 int used, int quota_claim)
343 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
344 struct ext4_inode_info *ei = EXT4_I(inode);
346 spin_lock(&ei->i_block_reservation_lock);
347 trace_ext4_da_update_reserve_space(inode, used, quota_claim);
348 if (unlikely(used > ei->i_reserved_data_blocks)) {
349 ext4_warning(inode->i_sb, "%s: ino %lu, used %d "
350 "with only %d reserved data blocks",
351 __func__, inode->i_ino, used,
352 ei->i_reserved_data_blocks);
354 used = ei->i_reserved_data_blocks;
357 if (unlikely(ei->i_allocated_meta_blocks > ei->i_reserved_meta_blocks)) {
358 ext4_warning(inode->i_sb, "ino %lu, allocated %d "
359 "with only %d reserved metadata blocks "
360 "(releasing %d blocks with reserved %d data blocks)",
361 inode->i_ino, ei->i_allocated_meta_blocks,
362 ei->i_reserved_meta_blocks, used,
363 ei->i_reserved_data_blocks);
365 ei->i_allocated_meta_blocks = ei->i_reserved_meta_blocks;
368 /* Update per-inode reservations */
369 ei->i_reserved_data_blocks -= used;
370 ei->i_reserved_meta_blocks -= ei->i_allocated_meta_blocks;
371 percpu_counter_sub(&sbi->s_dirtyclusters_counter,
372 used + ei->i_allocated_meta_blocks);
373 ei->i_allocated_meta_blocks = 0;
375 if (ei->i_reserved_data_blocks == 0) {
377 * We can release all of the reserved metadata blocks
378 * only when we have written all of the delayed
381 percpu_counter_sub(&sbi->s_dirtyclusters_counter,
382 ei->i_reserved_meta_blocks);
383 ei->i_reserved_meta_blocks = 0;
384 ei->i_da_metadata_calc_len = 0;
386 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
388 /* Update quota subsystem for data blocks */
390 dquot_claim_block(inode, EXT4_C2B(sbi, used));
393 * We did fallocate with an offset that is already delayed
394 * allocated. So on delayed allocated writeback we should
395 * not re-claim the quota for fallocated blocks.
397 dquot_release_reservation_block(inode, EXT4_C2B(sbi, used));
401 * If we have done all the pending block allocations and if
402 * there aren't any writers on the inode, we can discard the
403 * inode's preallocations.
405 if ((ei->i_reserved_data_blocks == 0) &&
406 (atomic_read(&inode->i_writecount) == 0))
407 ext4_discard_preallocations(inode);
410 static int __check_block_validity(struct inode *inode, const char *func,
412 struct ext4_map_blocks *map)
414 if (!ext4_data_block_valid(EXT4_SB(inode->i_sb), map->m_pblk,
416 ext4_error_inode(inode, func, line, map->m_pblk,
417 "lblock %lu mapped to illegal pblock "
418 "(length %d)", (unsigned long) map->m_lblk,
425 #define check_block_validity(inode, map) \
426 __check_block_validity((inode), __func__, __LINE__, (map))
428 #ifdef ES_AGGRESSIVE_TEST
429 static void ext4_map_blocks_es_recheck(handle_t *handle,
431 struct ext4_map_blocks *es_map,
432 struct ext4_map_blocks *map,
439 * There is a race window that the result is not the same.
440 * e.g. xfstests #223 when dioread_nolock enables. The reason
441 * is that we lookup a block mapping in extent status tree with
442 * out taking i_data_sem. So at the time the unwritten extent
443 * could be converted.
445 if (!(flags & EXT4_GET_BLOCKS_NO_LOCK))
446 down_read((&EXT4_I(inode)->i_data_sem));
447 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
448 retval = ext4_ext_map_blocks(handle, inode, map, flags &
449 EXT4_GET_BLOCKS_KEEP_SIZE);
451 retval = ext4_ind_map_blocks(handle, inode, map, flags &
452 EXT4_GET_BLOCKS_KEEP_SIZE);
454 if (!(flags & EXT4_GET_BLOCKS_NO_LOCK))
455 up_read((&EXT4_I(inode)->i_data_sem));
457 * Clear EXT4_MAP_FROM_CLUSTER and EXT4_MAP_BOUNDARY flag
458 * because it shouldn't be marked in es_map->m_flags.
460 map->m_flags &= ~(EXT4_MAP_FROM_CLUSTER | EXT4_MAP_BOUNDARY);
463 * We don't check m_len because extent will be collpased in status
464 * tree. So the m_len might not equal.
466 if (es_map->m_lblk != map->m_lblk ||
467 es_map->m_flags != map->m_flags ||
468 es_map->m_pblk != map->m_pblk) {
469 printk("ES cache assertion failed for inode: %lu "
470 "es_cached ex [%d/%d/%llu/%x] != "
471 "found ex [%d/%d/%llu/%x] retval %d flags %x\n",
472 inode->i_ino, es_map->m_lblk, es_map->m_len,
473 es_map->m_pblk, es_map->m_flags, map->m_lblk,
474 map->m_len, map->m_pblk, map->m_flags,
478 #endif /* ES_AGGRESSIVE_TEST */
481 * The ext4_map_blocks() function tries to look up the requested blocks,
482 * and returns if the blocks are already mapped.
484 * Otherwise it takes the write lock of the i_data_sem and allocate blocks
485 * and store the allocated blocks in the result buffer head and mark it
488 * If file type is extents based, it will call ext4_ext_map_blocks(),
489 * Otherwise, call with ext4_ind_map_blocks() to handle indirect mapping
492 * On success, it returns the number of blocks being mapped or allocate.
493 * if create==0 and the blocks are pre-allocated and uninitialized block,
494 * the result buffer head is unmapped. If the create ==1, it will make sure
495 * the buffer head is mapped.
497 * It returns 0 if plain look up failed (blocks have not been allocated), in
498 * that case, buffer head is unmapped
500 * It returns the error in case of allocation failure.
502 int ext4_map_blocks(handle_t *handle, struct inode *inode,
503 struct ext4_map_blocks *map, int flags)
505 struct extent_status es;
507 #ifdef ES_AGGRESSIVE_TEST
508 struct ext4_map_blocks orig_map;
510 memcpy(&orig_map, map, sizeof(*map));
514 ext_debug("ext4_map_blocks(): inode %lu, flag %d, max_blocks %u,"
515 "logical block %lu\n", inode->i_ino, flags, map->m_len,
516 (unsigned long) map->m_lblk);
518 /* We can handle the block number less than EXT_MAX_BLOCKS */
519 if (unlikely(map->m_lblk >= EXT_MAX_BLOCKS))
522 /* Lookup extent status tree firstly */
523 if (ext4_es_lookup_extent(inode, map->m_lblk, &es)) {
524 ext4_es_lru_add(inode);
525 if (ext4_es_is_written(&es) || ext4_es_is_unwritten(&es)) {
526 map->m_pblk = ext4_es_pblock(&es) +
527 map->m_lblk - es.es_lblk;
528 map->m_flags |= ext4_es_is_written(&es) ?
529 EXT4_MAP_MAPPED : EXT4_MAP_UNWRITTEN;
530 retval = es.es_len - (map->m_lblk - es.es_lblk);
531 if (retval > map->m_len)
534 } else if (ext4_es_is_delayed(&es) || ext4_es_is_hole(&es)) {
539 #ifdef ES_AGGRESSIVE_TEST
540 ext4_map_blocks_es_recheck(handle, inode, map,
547 * Try to see if we can get the block without requesting a new
550 if (!(flags & EXT4_GET_BLOCKS_NO_LOCK))
551 down_read((&EXT4_I(inode)->i_data_sem));
552 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
553 retval = ext4_ext_map_blocks(handle, inode, map, flags &
554 EXT4_GET_BLOCKS_KEEP_SIZE);
556 retval = ext4_ind_map_blocks(handle, inode, map, flags &
557 EXT4_GET_BLOCKS_KEEP_SIZE);
563 if (unlikely(retval != map->m_len)) {
564 ext4_warning(inode->i_sb,
565 "ES len assertion failed for inode "
566 "%lu: retval %d != map->m_len %d",
567 inode->i_ino, retval, map->m_len);
571 status = map->m_flags & EXT4_MAP_UNWRITTEN ?
572 EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
573 if (!(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) &&
574 ext4_find_delalloc_range(inode, map->m_lblk,
575 map->m_lblk + map->m_len - 1))
576 status |= EXTENT_STATUS_DELAYED;
577 ret = ext4_es_insert_extent(inode, map->m_lblk,
578 map->m_len, map->m_pblk, status);
582 if (!(flags & EXT4_GET_BLOCKS_NO_LOCK))
583 up_read((&EXT4_I(inode)->i_data_sem));
586 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
587 int ret = check_block_validity(inode, map);
592 /* If it is only a block(s) look up */
593 if ((flags & EXT4_GET_BLOCKS_CREATE) == 0)
597 * Returns if the blocks have already allocated
599 * Note that if blocks have been preallocated
600 * ext4_ext_get_block() returns the create = 0
601 * with buffer head unmapped.
603 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED)
607 * Here we clear m_flags because after allocating an new extent,
608 * it will be set again.
610 map->m_flags &= ~EXT4_MAP_FLAGS;
613 * New blocks allocate and/or writing to uninitialized extent
614 * will possibly result in updating i_data, so we take
615 * the write lock of i_data_sem, and call get_blocks()
616 * with create == 1 flag.
618 down_write((&EXT4_I(inode)->i_data_sem));
621 * if the caller is from delayed allocation writeout path
622 * we have already reserved fs blocks for allocation
623 * let the underlying get_block() function know to
624 * avoid double accounting
626 if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
627 ext4_set_inode_state(inode, EXT4_STATE_DELALLOC_RESERVED);
629 * We need to check for EXT4 here because migrate
630 * could have changed the inode type in between
632 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
633 retval = ext4_ext_map_blocks(handle, inode, map, flags);
635 retval = ext4_ind_map_blocks(handle, inode, map, flags);
637 if (retval > 0 && map->m_flags & EXT4_MAP_NEW) {
639 * We allocated new blocks which will result in
640 * i_data's format changing. Force the migrate
641 * to fail by clearing migrate flags
643 ext4_clear_inode_state(inode, EXT4_STATE_EXT_MIGRATE);
647 * Update reserved blocks/metadata blocks after successful
648 * block allocation which had been deferred till now. We don't
649 * support fallocate for non extent files. So we can update
650 * reserve space here.
653 (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE))
654 ext4_da_update_reserve_space(inode, retval, 1);
656 if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
657 ext4_clear_inode_state(inode, EXT4_STATE_DELALLOC_RESERVED);
663 if (unlikely(retval != map->m_len)) {
664 ext4_warning(inode->i_sb,
665 "ES len assertion failed for inode "
666 "%lu: retval %d != map->m_len %d",
667 inode->i_ino, retval, map->m_len);
672 * If the extent has been zeroed out, we don't need to update
673 * extent status tree.
675 if ((flags & EXT4_GET_BLOCKS_PRE_IO) &&
676 ext4_es_lookup_extent(inode, map->m_lblk, &es)) {
677 if (ext4_es_is_written(&es))
680 status = map->m_flags & EXT4_MAP_UNWRITTEN ?
681 EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
682 if (!(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) &&
683 ext4_find_delalloc_range(inode, map->m_lblk,
684 map->m_lblk + map->m_len - 1))
685 status |= EXTENT_STATUS_DELAYED;
686 ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
687 map->m_pblk, status);
693 up_write((&EXT4_I(inode)->i_data_sem));
694 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
695 int ret = check_block_validity(inode, map);
702 /* Maximum number of blocks we map for direct IO at once. */
703 #define DIO_MAX_BLOCKS 4096
705 static int _ext4_get_block(struct inode *inode, sector_t iblock,
706 struct buffer_head *bh, int flags)
708 handle_t *handle = ext4_journal_current_handle();
709 struct ext4_map_blocks map;
710 int ret = 0, started = 0;
713 if (ext4_has_inline_data(inode))
717 map.m_len = bh->b_size >> inode->i_blkbits;
719 if (flags && !(flags & EXT4_GET_BLOCKS_NO_LOCK) && !handle) {
720 /* Direct IO write... */
721 if (map.m_len > DIO_MAX_BLOCKS)
722 map.m_len = DIO_MAX_BLOCKS;
723 dio_credits = ext4_chunk_trans_blocks(inode, map.m_len);
724 handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS,
726 if (IS_ERR(handle)) {
727 ret = PTR_ERR(handle);
733 ret = ext4_map_blocks(handle, inode, &map, flags);
735 ext4_io_end_t *io_end = ext4_inode_aio(inode);
737 map_bh(bh, inode->i_sb, map.m_pblk);
738 bh->b_state = (bh->b_state & ~EXT4_MAP_FLAGS) | map.m_flags;
739 if (io_end && io_end->flag & EXT4_IO_END_UNWRITTEN)
740 set_buffer_defer_completion(bh);
741 bh->b_size = inode->i_sb->s_blocksize * map.m_len;
745 ext4_journal_stop(handle);
749 int ext4_get_block(struct inode *inode, sector_t iblock,
750 struct buffer_head *bh, int create)
752 return _ext4_get_block(inode, iblock, bh,
753 create ? EXT4_GET_BLOCKS_CREATE : 0);
757 * `handle' can be NULL if create is zero
759 struct buffer_head *ext4_getblk(handle_t *handle, struct inode *inode,
760 ext4_lblk_t block, int create, int *errp)
762 struct ext4_map_blocks map;
763 struct buffer_head *bh;
766 J_ASSERT(handle != NULL || create == 0);
770 err = ext4_map_blocks(handle, inode, &map,
771 create ? EXT4_GET_BLOCKS_CREATE : 0);
773 /* ensure we send some value back into *errp */
776 if (create && err == 0)
777 err = -ENOSPC; /* should never happen */
783 bh = sb_getblk(inode->i_sb, map.m_pblk);
788 if (map.m_flags & EXT4_MAP_NEW) {
789 J_ASSERT(create != 0);
790 J_ASSERT(handle != NULL);
793 * Now that we do not always journal data, we should
794 * keep in mind whether this should always journal the
795 * new buffer as metadata. For now, regular file
796 * writes use ext4_get_block instead, so it's not a
800 BUFFER_TRACE(bh, "call get_create_access");
801 fatal = ext4_journal_get_create_access(handle, bh);
802 if (!fatal && !buffer_uptodate(bh)) {
803 memset(bh->b_data, 0, inode->i_sb->s_blocksize);
804 set_buffer_uptodate(bh);
807 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
808 err = ext4_handle_dirty_metadata(handle, inode, bh);
812 BUFFER_TRACE(bh, "not a new buffer");
822 struct buffer_head *ext4_bread(handle_t *handle, struct inode *inode,
823 ext4_lblk_t block, int create, int *err)
825 struct buffer_head *bh;
827 bh = ext4_getblk(handle, inode, block, create, err);
830 if (buffer_uptodate(bh))
832 ll_rw_block(READ | REQ_META | REQ_PRIO, 1, &bh);
834 if (buffer_uptodate(bh))
841 int ext4_walk_page_buffers(handle_t *handle,
842 struct buffer_head *head,
846 int (*fn)(handle_t *handle,
847 struct buffer_head *bh))
849 struct buffer_head *bh;
850 unsigned block_start, block_end;
851 unsigned blocksize = head->b_size;
853 struct buffer_head *next;
855 for (bh = head, block_start = 0;
856 ret == 0 && (bh != head || !block_start);
857 block_start = block_end, bh = next) {
858 next = bh->b_this_page;
859 block_end = block_start + blocksize;
860 if (block_end <= from || block_start >= to) {
861 if (partial && !buffer_uptodate(bh))
865 err = (*fn)(handle, bh);
873 * To preserve ordering, it is essential that the hole instantiation and
874 * the data write be encapsulated in a single transaction. We cannot
875 * close off a transaction and start a new one between the ext4_get_block()
876 * and the commit_write(). So doing the jbd2_journal_start at the start of
877 * prepare_write() is the right place.
879 * Also, this function can nest inside ext4_writepage(). In that case, we
880 * *know* that ext4_writepage() has generated enough buffer credits to do the
881 * whole page. So we won't block on the journal in that case, which is good,
882 * because the caller may be PF_MEMALLOC.
884 * By accident, ext4 can be reentered when a transaction is open via
885 * quota file writes. If we were to commit the transaction while thus
886 * reentered, there can be a deadlock - we would be holding a quota
887 * lock, and the commit would never complete if another thread had a
888 * transaction open and was blocking on the quota lock - a ranking
891 * So what we do is to rely on the fact that jbd2_journal_stop/journal_start
892 * will _not_ run commit under these circumstances because handle->h_ref
893 * is elevated. We'll still have enough credits for the tiny quotafile
896 int do_journal_get_write_access(handle_t *handle,
897 struct buffer_head *bh)
899 int dirty = buffer_dirty(bh);
902 if (!buffer_mapped(bh) || buffer_freed(bh))
905 * __block_write_begin() could have dirtied some buffers. Clean
906 * the dirty bit as jbd2_journal_get_write_access() could complain
907 * otherwise about fs integrity issues. Setting of the dirty bit
908 * by __block_write_begin() isn't a real problem here as we clear
909 * the bit before releasing a page lock and thus writeback cannot
910 * ever write the buffer.
913 clear_buffer_dirty(bh);
914 ret = ext4_journal_get_write_access(handle, bh);
916 ret = ext4_handle_dirty_metadata(handle, NULL, bh);
920 static int ext4_get_block_write_nolock(struct inode *inode, sector_t iblock,
921 struct buffer_head *bh_result, int create);
922 static int ext4_write_begin(struct file *file, struct address_space *mapping,
923 loff_t pos, unsigned len, unsigned flags,
924 struct page **pagep, void **fsdata)
926 struct inode *inode = mapping->host;
927 int ret, needed_blocks;
934 trace_ext4_write_begin(inode, pos, len, flags);
936 * Reserve one block more for addition to orphan list in case
937 * we allocate blocks but write fails for some reason
939 needed_blocks = ext4_writepage_trans_blocks(inode) + 1;
940 index = pos >> PAGE_CACHE_SHIFT;
941 from = pos & (PAGE_CACHE_SIZE - 1);
944 if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
945 ret = ext4_try_to_write_inline_data(mapping, inode, pos, len,
954 * grab_cache_page_write_begin() can take a long time if the
955 * system is thrashing due to memory pressure, or if the page
956 * is being written back. So grab it first before we start
957 * the transaction handle. This also allows us to allocate
958 * the page (if needed) without using GFP_NOFS.
961 page = grab_cache_page_write_begin(mapping, index, flags);
967 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE, needed_blocks);
968 if (IS_ERR(handle)) {
969 page_cache_release(page);
970 return PTR_ERR(handle);
974 if (page->mapping != mapping) {
975 /* The page got truncated from under us */
977 page_cache_release(page);
978 ext4_journal_stop(handle);
981 /* In case writeback began while the page was unlocked */
982 wait_for_stable_page(page);
984 if (ext4_should_dioread_nolock(inode))
985 ret = __block_write_begin(page, pos, len, ext4_get_block_write);
987 ret = __block_write_begin(page, pos, len, ext4_get_block);
989 if (!ret && ext4_should_journal_data(inode)) {
990 ret = ext4_walk_page_buffers(handle, page_buffers(page),
992 do_journal_get_write_access);
998 * __block_write_begin may have instantiated a few blocks
999 * outside i_size. Trim these off again. Don't need
1000 * i_size_read because we hold i_mutex.
1002 * Add inode to orphan list in case we crash before
1005 if (pos + len > inode->i_size && ext4_can_truncate(inode))
1006 ext4_orphan_add(handle, inode);
1008 ext4_journal_stop(handle);
1009 if (pos + len > inode->i_size) {
1010 ext4_truncate_failed_write(inode);
1012 * If truncate failed early the inode might
1013 * still be on the orphan list; we need to
1014 * make sure the inode is removed from the
1015 * orphan list in that case.
1018 ext4_orphan_del(NULL, inode);
1021 if (ret == -ENOSPC &&
1022 ext4_should_retry_alloc(inode->i_sb, &retries))
1024 page_cache_release(page);
1031 /* For write_end() in data=journal mode */
1032 static int write_end_fn(handle_t *handle, struct buffer_head *bh)
1035 if (!buffer_mapped(bh) || buffer_freed(bh))
1037 set_buffer_uptodate(bh);
1038 ret = ext4_handle_dirty_metadata(handle, NULL, bh);
1039 clear_buffer_meta(bh);
1040 clear_buffer_prio(bh);
1045 * We need to pick up the new inode size which generic_commit_write gave us
1046 * `file' can be NULL - eg, when called from page_symlink().
1048 * ext4 never places buffers on inode->i_mapping->private_list. metadata
1049 * buffers are managed internally.
1051 static int ext4_write_end(struct file *file,
1052 struct address_space *mapping,
1053 loff_t pos, unsigned len, unsigned copied,
1054 struct page *page, void *fsdata)
1056 handle_t *handle = ext4_journal_current_handle();
1057 struct inode *inode = mapping->host;
1059 int i_size_changed = 0;
1061 trace_ext4_write_end(inode, pos, len, copied);
1062 if (ext4_test_inode_state(inode, EXT4_STATE_ORDERED_MODE)) {
1063 ret = ext4_jbd2_file_inode(handle, inode);
1066 page_cache_release(page);
1071 if (ext4_has_inline_data(inode)) {
1072 ret = ext4_write_inline_data_end(inode, pos, len,
1078 copied = block_write_end(file, mapping, pos,
1079 len, copied, page, fsdata);
1082 * No need to use i_size_read() here, the i_size
1083 * cannot change under us because we hole i_mutex.
1085 * But it's important to update i_size while still holding page lock:
1086 * page writeout could otherwise come in and zero beyond i_size.
1088 if (pos + copied > inode->i_size) {
1089 i_size_write(inode, pos + copied);
1093 if (pos + copied > EXT4_I(inode)->i_disksize) {
1094 /* We need to mark inode dirty even if
1095 * new_i_size is less that inode->i_size
1096 * but greater than i_disksize. (hint delalloc)
1098 ext4_update_i_disksize(inode, (pos + copied));
1102 page_cache_release(page);
1105 * Don't mark the inode dirty under page lock. First, it unnecessarily
1106 * makes the holding time of page lock longer. Second, it forces lock
1107 * ordering of page lock and transaction start for journaling
1111 ext4_mark_inode_dirty(handle, inode);
1113 if (pos + len > inode->i_size && ext4_can_truncate(inode))
1114 /* if we have allocated more blocks and copied
1115 * less. We will have blocks allocated outside
1116 * inode->i_size. So truncate them
1118 ext4_orphan_add(handle, inode);
1120 ret2 = ext4_journal_stop(handle);
1124 if (pos + len > inode->i_size) {
1125 ext4_truncate_failed_write(inode);
1127 * If truncate failed early the inode might still be
1128 * on the orphan list; we need to make sure the inode
1129 * is removed from the orphan list in that case.
1132 ext4_orphan_del(NULL, inode);
1135 return ret ? ret : copied;
1138 static int ext4_journalled_write_end(struct file *file,
1139 struct address_space *mapping,
1140 loff_t pos, unsigned len, unsigned copied,
1141 struct page *page, void *fsdata)
1143 handle_t *handle = ext4_journal_current_handle();
1144 struct inode *inode = mapping->host;
1150 trace_ext4_journalled_write_end(inode, pos, len, copied);
1151 from = pos & (PAGE_CACHE_SIZE - 1);
1154 BUG_ON(!ext4_handle_valid(handle));
1156 if (ext4_has_inline_data(inode))
1157 copied = ext4_write_inline_data_end(inode, pos, len,
1161 if (!PageUptodate(page))
1163 page_zero_new_buffers(page, from+copied, to);
1166 ret = ext4_walk_page_buffers(handle, page_buffers(page), from,
1167 to, &partial, write_end_fn);
1169 SetPageUptodate(page);
1171 new_i_size = pos + copied;
1172 if (new_i_size > inode->i_size)
1173 i_size_write(inode, pos+copied);
1174 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
1175 EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
1176 if (new_i_size > EXT4_I(inode)->i_disksize) {
1177 ext4_update_i_disksize(inode, new_i_size);
1178 ret2 = ext4_mark_inode_dirty(handle, inode);
1184 page_cache_release(page);
1185 if (pos + len > inode->i_size && ext4_can_truncate(inode))
1186 /* if we have allocated more blocks and copied
1187 * less. We will have blocks allocated outside
1188 * inode->i_size. So truncate them
1190 ext4_orphan_add(handle, inode);
1192 ret2 = ext4_journal_stop(handle);
1195 if (pos + len > inode->i_size) {
1196 ext4_truncate_failed_write(inode);
1198 * If truncate failed early the inode might still be
1199 * on the orphan list; we need to make sure the inode
1200 * is removed from the orphan list in that case.
1203 ext4_orphan_del(NULL, inode);
1206 return ret ? ret : copied;
1210 * Reserve a metadata for a single block located at lblock
1212 static int ext4_da_reserve_metadata(struct inode *inode, ext4_lblk_t lblock)
1214 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1215 struct ext4_inode_info *ei = EXT4_I(inode);
1216 unsigned int md_needed;
1217 ext4_lblk_t save_last_lblock;
1221 * recalculate the amount of metadata blocks to reserve
1222 * in order to allocate nrblocks
1223 * worse case is one extent per block
1225 spin_lock(&ei->i_block_reservation_lock);
1227 * ext4_calc_metadata_amount() has side effects, which we have
1228 * to be prepared undo if we fail to claim space.
1230 save_len = ei->i_da_metadata_calc_len;
1231 save_last_lblock = ei->i_da_metadata_calc_last_lblock;
1232 md_needed = EXT4_NUM_B2C(sbi,
1233 ext4_calc_metadata_amount(inode, lblock));
1234 trace_ext4_da_reserve_space(inode, md_needed);
1237 * We do still charge estimated metadata to the sb though;
1238 * we cannot afford to run out of free blocks.
1240 if (ext4_claim_free_clusters(sbi, md_needed, 0)) {
1241 ei->i_da_metadata_calc_len = save_len;
1242 ei->i_da_metadata_calc_last_lblock = save_last_lblock;
1243 spin_unlock(&ei->i_block_reservation_lock);
1246 ei->i_reserved_meta_blocks += md_needed;
1247 spin_unlock(&ei->i_block_reservation_lock);
1249 return 0; /* success */
1253 * Reserve a single cluster located at lblock
1255 static int ext4_da_reserve_space(struct inode *inode, ext4_lblk_t lblock)
1257 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1258 struct ext4_inode_info *ei = EXT4_I(inode);
1259 unsigned int md_needed;
1261 ext4_lblk_t save_last_lblock;
1265 * We will charge metadata quota at writeout time; this saves
1266 * us from metadata over-estimation, though we may go over by
1267 * a small amount in the end. Here we just reserve for data.
1269 ret = dquot_reserve_block(inode, EXT4_C2B(sbi, 1));
1274 * recalculate the amount of metadata blocks to reserve
1275 * in order to allocate nrblocks
1276 * worse case is one extent per block
1278 spin_lock(&ei->i_block_reservation_lock);
1280 * ext4_calc_metadata_amount() has side effects, which we have
1281 * to be prepared undo if we fail to claim space.
1283 save_len = ei->i_da_metadata_calc_len;
1284 save_last_lblock = ei->i_da_metadata_calc_last_lblock;
1285 md_needed = EXT4_NUM_B2C(sbi,
1286 ext4_calc_metadata_amount(inode, lblock));
1287 trace_ext4_da_reserve_space(inode, md_needed);
1290 * We do still charge estimated metadata to the sb though;
1291 * we cannot afford to run out of free blocks.
1293 if (ext4_claim_free_clusters(sbi, md_needed + 1, 0)) {
1294 ei->i_da_metadata_calc_len = save_len;
1295 ei->i_da_metadata_calc_last_lblock = save_last_lblock;
1296 spin_unlock(&ei->i_block_reservation_lock);
1297 dquot_release_reservation_block(inode, EXT4_C2B(sbi, 1));
1300 ei->i_reserved_data_blocks++;
1301 ei->i_reserved_meta_blocks += md_needed;
1302 spin_unlock(&ei->i_block_reservation_lock);
1304 return 0; /* success */
1307 static void ext4_da_release_space(struct inode *inode, int to_free)
1309 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1310 struct ext4_inode_info *ei = EXT4_I(inode);
1313 return; /* Nothing to release, exit */
1315 spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
1317 trace_ext4_da_release_space(inode, to_free);
1318 if (unlikely(to_free > ei->i_reserved_data_blocks)) {
1320 * if there aren't enough reserved blocks, then the
1321 * counter is messed up somewhere. Since this
1322 * function is called from invalidate page, it's
1323 * harmless to return without any action.
1325 ext4_warning(inode->i_sb, "ext4_da_release_space: "
1326 "ino %lu, to_free %d with only %d reserved "
1327 "data blocks", inode->i_ino, to_free,
1328 ei->i_reserved_data_blocks);
1330 to_free = ei->i_reserved_data_blocks;
1332 ei->i_reserved_data_blocks -= to_free;
1334 if (ei->i_reserved_data_blocks == 0) {
1336 * We can release all of the reserved metadata blocks
1337 * only when we have written all of the delayed
1338 * allocation blocks.
1339 * Note that in case of bigalloc, i_reserved_meta_blocks,
1340 * i_reserved_data_blocks, etc. refer to number of clusters.
1342 percpu_counter_sub(&sbi->s_dirtyclusters_counter,
1343 ei->i_reserved_meta_blocks);
1344 ei->i_reserved_meta_blocks = 0;
1345 ei->i_da_metadata_calc_len = 0;
1348 /* update fs dirty data blocks counter */
1349 percpu_counter_sub(&sbi->s_dirtyclusters_counter, to_free);
1351 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
1353 dquot_release_reservation_block(inode, EXT4_C2B(sbi, to_free));
1356 static void ext4_da_page_release_reservation(struct page *page,
1357 unsigned int offset,
1358 unsigned int length)
1361 struct buffer_head *head, *bh;
1362 unsigned int curr_off = 0;
1363 struct inode *inode = page->mapping->host;
1364 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1365 unsigned int stop = offset + length;
1369 BUG_ON(stop > PAGE_CACHE_SIZE || stop < length);
1371 head = page_buffers(page);
1374 unsigned int next_off = curr_off + bh->b_size;
1376 if (next_off > stop)
1379 if ((offset <= curr_off) && (buffer_delay(bh))) {
1381 clear_buffer_delay(bh);
1383 curr_off = next_off;
1384 } while ((bh = bh->b_this_page) != head);
1387 lblk = page->index << (PAGE_CACHE_SHIFT - inode->i_blkbits);
1388 ext4_es_remove_extent(inode, lblk, to_release);
1391 /* If we have released all the blocks belonging to a cluster, then we
1392 * need to release the reserved space for that cluster. */
1393 num_clusters = EXT4_NUM_B2C(sbi, to_release);
1394 while (num_clusters > 0) {
1395 lblk = (page->index << (PAGE_CACHE_SHIFT - inode->i_blkbits)) +
1396 ((num_clusters - 1) << sbi->s_cluster_bits);
1397 if (sbi->s_cluster_ratio == 1 ||
1398 !ext4_find_delalloc_cluster(inode, lblk))
1399 ext4_da_release_space(inode, 1);
1406 * Delayed allocation stuff
1409 struct mpage_da_data {
1410 struct inode *inode;
1411 struct writeback_control *wbc;
1413 pgoff_t first_page; /* The first page to write */
1414 pgoff_t next_page; /* Current page to examine */
1415 pgoff_t last_page; /* Last page to examine */
1417 * Extent to map - this can be after first_page because that can be
1418 * fully mapped. We somewhat abuse m_flags to store whether the extent
1419 * is delalloc or unwritten.
1421 struct ext4_map_blocks map;
1422 struct ext4_io_submit io_submit; /* IO submission data */
1425 static void mpage_release_unused_pages(struct mpage_da_data *mpd,
1430 struct pagevec pvec;
1431 struct inode *inode = mpd->inode;
1432 struct address_space *mapping = inode->i_mapping;
1434 /* This is necessary when next_page == 0. */
1435 if (mpd->first_page >= mpd->next_page)
1438 index = mpd->first_page;
1439 end = mpd->next_page - 1;
1441 ext4_lblk_t start, last;
1442 start = index << (PAGE_CACHE_SHIFT - inode->i_blkbits);
1443 last = end << (PAGE_CACHE_SHIFT - inode->i_blkbits);
1444 ext4_es_remove_extent(inode, start, last - start + 1);
1447 pagevec_init(&pvec, 0);
1448 while (index <= end) {
1449 nr_pages = pagevec_lookup(&pvec, mapping, index, PAGEVEC_SIZE);
1452 for (i = 0; i < nr_pages; i++) {
1453 struct page *page = pvec.pages[i];
1454 if (page->index > end)
1456 BUG_ON(!PageLocked(page));
1457 BUG_ON(PageWriteback(page));
1459 block_invalidatepage(page, 0, PAGE_CACHE_SIZE);
1460 ClearPageUptodate(page);
1464 index = pvec.pages[nr_pages - 1]->index + 1;
1465 pagevec_release(&pvec);
1469 static void ext4_print_free_blocks(struct inode *inode)
1471 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1472 struct super_block *sb = inode->i_sb;
1473 struct ext4_inode_info *ei = EXT4_I(inode);
1475 ext4_msg(sb, KERN_CRIT, "Total free blocks count %lld",
1476 EXT4_C2B(EXT4_SB(inode->i_sb),
1477 ext4_count_free_clusters(sb)));
1478 ext4_msg(sb, KERN_CRIT, "Free/Dirty block details");
1479 ext4_msg(sb, KERN_CRIT, "free_blocks=%lld",
1480 (long long) EXT4_C2B(EXT4_SB(sb),
1481 percpu_counter_sum(&sbi->s_freeclusters_counter)));
1482 ext4_msg(sb, KERN_CRIT, "dirty_blocks=%lld",
1483 (long long) EXT4_C2B(EXT4_SB(sb),
1484 percpu_counter_sum(&sbi->s_dirtyclusters_counter)));
1485 ext4_msg(sb, KERN_CRIT, "Block reservation details");
1486 ext4_msg(sb, KERN_CRIT, "i_reserved_data_blocks=%u",
1487 ei->i_reserved_data_blocks);
1488 ext4_msg(sb, KERN_CRIT, "i_reserved_meta_blocks=%u",
1489 ei->i_reserved_meta_blocks);
1490 ext4_msg(sb, KERN_CRIT, "i_allocated_meta_blocks=%u",
1491 ei->i_allocated_meta_blocks);
1495 static int ext4_bh_delay_or_unwritten(handle_t *handle, struct buffer_head *bh)
1497 return (buffer_delay(bh) || buffer_unwritten(bh)) && buffer_dirty(bh);
1501 * This function is grabs code from the very beginning of
1502 * ext4_map_blocks, but assumes that the caller is from delayed write
1503 * time. This function looks up the requested blocks and sets the
1504 * buffer delay bit under the protection of i_data_sem.
1506 static int ext4_da_map_blocks(struct inode *inode, sector_t iblock,
1507 struct ext4_map_blocks *map,
1508 struct buffer_head *bh)
1510 struct extent_status es;
1512 sector_t invalid_block = ~((sector_t) 0xffff);
1513 #ifdef ES_AGGRESSIVE_TEST
1514 struct ext4_map_blocks orig_map;
1516 memcpy(&orig_map, map, sizeof(*map));
1519 if (invalid_block < ext4_blocks_count(EXT4_SB(inode->i_sb)->s_es))
1523 ext_debug("ext4_da_map_blocks(): inode %lu, max_blocks %u,"
1524 "logical block %lu\n", inode->i_ino, map->m_len,
1525 (unsigned long) map->m_lblk);
1527 /* Lookup extent status tree firstly */
1528 if (ext4_es_lookup_extent(inode, iblock, &es)) {
1529 ext4_es_lru_add(inode);
1530 if (ext4_es_is_hole(&es)) {
1532 down_read((&EXT4_I(inode)->i_data_sem));
1537 * Delayed extent could be allocated by fallocate.
1538 * So we need to check it.
1540 if (ext4_es_is_delayed(&es) && !ext4_es_is_unwritten(&es)) {
1541 map_bh(bh, inode->i_sb, invalid_block);
1543 set_buffer_delay(bh);
1547 map->m_pblk = ext4_es_pblock(&es) + iblock - es.es_lblk;
1548 retval = es.es_len - (iblock - es.es_lblk);
1549 if (retval > map->m_len)
1550 retval = map->m_len;
1551 map->m_len = retval;
1552 if (ext4_es_is_written(&es))
1553 map->m_flags |= EXT4_MAP_MAPPED;
1554 else if (ext4_es_is_unwritten(&es))
1555 map->m_flags |= EXT4_MAP_UNWRITTEN;
1559 #ifdef ES_AGGRESSIVE_TEST
1560 ext4_map_blocks_es_recheck(NULL, inode, map, &orig_map, 0);
1566 * Try to see if we can get the block without requesting a new
1567 * file system block.
1569 down_read((&EXT4_I(inode)->i_data_sem));
1570 if (ext4_has_inline_data(inode)) {
1572 * We will soon create blocks for this page, and let
1573 * us pretend as if the blocks aren't allocated yet.
1574 * In case of clusters, we have to handle the work
1575 * of mapping from cluster so that the reserved space
1576 * is calculated properly.
1578 if ((EXT4_SB(inode->i_sb)->s_cluster_ratio > 1) &&
1579 ext4_find_delalloc_cluster(inode, map->m_lblk))
1580 map->m_flags |= EXT4_MAP_FROM_CLUSTER;
1582 } else if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
1583 retval = ext4_ext_map_blocks(NULL, inode, map,
1584 EXT4_GET_BLOCKS_NO_PUT_HOLE);
1586 retval = ext4_ind_map_blocks(NULL, inode, map,
1587 EXT4_GET_BLOCKS_NO_PUT_HOLE);
1593 * XXX: __block_prepare_write() unmaps passed block,
1597 * If the block was allocated from previously allocated cluster,
1598 * then we don't need to reserve it again. However we still need
1599 * to reserve metadata for every block we're going to write.
1601 if (!(map->m_flags & EXT4_MAP_FROM_CLUSTER)) {
1602 ret = ext4_da_reserve_space(inode, iblock);
1604 /* not enough space to reserve */
1609 ret = ext4_da_reserve_metadata(inode, iblock);
1611 /* not enough space to reserve */
1617 ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
1618 ~0, EXTENT_STATUS_DELAYED);
1624 /* Clear EXT4_MAP_FROM_CLUSTER flag since its purpose is served
1625 * and it should not appear on the bh->b_state.
1627 map->m_flags &= ~EXT4_MAP_FROM_CLUSTER;
1629 map_bh(bh, inode->i_sb, invalid_block);
1631 set_buffer_delay(bh);
1632 } else if (retval > 0) {
1634 unsigned int status;
1636 if (unlikely(retval != map->m_len)) {
1637 ext4_warning(inode->i_sb,
1638 "ES len assertion failed for inode "
1639 "%lu: retval %d != map->m_len %d",
1640 inode->i_ino, retval, map->m_len);
1644 status = map->m_flags & EXT4_MAP_UNWRITTEN ?
1645 EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
1646 ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
1647 map->m_pblk, status);
1653 up_read((&EXT4_I(inode)->i_data_sem));
1659 * This is a special get_blocks_t callback which is used by
1660 * ext4_da_write_begin(). It will either return mapped block or
1661 * reserve space for a single block.
1663 * For delayed buffer_head we have BH_Mapped, BH_New, BH_Delay set.
1664 * We also have b_blocknr = -1 and b_bdev initialized properly
1666 * For unwritten buffer_head we have BH_Mapped, BH_New, BH_Unwritten set.
1667 * We also have b_blocknr = physicalblock mapping unwritten extent and b_bdev
1668 * initialized properly.
1670 int ext4_da_get_block_prep(struct inode *inode, sector_t iblock,
1671 struct buffer_head *bh, int create)
1673 struct ext4_map_blocks map;
1676 BUG_ON(create == 0);
1677 BUG_ON(bh->b_size != inode->i_sb->s_blocksize);
1679 map.m_lblk = iblock;
1683 * first, we need to know whether the block is allocated already
1684 * preallocated blocks are unmapped but should treated
1685 * the same as allocated blocks.
1687 ret = ext4_da_map_blocks(inode, iblock, &map, bh);
1691 map_bh(bh, inode->i_sb, map.m_pblk);
1692 bh->b_state = (bh->b_state & ~EXT4_MAP_FLAGS) | map.m_flags;
1694 if (buffer_unwritten(bh)) {
1695 /* A delayed write to unwritten bh should be marked
1696 * new and mapped. Mapped ensures that we don't do
1697 * get_block multiple times when we write to the same
1698 * offset and new ensures that we do proper zero out
1699 * for partial write.
1702 set_buffer_mapped(bh);
1707 static int bget_one(handle_t *handle, struct buffer_head *bh)
1713 static int bput_one(handle_t *handle, struct buffer_head *bh)
1719 static int __ext4_journalled_writepage(struct page *page,
1722 struct address_space *mapping = page->mapping;
1723 struct inode *inode = mapping->host;
1724 struct buffer_head *page_bufs = NULL;
1725 handle_t *handle = NULL;
1726 int ret = 0, err = 0;
1727 int inline_data = ext4_has_inline_data(inode);
1728 struct buffer_head *inode_bh = NULL;
1730 ClearPageChecked(page);
1733 BUG_ON(page->index != 0);
1734 BUG_ON(len > ext4_get_max_inline_size(inode));
1735 inode_bh = ext4_journalled_write_inline_data(inode, len, page);
1736 if (inode_bh == NULL)
1739 page_bufs = page_buffers(page);
1744 ext4_walk_page_buffers(handle, page_bufs, 0, len,
1747 /* As soon as we unlock the page, it can go away, but we have
1748 * references to buffers so we are safe */
1751 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
1752 ext4_writepage_trans_blocks(inode));
1753 if (IS_ERR(handle)) {
1754 ret = PTR_ERR(handle);
1758 BUG_ON(!ext4_handle_valid(handle));
1761 ret = ext4_journal_get_write_access(handle, inode_bh);
1763 err = ext4_handle_dirty_metadata(handle, inode, inode_bh);
1766 ret = ext4_walk_page_buffers(handle, page_bufs, 0, len, NULL,
1767 do_journal_get_write_access);
1769 err = ext4_walk_page_buffers(handle, page_bufs, 0, len, NULL,
1774 EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
1775 err = ext4_journal_stop(handle);
1779 if (!ext4_has_inline_data(inode))
1780 ext4_walk_page_buffers(NULL, page_bufs, 0, len,
1782 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
1789 * Note that we don't need to start a transaction unless we're journaling data
1790 * because we should have holes filled from ext4_page_mkwrite(). We even don't
1791 * need to file the inode to the transaction's list in ordered mode because if
1792 * we are writing back data added by write(), the inode is already there and if
1793 * we are writing back data modified via mmap(), no one guarantees in which
1794 * transaction the data will hit the disk. In case we are journaling data, we
1795 * cannot start transaction directly because transaction start ranks above page
1796 * lock so we have to do some magic.
1798 * This function can get called via...
1799 * - ext4_writepages after taking page lock (have journal handle)
1800 * - journal_submit_inode_data_buffers (no journal handle)
1801 * - shrink_page_list via the kswapd/direct reclaim (no journal handle)
1802 * - grab_page_cache when doing write_begin (have journal handle)
1804 * We don't do any block allocation in this function. If we have page with
1805 * multiple blocks we need to write those buffer_heads that are mapped. This
1806 * is important for mmaped based write. So if we do with blocksize 1K
1807 * truncate(f, 1024);
1808 * a = mmap(f, 0, 4096);
1810 * truncate(f, 4096);
1811 * we have in the page first buffer_head mapped via page_mkwrite call back
1812 * but other buffer_heads would be unmapped but dirty (dirty done via the
1813 * do_wp_page). So writepage should write the first block. If we modify
1814 * the mmap area beyond 1024 we will again get a page_fault and the
1815 * page_mkwrite callback will do the block allocation and mark the
1816 * buffer_heads mapped.
1818 * We redirty the page if we have any buffer_heads that is either delay or
1819 * unwritten in the page.
1821 * We can get recursively called as show below.
1823 * ext4_writepage() -> kmalloc() -> __alloc_pages() -> page_launder() ->
1826 * But since we don't do any block allocation we should not deadlock.
1827 * Page also have the dirty flag cleared so we don't get recurive page_lock.
1829 static int ext4_writepage(struct page *page,
1830 struct writeback_control *wbc)
1835 struct buffer_head *page_bufs = NULL;
1836 struct inode *inode = page->mapping->host;
1837 struct ext4_io_submit io_submit;
1838 bool keep_towrite = false;
1840 trace_ext4_writepage(page);
1841 size = i_size_read(inode);
1842 if (page->index == size >> PAGE_CACHE_SHIFT)
1843 len = size & ~PAGE_CACHE_MASK;
1845 len = PAGE_CACHE_SIZE;
1847 page_bufs = page_buffers(page);
1849 * We cannot do block allocation or other extent handling in this
1850 * function. If there are buffers needing that, we have to redirty
1851 * the page. But we may reach here when we do a journal commit via
1852 * journal_submit_inode_data_buffers() and in that case we must write
1853 * allocated buffers to achieve data=ordered mode guarantees.
1855 if (ext4_walk_page_buffers(NULL, page_bufs, 0, len, NULL,
1856 ext4_bh_delay_or_unwritten)) {
1857 redirty_page_for_writepage(wbc, page);
1858 if (current->flags & PF_MEMALLOC) {
1860 * For memory cleaning there's no point in writing only
1861 * some buffers. So just bail out. Warn if we came here
1862 * from direct reclaim.
1864 WARN_ON_ONCE((current->flags & (PF_MEMALLOC|PF_KSWAPD))
1869 keep_towrite = true;
1872 if (PageChecked(page) && ext4_should_journal_data(inode))
1874 * It's mmapped pagecache. Add buffers and journal it. There
1875 * doesn't seem much point in redirtying the page here.
1877 return __ext4_journalled_writepage(page, len);
1879 ext4_io_submit_init(&io_submit, wbc);
1880 io_submit.io_end = ext4_init_io_end(inode, GFP_NOFS);
1881 if (!io_submit.io_end) {
1882 redirty_page_for_writepage(wbc, page);
1886 ret = ext4_bio_write_page(&io_submit, page, len, wbc, keep_towrite);
1887 ext4_io_submit(&io_submit);
1888 /* Drop io_end reference we got from init */
1889 ext4_put_io_end_defer(io_submit.io_end);
1893 static int mpage_submit_page(struct mpage_da_data *mpd, struct page *page)
1896 loff_t size = i_size_read(mpd->inode);
1899 BUG_ON(page->index != mpd->first_page);
1900 if (page->index == size >> PAGE_CACHE_SHIFT)
1901 len = size & ~PAGE_CACHE_MASK;
1903 len = PAGE_CACHE_SIZE;
1904 clear_page_dirty_for_io(page);
1905 err = ext4_bio_write_page(&mpd->io_submit, page, len, mpd->wbc, false);
1907 mpd->wbc->nr_to_write--;
1913 #define BH_FLAGS ((1 << BH_Unwritten) | (1 << BH_Delay))
1916 * mballoc gives us at most this number of blocks...
1917 * XXX: That seems to be only a limitation of ext4_mb_normalize_request().
1918 * The rest of mballoc seems to handle chunks up to full group size.
1920 #define MAX_WRITEPAGES_EXTENT_LEN 2048
1923 * mpage_add_bh_to_extent - try to add bh to extent of blocks to map
1925 * @mpd - extent of blocks
1926 * @lblk - logical number of the block in the file
1927 * @bh - buffer head we want to add to the extent
1929 * The function is used to collect contig. blocks in the same state. If the
1930 * buffer doesn't require mapping for writeback and we haven't started the
1931 * extent of buffers to map yet, the function returns 'true' immediately - the
1932 * caller can write the buffer right away. Otherwise the function returns true
1933 * if the block has been added to the extent, false if the block couldn't be
1936 static bool mpage_add_bh_to_extent(struct mpage_da_data *mpd, ext4_lblk_t lblk,
1937 struct buffer_head *bh)
1939 struct ext4_map_blocks *map = &mpd->map;
1941 /* Buffer that doesn't need mapping for writeback? */
1942 if (!buffer_dirty(bh) || !buffer_mapped(bh) ||
1943 (!buffer_delay(bh) && !buffer_unwritten(bh))) {
1944 /* So far no extent to map => we write the buffer right away */
1945 if (map->m_len == 0)
1950 /* First block in the extent? */
1951 if (map->m_len == 0) {
1954 map->m_flags = bh->b_state & BH_FLAGS;
1958 /* Don't go larger than mballoc is willing to allocate */
1959 if (map->m_len >= MAX_WRITEPAGES_EXTENT_LEN)
1962 /* Can we merge the block to our big extent? */
1963 if (lblk == map->m_lblk + map->m_len &&
1964 (bh->b_state & BH_FLAGS) == map->m_flags) {
1972 * mpage_process_page_bufs - submit page buffers for IO or add them to extent
1974 * @mpd - extent of blocks for mapping
1975 * @head - the first buffer in the page
1976 * @bh - buffer we should start processing from
1977 * @lblk - logical number of the block in the file corresponding to @bh
1979 * Walk through page buffers from @bh upto @head (exclusive) and either submit
1980 * the page for IO if all buffers in this page were mapped and there's no
1981 * accumulated extent of buffers to map or add buffers in the page to the
1982 * extent of buffers to map. The function returns 1 if the caller can continue
1983 * by processing the next page, 0 if it should stop adding buffers to the
1984 * extent to map because we cannot extend it anymore. It can also return value
1985 * < 0 in case of error during IO submission.
1987 static int mpage_process_page_bufs(struct mpage_da_data *mpd,
1988 struct buffer_head *head,
1989 struct buffer_head *bh,
1992 struct inode *inode = mpd->inode;
1994 ext4_lblk_t blocks = (i_size_read(inode) + (1 << inode->i_blkbits) - 1)
1995 >> inode->i_blkbits;
1998 BUG_ON(buffer_locked(bh));
2000 if (lblk >= blocks || !mpage_add_bh_to_extent(mpd, lblk, bh)) {
2001 /* Found extent to map? */
2004 /* Everything mapped so far and we hit EOF */
2007 } while (lblk++, (bh = bh->b_this_page) != head);
2008 /* So far everything mapped? Submit the page for IO. */
2009 if (mpd->map.m_len == 0) {
2010 err = mpage_submit_page(mpd, head->b_page);
2014 return lblk < blocks;
2018 * mpage_map_buffers - update buffers corresponding to changed extent and
2019 * submit fully mapped pages for IO
2021 * @mpd - description of extent to map, on return next extent to map
2023 * Scan buffers corresponding to changed extent (we expect corresponding pages
2024 * to be already locked) and update buffer state according to new extent state.
2025 * We map delalloc buffers to their physical location, clear unwritten bits,
2026 * and mark buffers as uninit when we perform writes to uninitialized extents
2027 * and do extent conversion after IO is finished. If the last page is not fully
2028 * mapped, we update @map to the next extent in the last page that needs
2029 * mapping. Otherwise we submit the page for IO.
2031 static int mpage_map_and_submit_buffers(struct mpage_da_data *mpd)
2033 struct pagevec pvec;
2035 struct inode *inode = mpd->inode;
2036 struct buffer_head *head, *bh;
2037 int bpp_bits = PAGE_CACHE_SHIFT - inode->i_blkbits;
2043 start = mpd->map.m_lblk >> bpp_bits;
2044 end = (mpd->map.m_lblk + mpd->map.m_len - 1) >> bpp_bits;
2045 lblk = start << bpp_bits;
2046 pblock = mpd->map.m_pblk;
2048 pagevec_init(&pvec, 0);
2049 while (start <= end) {
2050 nr_pages = pagevec_lookup(&pvec, inode->i_mapping, start,
2054 for (i = 0; i < nr_pages; i++) {
2055 struct page *page = pvec.pages[i];
2057 if (page->index > end)
2059 /* Up to 'end' pages must be contiguous */
2060 BUG_ON(page->index != start);
2061 bh = head = page_buffers(page);
2063 if (lblk < mpd->map.m_lblk)
2065 if (lblk >= mpd->map.m_lblk + mpd->map.m_len) {
2067 * Buffer after end of mapped extent.
2068 * Find next buffer in the page to map.
2071 mpd->map.m_flags = 0;
2073 * FIXME: If dioread_nolock supports
2074 * blocksize < pagesize, we need to make
2075 * sure we add size mapped so far to
2076 * io_end->size as the following call
2077 * can submit the page for IO.
2079 err = mpage_process_page_bufs(mpd, head,
2081 pagevec_release(&pvec);
2086 if (buffer_delay(bh)) {
2087 clear_buffer_delay(bh);
2088 bh->b_blocknr = pblock++;
2090 clear_buffer_unwritten(bh);
2091 } while (lblk++, (bh = bh->b_this_page) != head);
2094 * FIXME: This is going to break if dioread_nolock
2095 * supports blocksize < pagesize as we will try to
2096 * convert potentially unmapped parts of inode.
2098 mpd->io_submit.io_end->size += PAGE_CACHE_SIZE;
2099 /* Page fully mapped - let IO run! */
2100 err = mpage_submit_page(mpd, page);
2102 pagevec_release(&pvec);
2107 pagevec_release(&pvec);
2109 /* Extent fully mapped and matches with page boundary. We are done. */
2111 mpd->map.m_flags = 0;
2115 static int mpage_map_one_extent(handle_t *handle, struct mpage_da_data *mpd)
2117 struct inode *inode = mpd->inode;
2118 struct ext4_map_blocks *map = &mpd->map;
2119 int get_blocks_flags;
2122 trace_ext4_da_write_pages_extent(inode, map);
2124 * Call ext4_map_blocks() to allocate any delayed allocation blocks, or
2125 * to convert an uninitialized extent to be initialized (in the case
2126 * where we have written into one or more preallocated blocks). It is
2127 * possible that we're going to need more metadata blocks than
2128 * previously reserved. However we must not fail because we're in
2129 * writeback and there is nothing we can do about it so it might result
2130 * in data loss. So use reserved blocks to allocate metadata if
2133 * We pass in the magic EXT4_GET_BLOCKS_DELALLOC_RESERVE if the blocks
2134 * in question are delalloc blocks. This affects functions in many
2135 * different parts of the allocation call path. This flag exists
2136 * primarily because we don't want to change *many* call functions, so
2137 * ext4_map_blocks() will set the EXT4_STATE_DELALLOC_RESERVED flag
2138 * once the inode's allocation semaphore is taken.
2140 get_blocks_flags = EXT4_GET_BLOCKS_CREATE |
2141 EXT4_GET_BLOCKS_METADATA_NOFAIL;
2142 if (ext4_should_dioread_nolock(inode))
2143 get_blocks_flags |= EXT4_GET_BLOCKS_IO_CREATE_EXT;
2144 if (map->m_flags & (1 << BH_Delay))
2145 get_blocks_flags |= EXT4_GET_BLOCKS_DELALLOC_RESERVE;
2147 err = ext4_map_blocks(handle, inode, map, get_blocks_flags);
2150 if (map->m_flags & EXT4_MAP_UNINIT) {
2151 if (!mpd->io_submit.io_end->handle &&
2152 ext4_handle_valid(handle)) {
2153 mpd->io_submit.io_end->handle = handle->h_rsv_handle;
2154 handle->h_rsv_handle = NULL;
2156 ext4_set_io_unwritten_flag(inode, mpd->io_submit.io_end);
2159 BUG_ON(map->m_len == 0);
2160 if (map->m_flags & EXT4_MAP_NEW) {
2161 struct block_device *bdev = inode->i_sb->s_bdev;
2164 for (i = 0; i < map->m_len; i++)
2165 unmap_underlying_metadata(bdev, map->m_pblk + i);
2171 * mpage_map_and_submit_extent - map extent starting at mpd->lblk of length
2172 * mpd->len and submit pages underlying it for IO
2174 * @handle - handle for journal operations
2175 * @mpd - extent to map
2176 * @give_up_on_write - we set this to true iff there is a fatal error and there
2177 * is no hope of writing the data. The caller should discard
2178 * dirty pages to avoid infinite loops.
2180 * The function maps extent starting at mpd->lblk of length mpd->len. If it is
2181 * delayed, blocks are allocated, if it is unwritten, we may need to convert
2182 * them to initialized or split the described range from larger unwritten
2183 * extent. Note that we need not map all the described range since allocation
2184 * can return less blocks or the range is covered by more unwritten extents. We
2185 * cannot map more because we are limited by reserved transaction credits. On
2186 * the other hand we always make sure that the last touched page is fully
2187 * mapped so that it can be written out (and thus forward progress is
2188 * guaranteed). After mapping we submit all mapped pages for IO.
2190 static int mpage_map_and_submit_extent(handle_t *handle,
2191 struct mpage_da_data *mpd,
2192 bool *give_up_on_write)
2194 struct inode *inode = mpd->inode;
2195 struct ext4_map_blocks *map = &mpd->map;
2199 mpd->io_submit.io_end->offset =
2200 ((loff_t)map->m_lblk) << inode->i_blkbits;
2202 err = mpage_map_one_extent(handle, mpd);
2204 struct super_block *sb = inode->i_sb;
2206 if (EXT4_SB(sb)->s_mount_flags & EXT4_MF_FS_ABORTED)
2207 goto invalidate_dirty_pages;
2209 * Let the uper layers retry transient errors.
2210 * In the case of ENOSPC, if ext4_count_free_blocks()
2211 * is non-zero, a commit should free up blocks.
2213 if ((err == -ENOMEM) ||
2214 (err == -ENOSPC && ext4_count_free_clusters(sb)))
2216 ext4_msg(sb, KERN_CRIT,
2217 "Delayed block allocation failed for "
2218 "inode %lu at logical offset %llu with"
2219 " max blocks %u with error %d",
2221 (unsigned long long)map->m_lblk,
2222 (unsigned)map->m_len, -err);
2223 ext4_msg(sb, KERN_CRIT,
2224 "This should not happen!! Data will "
2227 ext4_print_free_blocks(inode);
2228 invalidate_dirty_pages:
2229 *give_up_on_write = true;
2233 * Update buffer state, submit mapped pages, and get us new
2236 err = mpage_map_and_submit_buffers(mpd);
2239 } while (map->m_len);
2242 * Update on-disk size after IO is submitted. Races with
2243 * truncate are avoided by checking i_size under i_data_sem.
2245 disksize = ((loff_t)mpd->first_page) << PAGE_CACHE_SHIFT;
2246 if (disksize > EXT4_I(inode)->i_disksize) {
2250 down_write(&EXT4_I(inode)->i_data_sem);
2251 i_size = i_size_read(inode);
2252 if (disksize > i_size)
2254 if (disksize > EXT4_I(inode)->i_disksize)
2255 EXT4_I(inode)->i_disksize = disksize;
2256 err2 = ext4_mark_inode_dirty(handle, inode);
2257 up_write(&EXT4_I(inode)->i_data_sem);
2259 ext4_error(inode->i_sb,
2260 "Failed to mark inode %lu dirty",
2269 * Calculate the total number of credits to reserve for one writepages
2270 * iteration. This is called from ext4_writepages(). We map an extent of
2271 * up to MAX_WRITEPAGES_EXTENT_LEN blocks and then we go on and finish mapping
2272 * the last partial page. So in total we can map MAX_WRITEPAGES_EXTENT_LEN +
2273 * bpp - 1 blocks in bpp different extents.
2275 static int ext4_da_writepages_trans_blocks(struct inode *inode)
2277 int bpp = ext4_journal_blocks_per_page(inode);
2279 return ext4_meta_trans_blocks(inode,
2280 MAX_WRITEPAGES_EXTENT_LEN + bpp - 1, bpp);
2284 * mpage_prepare_extent_to_map - find & lock contiguous range of dirty pages
2285 * and underlying extent to map
2287 * @mpd - where to look for pages
2289 * Walk dirty pages in the mapping. If they are fully mapped, submit them for
2290 * IO immediately. When we find a page which isn't mapped we start accumulating
2291 * extent of buffers underlying these pages that needs mapping (formed by
2292 * either delayed or unwritten buffers). We also lock the pages containing
2293 * these buffers. The extent found is returned in @mpd structure (starting at
2294 * mpd->lblk with length mpd->len blocks).
2296 * Note that this function can attach bios to one io_end structure which are
2297 * neither logically nor physically contiguous. Although it may seem as an
2298 * unnecessary complication, it is actually inevitable in blocksize < pagesize
2299 * case as we need to track IO to all buffers underlying a page in one io_end.
2301 static int mpage_prepare_extent_to_map(struct mpage_da_data *mpd)
2303 struct address_space *mapping = mpd->inode->i_mapping;
2304 struct pagevec pvec;
2305 unsigned int nr_pages;
2306 long left = mpd->wbc->nr_to_write;
2307 pgoff_t index = mpd->first_page;
2308 pgoff_t end = mpd->last_page;
2311 int blkbits = mpd->inode->i_blkbits;
2313 struct buffer_head *head;
2315 if (mpd->wbc->sync_mode == WB_SYNC_ALL || mpd->wbc->tagged_writepages)
2316 tag = PAGECACHE_TAG_TOWRITE;
2318 tag = PAGECACHE_TAG_DIRTY;
2320 pagevec_init(&pvec, 0);
2322 mpd->next_page = index;
2323 while (index <= end) {
2324 nr_pages = pagevec_lookup_tag(&pvec, mapping, &index, tag,
2325 min(end - index, (pgoff_t)PAGEVEC_SIZE-1) + 1);
2329 for (i = 0; i < nr_pages; i++) {
2330 struct page *page = pvec.pages[i];
2333 * At this point, the page may be truncated or
2334 * invalidated (changing page->mapping to NULL), or
2335 * even swizzled back from swapper_space to tmpfs file
2336 * mapping. However, page->index will not change
2337 * because we have a reference on the page.
2339 if (page->index > end)
2343 * Accumulated enough dirty pages? This doesn't apply
2344 * to WB_SYNC_ALL mode. For integrity sync we have to
2345 * keep going because someone may be concurrently
2346 * dirtying pages, and we might have synced a lot of
2347 * newly appeared dirty pages, but have not synced all
2348 * of the old dirty pages.
2350 if (mpd->wbc->sync_mode == WB_SYNC_NONE && left <= 0)
2353 /* If we can't merge this page, we are done. */
2354 if (mpd->map.m_len > 0 && mpd->next_page != page->index)
2359 * If the page is no longer dirty, or its mapping no
2360 * longer corresponds to inode we are writing (which
2361 * means it has been truncated or invalidated), or the
2362 * page is already under writeback and we are not doing
2363 * a data integrity writeback, skip the page
2365 if (!PageDirty(page) ||
2366 (PageWriteback(page) &&
2367 (mpd->wbc->sync_mode == WB_SYNC_NONE)) ||
2368 unlikely(page->mapping != mapping)) {
2373 wait_on_page_writeback(page);
2374 BUG_ON(PageWriteback(page));
2376 if (mpd->map.m_len == 0)
2377 mpd->first_page = page->index;
2378 mpd->next_page = page->index + 1;
2379 /* Add all dirty buffers to mpd */
2380 lblk = ((ext4_lblk_t)page->index) <<
2381 (PAGE_CACHE_SHIFT - blkbits);
2382 head = page_buffers(page);
2383 err = mpage_process_page_bufs(mpd, head, head, lblk);
2389 pagevec_release(&pvec);
2394 pagevec_release(&pvec);
2398 static int __writepage(struct page *page, struct writeback_control *wbc,
2401 struct address_space *mapping = data;
2402 int ret = ext4_writepage(page, wbc);
2403 mapping_set_error(mapping, ret);
2407 static int ext4_writepages(struct address_space *mapping,
2408 struct writeback_control *wbc)
2410 pgoff_t writeback_index = 0;
2411 long nr_to_write = wbc->nr_to_write;
2412 int range_whole = 0;
2414 handle_t *handle = NULL;
2415 struct mpage_da_data mpd;
2416 struct inode *inode = mapping->host;
2417 int needed_blocks, rsv_blocks = 0, ret = 0;
2418 struct ext4_sb_info *sbi = EXT4_SB(mapping->host->i_sb);
2420 struct blk_plug plug;
2421 bool give_up_on_write = false;
2423 trace_ext4_writepages(inode, wbc);
2426 * No pages to write? This is mainly a kludge to avoid starting
2427 * a transaction for special inodes like journal inode on last iput()
2428 * because that could violate lock ordering on umount
2430 if (!mapping->nrpages || !mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
2431 goto out_writepages;
2433 if (ext4_should_journal_data(inode)) {
2434 struct blk_plug plug;
2436 blk_start_plug(&plug);
2437 ret = write_cache_pages(mapping, wbc, __writepage, mapping);
2438 blk_finish_plug(&plug);
2439 goto out_writepages;
2443 * If the filesystem has aborted, it is read-only, so return
2444 * right away instead of dumping stack traces later on that
2445 * will obscure the real source of the problem. We test
2446 * EXT4_MF_FS_ABORTED instead of sb->s_flag's MS_RDONLY because
2447 * the latter could be true if the filesystem is mounted
2448 * read-only, and in that case, ext4_writepages should
2449 * *never* be called, so if that ever happens, we would want
2452 if (unlikely(sbi->s_mount_flags & EXT4_MF_FS_ABORTED)) {
2454 goto out_writepages;
2457 if (ext4_should_dioread_nolock(inode)) {
2459 * We may need to convert up to one extent per block in
2460 * the page and we may dirty the inode.
2462 rsv_blocks = 1 + (PAGE_CACHE_SIZE >> inode->i_blkbits);
2466 * If we have inline data and arrive here, it means that
2467 * we will soon create the block for the 1st page, so
2468 * we'd better clear the inline data here.
2470 if (ext4_has_inline_data(inode)) {
2471 /* Just inode will be modified... */
2472 handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
2473 if (IS_ERR(handle)) {
2474 ret = PTR_ERR(handle);
2475 goto out_writepages;
2477 BUG_ON(ext4_test_inode_state(inode,
2478 EXT4_STATE_MAY_INLINE_DATA));
2479 ext4_destroy_inline_data(handle, inode);
2480 ext4_journal_stop(handle);
2483 if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
2486 if (wbc->range_cyclic) {
2487 writeback_index = mapping->writeback_index;
2488 if (writeback_index)
2490 mpd.first_page = writeback_index;
2493 mpd.first_page = wbc->range_start >> PAGE_CACHE_SHIFT;
2494 mpd.last_page = wbc->range_end >> PAGE_CACHE_SHIFT;
2499 ext4_io_submit_init(&mpd.io_submit, wbc);
2501 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
2502 tag_pages_for_writeback(mapping, mpd.first_page, mpd.last_page);
2504 blk_start_plug(&plug);
2505 while (!done && mpd.first_page <= mpd.last_page) {
2506 /* For each extent of pages we use new io_end */
2507 mpd.io_submit.io_end = ext4_init_io_end(inode, GFP_KERNEL);
2508 if (!mpd.io_submit.io_end) {
2514 * We have two constraints: We find one extent to map and we
2515 * must always write out whole page (makes a difference when
2516 * blocksize < pagesize) so that we don't block on IO when we
2517 * try to write out the rest of the page. Journalled mode is
2518 * not supported by delalloc.
2520 BUG_ON(ext4_should_journal_data(inode));
2521 needed_blocks = ext4_da_writepages_trans_blocks(inode);
2523 /* start a new transaction */
2524 handle = ext4_journal_start_with_reserve(inode,
2525 EXT4_HT_WRITE_PAGE, needed_blocks, rsv_blocks);
2526 if (IS_ERR(handle)) {
2527 ret = PTR_ERR(handle);
2528 ext4_msg(inode->i_sb, KERN_CRIT, "%s: jbd2_start: "
2529 "%ld pages, ino %lu; err %d", __func__,
2530 wbc->nr_to_write, inode->i_ino, ret);
2531 /* Release allocated io_end */
2532 ext4_put_io_end(mpd.io_submit.io_end);
2536 trace_ext4_da_write_pages(inode, mpd.first_page, mpd.wbc);
2537 ret = mpage_prepare_extent_to_map(&mpd);
2540 ret = mpage_map_and_submit_extent(handle, &mpd,
2544 * We scanned the whole range (or exhausted
2545 * nr_to_write), submitted what was mapped and
2546 * didn't find anything needing mapping. We are
2552 ext4_journal_stop(handle);
2553 /* Submit prepared bio */
2554 ext4_io_submit(&mpd.io_submit);
2555 /* Unlock pages we didn't use */
2556 mpage_release_unused_pages(&mpd, give_up_on_write);
2557 /* Drop our io_end reference we got from init */
2558 ext4_put_io_end(mpd.io_submit.io_end);
2560 if (ret == -ENOSPC && sbi->s_journal) {
2562 * Commit the transaction which would
2563 * free blocks released in the transaction
2566 jbd2_journal_force_commit_nested(sbi->s_journal);
2570 /* Fatal error - ENOMEM, EIO... */
2574 blk_finish_plug(&plug);
2575 if (!ret && !cycled && wbc->nr_to_write > 0) {
2577 mpd.last_page = writeback_index - 1;
2583 if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
2585 * Set the writeback_index so that range_cyclic
2586 * mode will write it back later
2588 mapping->writeback_index = mpd.first_page;
2591 trace_ext4_writepages_result(inode, wbc, ret,
2592 nr_to_write - wbc->nr_to_write);
2596 static int ext4_nonda_switch(struct super_block *sb)
2598 s64 free_clusters, dirty_clusters;
2599 struct ext4_sb_info *sbi = EXT4_SB(sb);
2602 * switch to non delalloc mode if we are running low
2603 * on free block. The free block accounting via percpu
2604 * counters can get slightly wrong with percpu_counter_batch getting
2605 * accumulated on each CPU without updating global counters
2606 * Delalloc need an accurate free block accounting. So switch
2607 * to non delalloc when we are near to error range.
2610 percpu_counter_read_positive(&sbi->s_freeclusters_counter);
2612 percpu_counter_read_positive(&sbi->s_dirtyclusters_counter);
2614 * Start pushing delalloc when 1/2 of free blocks are dirty.
2616 if (dirty_clusters && (free_clusters < 2 * dirty_clusters))
2617 try_to_writeback_inodes_sb(sb, WB_REASON_FS_FREE_SPACE);
2619 if (2 * free_clusters < 3 * dirty_clusters ||
2620 free_clusters < (dirty_clusters + EXT4_FREECLUSTERS_WATERMARK)) {
2622 * free block count is less than 150% of dirty blocks
2623 * or free blocks is less than watermark
2630 static int ext4_da_write_begin(struct file *file, struct address_space *mapping,
2631 loff_t pos, unsigned len, unsigned flags,
2632 struct page **pagep, void **fsdata)
2634 int ret, retries = 0;
2637 struct inode *inode = mapping->host;
2640 index = pos >> PAGE_CACHE_SHIFT;
2642 if (ext4_nonda_switch(inode->i_sb)) {
2643 *fsdata = (void *)FALL_BACK_TO_NONDELALLOC;
2644 return ext4_write_begin(file, mapping, pos,
2645 len, flags, pagep, fsdata);
2647 *fsdata = (void *)0;
2648 trace_ext4_da_write_begin(inode, pos, len, flags);
2650 if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
2651 ret = ext4_da_write_inline_data_begin(mapping, inode,
2661 * grab_cache_page_write_begin() can take a long time if the
2662 * system is thrashing due to memory pressure, or if the page
2663 * is being written back. So grab it first before we start
2664 * the transaction handle. This also allows us to allocate
2665 * the page (if needed) without using GFP_NOFS.
2668 page = grab_cache_page_write_begin(mapping, index, flags);
2674 * With delayed allocation, we don't log the i_disksize update
2675 * if there is delayed block allocation. But we still need
2676 * to journalling the i_disksize update if writes to the end
2677 * of file which has an already mapped buffer.
2680 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE, 1);
2681 if (IS_ERR(handle)) {
2682 page_cache_release(page);
2683 return PTR_ERR(handle);
2687 if (page->mapping != mapping) {
2688 /* The page got truncated from under us */
2690 page_cache_release(page);
2691 ext4_journal_stop(handle);
2694 /* In case writeback began while the page was unlocked */
2695 wait_for_stable_page(page);
2697 ret = __block_write_begin(page, pos, len, ext4_da_get_block_prep);
2700 ext4_journal_stop(handle);
2702 * block_write_begin may have instantiated a few blocks
2703 * outside i_size. Trim these off again. Don't need
2704 * i_size_read because we hold i_mutex.
2706 if (pos + len > inode->i_size)
2707 ext4_truncate_failed_write(inode);
2709 if (ret == -ENOSPC &&
2710 ext4_should_retry_alloc(inode->i_sb, &retries))
2713 page_cache_release(page);
2722 * Check if we should update i_disksize
2723 * when write to the end of file but not require block allocation
2725 static int ext4_da_should_update_i_disksize(struct page *page,
2726 unsigned long offset)
2728 struct buffer_head *bh;
2729 struct inode *inode = page->mapping->host;
2733 bh = page_buffers(page);
2734 idx = offset >> inode->i_blkbits;
2736 for (i = 0; i < idx; i++)
2737 bh = bh->b_this_page;
2739 if (!buffer_mapped(bh) || (buffer_delay(bh)) || buffer_unwritten(bh))
2744 static int ext4_da_write_end(struct file *file,
2745 struct address_space *mapping,
2746 loff_t pos, unsigned len, unsigned copied,
2747 struct page *page, void *fsdata)
2749 struct inode *inode = mapping->host;
2751 handle_t *handle = ext4_journal_current_handle();
2753 unsigned long start, end;
2754 int write_mode = (int)(unsigned long)fsdata;
2756 if (write_mode == FALL_BACK_TO_NONDELALLOC)
2757 return ext4_write_end(file, mapping, pos,
2758 len, copied, page, fsdata);
2760 trace_ext4_da_write_end(inode, pos, len, copied);
2761 start = pos & (PAGE_CACHE_SIZE - 1);
2762 end = start + copied - 1;
2765 * generic_write_end() will run mark_inode_dirty() if i_size
2766 * changes. So let's piggyback the i_disksize mark_inode_dirty
2769 new_i_size = pos + copied;
2770 if (copied && new_i_size > EXT4_I(inode)->i_disksize) {
2771 if (ext4_has_inline_data(inode) ||
2772 ext4_da_should_update_i_disksize(page, end)) {
2773 down_write(&EXT4_I(inode)->i_data_sem);
2774 if (new_i_size > EXT4_I(inode)->i_disksize)
2775 EXT4_I(inode)->i_disksize = new_i_size;
2776 up_write(&EXT4_I(inode)->i_data_sem);
2777 /* We need to mark inode dirty even if
2778 * new_i_size is less that inode->i_size
2779 * bu greater than i_disksize.(hint delalloc)
2781 ext4_mark_inode_dirty(handle, inode);
2785 if (write_mode != CONVERT_INLINE_DATA &&
2786 ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA) &&
2787 ext4_has_inline_data(inode))
2788 ret2 = ext4_da_write_inline_data_end(inode, pos, len, copied,
2791 ret2 = generic_write_end(file, mapping, pos, len, copied,
2797 ret2 = ext4_journal_stop(handle);
2801 return ret ? ret : copied;
2804 static void ext4_da_invalidatepage(struct page *page, unsigned int offset,
2805 unsigned int length)
2808 * Drop reserved blocks
2810 BUG_ON(!PageLocked(page));
2811 if (!page_has_buffers(page))
2814 ext4_da_page_release_reservation(page, offset, length);
2817 ext4_invalidatepage(page, offset, length);
2823 * Force all delayed allocation blocks to be allocated for a given inode.
2825 int ext4_alloc_da_blocks(struct inode *inode)
2827 trace_ext4_alloc_da_blocks(inode);
2829 if (!EXT4_I(inode)->i_reserved_data_blocks &&
2830 !EXT4_I(inode)->i_reserved_meta_blocks)
2834 * We do something simple for now. The filemap_flush() will
2835 * also start triggering a write of the data blocks, which is
2836 * not strictly speaking necessary (and for users of
2837 * laptop_mode, not even desirable). However, to do otherwise
2838 * would require replicating code paths in:
2840 * ext4_writepages() ->
2841 * write_cache_pages() ---> (via passed in callback function)
2842 * __mpage_da_writepage() -->
2843 * mpage_add_bh_to_extent()
2844 * mpage_da_map_blocks()
2846 * The problem is that write_cache_pages(), located in
2847 * mm/page-writeback.c, marks pages clean in preparation for
2848 * doing I/O, which is not desirable if we're not planning on
2851 * We could call write_cache_pages(), and then redirty all of
2852 * the pages by calling redirty_page_for_writepage() but that
2853 * would be ugly in the extreme. So instead we would need to
2854 * replicate parts of the code in the above functions,
2855 * simplifying them because we wouldn't actually intend to
2856 * write out the pages, but rather only collect contiguous
2857 * logical block extents, call the multi-block allocator, and
2858 * then update the buffer heads with the block allocations.
2860 * For now, though, we'll cheat by calling filemap_flush(),
2861 * which will map the blocks, and start the I/O, but not
2862 * actually wait for the I/O to complete.
2864 return filemap_flush(inode->i_mapping);
2868 * bmap() is special. It gets used by applications such as lilo and by
2869 * the swapper to find the on-disk block of a specific piece of data.
2871 * Naturally, this is dangerous if the block concerned is still in the
2872 * journal. If somebody makes a swapfile on an ext4 data-journaling
2873 * filesystem and enables swap, then they may get a nasty shock when the
2874 * data getting swapped to that swapfile suddenly gets overwritten by
2875 * the original zero's written out previously to the journal and
2876 * awaiting writeback in the kernel's buffer cache.
2878 * So, if we see any bmap calls here on a modified, data-journaled file,
2879 * take extra steps to flush any blocks which might be in the cache.
2881 static sector_t ext4_bmap(struct address_space *mapping, sector_t block)
2883 struct inode *inode = mapping->host;
2888 * We can get here for an inline file via the FIBMAP ioctl
2890 if (ext4_has_inline_data(inode))
2893 if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY) &&
2894 test_opt(inode->i_sb, DELALLOC)) {
2896 * With delalloc we want to sync the file
2897 * so that we can make sure we allocate
2900 filemap_write_and_wait(mapping);
2903 if (EXT4_JOURNAL(inode) &&
2904 ext4_test_inode_state(inode, EXT4_STATE_JDATA)) {
2906 * This is a REALLY heavyweight approach, but the use of
2907 * bmap on dirty files is expected to be extremely rare:
2908 * only if we run lilo or swapon on a freshly made file
2909 * do we expect this to happen.
2911 * (bmap requires CAP_SYS_RAWIO so this does not
2912 * represent an unprivileged user DOS attack --- we'd be
2913 * in trouble if mortal users could trigger this path at
2916 * NB. EXT4_STATE_JDATA is not set on files other than
2917 * regular files. If somebody wants to bmap a directory
2918 * or symlink and gets confused because the buffer
2919 * hasn't yet been flushed to disk, they deserve
2920 * everything they get.
2923 ext4_clear_inode_state(inode, EXT4_STATE_JDATA);
2924 journal = EXT4_JOURNAL(inode);
2925 jbd2_journal_lock_updates(journal);
2926 err = jbd2_journal_flush(journal);
2927 jbd2_journal_unlock_updates(journal);
2933 return generic_block_bmap(mapping, block, ext4_get_block);
2936 static int ext4_readpage(struct file *file, struct page *page)
2939 struct inode *inode = page->mapping->host;
2941 trace_ext4_readpage(page);
2943 if (ext4_has_inline_data(inode))
2944 ret = ext4_readpage_inline(inode, page);
2947 return mpage_readpage(page, ext4_get_block);
2953 ext4_readpages(struct file *file, struct address_space *mapping,
2954 struct list_head *pages, unsigned nr_pages)
2956 struct inode *inode = mapping->host;
2958 /* If the file has inline data, no need to do readpages. */
2959 if (ext4_has_inline_data(inode))
2962 return mpage_readpages(mapping, pages, nr_pages, ext4_get_block);
2965 static void ext4_invalidatepage(struct page *page, unsigned int offset,
2966 unsigned int length)
2968 trace_ext4_invalidatepage(page, offset, length);
2970 /* No journalling happens on data buffers when this function is used */
2971 WARN_ON(page_has_buffers(page) && buffer_jbd(page_buffers(page)));
2973 block_invalidatepage(page, offset, length);
2976 static int __ext4_journalled_invalidatepage(struct page *page,
2977 unsigned int offset,
2978 unsigned int length)
2980 journal_t *journal = EXT4_JOURNAL(page->mapping->host);
2982 trace_ext4_journalled_invalidatepage(page, offset, length);
2985 * If it's a full truncate we just forget about the pending dirtying
2987 if (offset == 0 && length == PAGE_CACHE_SIZE)
2988 ClearPageChecked(page);
2990 return jbd2_journal_invalidatepage(journal, page, offset, length);
2993 /* Wrapper for aops... */
2994 static void ext4_journalled_invalidatepage(struct page *page,
2995 unsigned int offset,
2996 unsigned int length)
2998 WARN_ON(__ext4_journalled_invalidatepage(page, offset, length) < 0);
3001 static int ext4_releasepage(struct page *page, gfp_t wait)
3003 journal_t *journal = EXT4_JOURNAL(page->mapping->host);
3005 trace_ext4_releasepage(page);
3007 /* Page has dirty journalled data -> cannot release */
3008 if (PageChecked(page))
3011 return jbd2_journal_try_to_free_buffers(journal, page, wait);
3013 return try_to_free_buffers(page);
3017 * ext4_get_block used when preparing for a DIO write or buffer write.
3018 * We allocate an uinitialized extent if blocks haven't been allocated.
3019 * The extent will be converted to initialized after the IO is complete.
3021 int ext4_get_block_write(struct inode *inode, sector_t iblock,
3022 struct buffer_head *bh_result, int create)
3024 ext4_debug("ext4_get_block_write: inode %lu, create flag %d\n",
3025 inode->i_ino, create);
3026 return _ext4_get_block(inode, iblock, bh_result,
3027 EXT4_GET_BLOCKS_IO_CREATE_EXT);
3030 static int ext4_get_block_write_nolock(struct inode *inode, sector_t iblock,
3031 struct buffer_head *bh_result, int create)
3033 ext4_debug("ext4_get_block_write_nolock: inode %lu, create flag %d\n",
3034 inode->i_ino, create);
3035 return _ext4_get_block(inode, iblock, bh_result,
3036 EXT4_GET_BLOCKS_NO_LOCK);
3039 static void ext4_end_io_dio(struct kiocb *iocb, loff_t offset,
3040 ssize_t size, void *private)
3042 ext4_io_end_t *io_end = iocb->private;
3044 /* if not async direct IO just return */
3048 ext_debug("ext4_end_io_dio(): io_end 0x%p "
3049 "for inode %lu, iocb 0x%p, offset %llu, size %zd\n",
3050 iocb->private, io_end->inode->i_ino, iocb, offset,
3053 iocb->private = NULL;
3054 io_end->offset = offset;
3055 io_end->size = size;
3056 ext4_put_io_end(io_end);
3060 * For ext4 extent files, ext4 will do direct-io write to holes,
3061 * preallocated extents, and those write extend the file, no need to
3062 * fall back to buffered IO.
3064 * For holes, we fallocate those blocks, mark them as uninitialized
3065 * If those blocks were preallocated, we mark sure they are split, but
3066 * still keep the range to write as uninitialized.
3068 * The unwritten extents will be converted to written when DIO is completed.
3069 * For async direct IO, since the IO may still pending when return, we
3070 * set up an end_io call back function, which will do the conversion
3071 * when async direct IO completed.
3073 * If the O_DIRECT write will extend the file then add this inode to the
3074 * orphan list. So recovery will truncate it back to the original size
3075 * if the machine crashes during the write.
3078 static ssize_t ext4_ext_direct_IO(int rw, struct kiocb *iocb,
3079 const struct iovec *iov, loff_t offset,
3080 unsigned long nr_segs)
3082 struct file *file = iocb->ki_filp;
3083 struct inode *inode = file->f_mapping->host;
3085 size_t count = iov_length(iov, nr_segs);
3087 get_block_t *get_block_func = NULL;
3089 loff_t final_size = offset + count;
3090 ext4_io_end_t *io_end = NULL;
3092 /* Use the old path for reads and writes beyond i_size. */
3093 if (rw != WRITE || final_size > inode->i_size)
3094 return ext4_ind_direct_IO(rw, iocb, iov, offset, nr_segs);
3096 BUG_ON(iocb->private == NULL);
3099 * Make all waiters for direct IO properly wait also for extent
3100 * conversion. This also disallows race between truncate() and
3101 * overwrite DIO as i_dio_count needs to be incremented under i_mutex.
3104 atomic_inc(&inode->i_dio_count);
3106 /* If we do a overwrite dio, i_mutex locking can be released */
3107 overwrite = *((int *)iocb->private);
3110 down_read(&EXT4_I(inode)->i_data_sem);
3111 mutex_unlock(&inode->i_mutex);
3115 * We could direct write to holes and fallocate.
3117 * Allocated blocks to fill the hole are marked as
3118 * uninitialized to prevent parallel buffered read to expose
3119 * the stale data before DIO complete the data IO.
3121 * As to previously fallocated extents, ext4 get_block will
3122 * just simply mark the buffer mapped but still keep the
3123 * extents uninitialized.
3125 * For non AIO case, we will convert those unwritten extents
3126 * to written after return back from blockdev_direct_IO.
3128 * For async DIO, the conversion needs to be deferred when the
3129 * IO is completed. The ext4 end_io callback function will be
3130 * called to take care of the conversion work. Here for async
3131 * case, we allocate an io_end structure to hook to the iocb.
3133 iocb->private = NULL;
3134 ext4_inode_aio_set(inode, NULL);
3135 if (!is_sync_kiocb(iocb)) {
3136 io_end = ext4_init_io_end(inode, GFP_NOFS);
3142 * Grab reference for DIO. Will be dropped in ext4_end_io_dio()
3144 iocb->private = ext4_get_io_end(io_end);
3146 * we save the io structure for current async direct
3147 * IO, so that later ext4_map_blocks() could flag the
3148 * io structure whether there is a unwritten extents
3149 * needs to be converted when IO is completed.
3151 ext4_inode_aio_set(inode, io_end);
3155 get_block_func = ext4_get_block_write_nolock;
3157 get_block_func = ext4_get_block_write;
3158 dio_flags = DIO_LOCKING;
3160 ret = __blockdev_direct_IO(rw, iocb, inode,
3161 inode->i_sb->s_bdev, iov,
3169 * Put our reference to io_end. This can free the io_end structure e.g.
3170 * in sync IO case or in case of error. It can even perform extent
3171 * conversion if all bios we submitted finished before we got here.
3172 * Note that in that case iocb->private can be already set to NULL
3176 ext4_inode_aio_set(inode, NULL);
3177 ext4_put_io_end(io_end);
3179 * When no IO was submitted ext4_end_io_dio() was not
3180 * called so we have to put iocb's reference.
3182 if (ret <= 0 && ret != -EIOCBQUEUED && iocb->private) {
3183 WARN_ON(iocb->private != io_end);
3184 WARN_ON(io_end->flag & EXT4_IO_END_UNWRITTEN);
3185 ext4_put_io_end(io_end);
3186 iocb->private = NULL;
3189 if (ret > 0 && !overwrite && ext4_test_inode_state(inode,
3190 EXT4_STATE_DIO_UNWRITTEN)) {
3193 * for non AIO case, since the IO is already
3194 * completed, we could do the conversion right here
3196 err = ext4_convert_unwritten_extents(NULL, inode,
3200 ext4_clear_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN);
3205 inode_dio_done(inode);
3206 /* take i_mutex locking again if we do a ovewrite dio */
3208 up_read(&EXT4_I(inode)->i_data_sem);
3209 mutex_lock(&inode->i_mutex);
3215 static ssize_t ext4_direct_IO(int rw, struct kiocb *iocb,
3216 const struct iovec *iov, loff_t offset,
3217 unsigned long nr_segs)
3219 struct file *file = iocb->ki_filp;
3220 struct inode *inode = file->f_mapping->host;
3224 * If we are doing data journalling we don't support O_DIRECT
3226 if (ext4_should_journal_data(inode))
3229 /* Let buffer I/O handle the inline data case. */
3230 if (ext4_has_inline_data(inode))
3233 trace_ext4_direct_IO_enter(inode, offset, iov_length(iov, nr_segs), rw);
3234 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3235 ret = ext4_ext_direct_IO(rw, iocb, iov, offset, nr_segs);
3237 ret = ext4_ind_direct_IO(rw, iocb, iov, offset, nr_segs);
3238 trace_ext4_direct_IO_exit(inode, offset,
3239 iov_length(iov, nr_segs), rw, ret);
3244 * Pages can be marked dirty completely asynchronously from ext4's journalling
3245 * activity. By filemap_sync_pte(), try_to_unmap_one(), etc. We cannot do
3246 * much here because ->set_page_dirty is called under VFS locks. The page is
3247 * not necessarily locked.
3249 * We cannot just dirty the page and leave attached buffers clean, because the
3250 * buffers' dirty state is "definitive". We cannot just set the buffers dirty
3251 * or jbddirty because all the journalling code will explode.
3253 * So what we do is to mark the page "pending dirty" and next time writepage
3254 * is called, propagate that into the buffers appropriately.
3256 static int ext4_journalled_set_page_dirty(struct page *page)
3258 SetPageChecked(page);
3259 return __set_page_dirty_nobuffers(page);
3262 static const struct address_space_operations ext4_aops = {
3263 .readpage = ext4_readpage,
3264 .readpages = ext4_readpages,
3265 .writepage = ext4_writepage,
3266 .writepages = ext4_writepages,
3267 .write_begin = ext4_write_begin,
3268 .write_end = ext4_write_end,
3270 .invalidatepage = ext4_invalidatepage,
3271 .releasepage = ext4_releasepage,
3272 .direct_IO = ext4_direct_IO,
3273 .migratepage = buffer_migrate_page,
3274 .is_partially_uptodate = block_is_partially_uptodate,
3275 .error_remove_page = generic_error_remove_page,
3278 static const struct address_space_operations ext4_journalled_aops = {
3279 .readpage = ext4_readpage,
3280 .readpages = ext4_readpages,
3281 .writepage = ext4_writepage,
3282 .writepages = ext4_writepages,
3283 .write_begin = ext4_write_begin,
3284 .write_end = ext4_journalled_write_end,
3285 .set_page_dirty = ext4_journalled_set_page_dirty,
3287 .invalidatepage = ext4_journalled_invalidatepage,
3288 .releasepage = ext4_releasepage,
3289 .direct_IO = ext4_direct_IO,
3290 .is_partially_uptodate = block_is_partially_uptodate,
3291 .error_remove_page = generic_error_remove_page,
3294 static const struct address_space_operations ext4_da_aops = {
3295 .readpage = ext4_readpage,
3296 .readpages = ext4_readpages,
3297 .writepage = ext4_writepage,
3298 .writepages = ext4_writepages,
3299 .write_begin = ext4_da_write_begin,
3300 .write_end = ext4_da_write_end,
3302 .invalidatepage = ext4_da_invalidatepage,
3303 .releasepage = ext4_releasepage,
3304 .direct_IO = ext4_direct_IO,
3305 .migratepage = buffer_migrate_page,
3306 .is_partially_uptodate = block_is_partially_uptodate,
3307 .error_remove_page = generic_error_remove_page,
3310 void ext4_set_aops(struct inode *inode)
3312 switch (ext4_inode_journal_mode(inode)) {
3313 case EXT4_INODE_ORDERED_DATA_MODE:
3314 ext4_set_inode_state(inode, EXT4_STATE_ORDERED_MODE);
3316 case EXT4_INODE_WRITEBACK_DATA_MODE:
3317 ext4_clear_inode_state(inode, EXT4_STATE_ORDERED_MODE);
3319 case EXT4_INODE_JOURNAL_DATA_MODE:
3320 inode->i_mapping->a_ops = &ext4_journalled_aops;
3325 if (test_opt(inode->i_sb, DELALLOC))
3326 inode->i_mapping->a_ops = &ext4_da_aops;
3328 inode->i_mapping->a_ops = &ext4_aops;
3332 * ext4_block_truncate_page() zeroes out a mapping from file offset `from'
3333 * up to the end of the block which corresponds to `from'.
3334 * This required during truncate. We need to physically zero the tail end
3335 * of that block so it doesn't yield old data if the file is later grown.
3337 int ext4_block_truncate_page(handle_t *handle,
3338 struct address_space *mapping, loff_t from)
3340 unsigned offset = from & (PAGE_CACHE_SIZE-1);
3343 struct inode *inode = mapping->host;
3345 blocksize = inode->i_sb->s_blocksize;
3346 length = blocksize - (offset & (blocksize - 1));
3348 return ext4_block_zero_page_range(handle, mapping, from, length);
3352 * ext4_block_zero_page_range() zeros out a mapping of length 'length'
3353 * starting from file offset 'from'. The range to be zero'd must
3354 * be contained with in one block. If the specified range exceeds
3355 * the end of the block it will be shortened to end of the block
3356 * that cooresponds to 'from'
3358 int ext4_block_zero_page_range(handle_t *handle,
3359 struct address_space *mapping, loff_t from, loff_t length)
3361 ext4_fsblk_t index = from >> PAGE_CACHE_SHIFT;
3362 unsigned offset = from & (PAGE_CACHE_SIZE-1);
3363 unsigned blocksize, max, pos;
3365 struct inode *inode = mapping->host;
3366 struct buffer_head *bh;
3370 page = find_or_create_page(mapping, from >> PAGE_CACHE_SHIFT,
3371 mapping_gfp_mask(mapping) & ~__GFP_FS);
3375 blocksize = inode->i_sb->s_blocksize;
3376 max = blocksize - (offset & (blocksize - 1));
3379 * correct length if it does not fall between
3380 * 'from' and the end of the block
3382 if (length > max || length < 0)
3385 iblock = index << (PAGE_CACHE_SHIFT - inode->i_sb->s_blocksize_bits);
3387 if (!page_has_buffers(page))
3388 create_empty_buffers(page, blocksize, 0);
3390 /* Find the buffer that contains "offset" */
3391 bh = page_buffers(page);
3393 while (offset >= pos) {
3394 bh = bh->b_this_page;
3398 if (buffer_freed(bh)) {
3399 BUFFER_TRACE(bh, "freed: skip");
3402 if (!buffer_mapped(bh)) {
3403 BUFFER_TRACE(bh, "unmapped");
3404 ext4_get_block(inode, iblock, bh, 0);
3405 /* unmapped? It's a hole - nothing to do */
3406 if (!buffer_mapped(bh)) {
3407 BUFFER_TRACE(bh, "still unmapped");
3412 /* Ok, it's mapped. Make sure it's up-to-date */
3413 if (PageUptodate(page))
3414 set_buffer_uptodate(bh);
3416 if (!buffer_uptodate(bh)) {
3418 ll_rw_block(READ, 1, &bh);
3420 /* Uhhuh. Read error. Complain and punt. */
3421 if (!buffer_uptodate(bh))
3424 if (ext4_should_journal_data(inode)) {
3425 BUFFER_TRACE(bh, "get write access");
3426 err = ext4_journal_get_write_access(handle, bh);
3430 zero_user(page, offset, length);
3431 BUFFER_TRACE(bh, "zeroed end of block");
3433 if (ext4_should_journal_data(inode)) {
3434 err = ext4_handle_dirty_metadata(handle, inode, bh);
3437 mark_buffer_dirty(bh);
3438 if (ext4_test_inode_state(inode, EXT4_STATE_ORDERED_MODE))
3439 err = ext4_jbd2_file_inode(handle, inode);
3444 page_cache_release(page);
3448 int ext4_zero_partial_blocks(handle_t *handle, struct inode *inode,
3449 loff_t lstart, loff_t length)
3451 struct super_block *sb = inode->i_sb;
3452 struct address_space *mapping = inode->i_mapping;
3453 unsigned partial_start, partial_end;
3454 ext4_fsblk_t start, end;
3455 loff_t byte_end = (lstart + length - 1);
3458 partial_start = lstart & (sb->s_blocksize - 1);
3459 partial_end = byte_end & (sb->s_blocksize - 1);
3461 start = lstart >> sb->s_blocksize_bits;
3462 end = byte_end >> sb->s_blocksize_bits;
3464 /* Handle partial zero within the single block */
3466 (partial_start || (partial_end != sb->s_blocksize - 1))) {
3467 err = ext4_block_zero_page_range(handle, mapping,
3471 /* Handle partial zero out on the start of the range */
3472 if (partial_start) {
3473 err = ext4_block_zero_page_range(handle, mapping,
3474 lstart, sb->s_blocksize);
3478 /* Handle partial zero out on the end of the range */
3479 if (partial_end != sb->s_blocksize - 1)
3480 err = ext4_block_zero_page_range(handle, mapping,
3481 byte_end - partial_end,
3486 int ext4_can_truncate(struct inode *inode)
3488 if (S_ISREG(inode->i_mode))
3490 if (S_ISDIR(inode->i_mode))
3492 if (S_ISLNK(inode->i_mode))
3493 return !ext4_inode_is_fast_symlink(inode);
3498 * ext4_punch_hole: punches a hole in a file by releaseing the blocks
3499 * associated with the given offset and length
3501 * @inode: File inode
3502 * @offset: The offset where the hole will begin
3503 * @len: The length of the hole
3505 * Returns: 0 on success or negative on failure
3508 int ext4_punch_hole(struct inode *inode, loff_t offset, loff_t length)
3510 struct super_block *sb = inode->i_sb;
3511 ext4_lblk_t first_block, stop_block;
3512 struct address_space *mapping = inode->i_mapping;
3513 loff_t first_block_offset, last_block_offset;
3515 unsigned int credits;
3518 if (!S_ISREG(inode->i_mode))
3521 trace_ext4_punch_hole(inode, offset, length);
3524 * Write out all dirty pages to avoid race conditions
3525 * Then release them.
3527 if (mapping->nrpages && mapping_tagged(mapping, PAGECACHE_TAG_DIRTY)) {
3528 ret = filemap_write_and_wait_range(mapping, offset,
3529 offset + length - 1);
3534 mutex_lock(&inode->i_mutex);
3535 /* It's not possible punch hole on append only file */
3536 if (IS_APPEND(inode) || IS_IMMUTABLE(inode)) {
3540 if (IS_SWAPFILE(inode)) {
3545 /* No need to punch hole beyond i_size */
3546 if (offset >= inode->i_size)
3550 * If the hole extends beyond i_size, set the hole
3551 * to end after the page that contains i_size
3553 if (offset + length > inode->i_size) {
3554 length = inode->i_size +
3555 PAGE_CACHE_SIZE - (inode->i_size & (PAGE_CACHE_SIZE - 1)) -
3559 if (offset & (sb->s_blocksize - 1) ||
3560 (offset + length) & (sb->s_blocksize - 1)) {
3562 * Attach jinode to inode for jbd2 if we do any zeroing of
3565 ret = ext4_inode_attach_jinode(inode);
3571 first_block_offset = round_up(offset, sb->s_blocksize);
3572 last_block_offset = round_down((offset + length), sb->s_blocksize) - 1;
3574 /* Now release the pages and zero block aligned part of pages*/
3575 if (last_block_offset > first_block_offset)
3576 truncate_pagecache_range(inode, first_block_offset,
3579 /* Wait all existing dio workers, newcomers will block on i_mutex */
3580 ext4_inode_block_unlocked_dio(inode);
3581 inode_dio_wait(inode);
3583 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3584 credits = ext4_writepage_trans_blocks(inode);
3586 credits = ext4_blocks_for_truncate(inode);
3587 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
3588 if (IS_ERR(handle)) {
3589 ret = PTR_ERR(handle);
3590 ext4_std_error(sb, ret);
3594 ret = ext4_zero_partial_blocks(handle, inode, offset,
3599 first_block = (offset + sb->s_blocksize - 1) >>
3600 EXT4_BLOCK_SIZE_BITS(sb);
3601 stop_block = (offset + length) >> EXT4_BLOCK_SIZE_BITS(sb);
3603 /* If there are no blocks to remove, return now */
3604 if (first_block >= stop_block)
3607 down_write(&EXT4_I(inode)->i_data_sem);
3608 ext4_discard_preallocations(inode);
3610 ret = ext4_es_remove_extent(inode, first_block,
3611 stop_block - first_block);
3613 up_write(&EXT4_I(inode)->i_data_sem);
3617 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3618 ret = ext4_ext_remove_space(inode, first_block,
3621 ret = ext4_free_hole_blocks(handle, inode, first_block,
3624 ext4_discard_preallocations(inode);
3625 up_write(&EXT4_I(inode)->i_data_sem);
3627 ext4_handle_sync(handle);
3628 inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
3629 ext4_mark_inode_dirty(handle, inode);
3631 ext4_journal_stop(handle);
3633 ext4_inode_resume_unlocked_dio(inode);
3635 mutex_unlock(&inode->i_mutex);
3639 int ext4_inode_attach_jinode(struct inode *inode)
3641 struct ext4_inode_info *ei = EXT4_I(inode);
3642 struct jbd2_inode *jinode;
3644 if (ei->jinode || !EXT4_SB(inode->i_sb)->s_journal)
3647 jinode = jbd2_alloc_inode(GFP_KERNEL);
3648 spin_lock(&inode->i_lock);
3651 spin_unlock(&inode->i_lock);
3654 ei->jinode = jinode;
3655 jbd2_journal_init_jbd_inode(ei->jinode, inode);
3658 spin_unlock(&inode->i_lock);
3659 if (unlikely(jinode != NULL))
3660 jbd2_free_inode(jinode);
3667 * We block out ext4_get_block() block instantiations across the entire
3668 * transaction, and VFS/VM ensures that ext4_truncate() cannot run
3669 * simultaneously on behalf of the same inode.
3671 * As we work through the truncate and commit bits of it to the journal there
3672 * is one core, guiding principle: the file's tree must always be consistent on
3673 * disk. We must be able to restart the truncate after a crash.
3675 * The file's tree may be transiently inconsistent in memory (although it
3676 * probably isn't), but whenever we close off and commit a journal transaction,
3677 * the contents of (the filesystem + the journal) must be consistent and
3678 * restartable. It's pretty simple, really: bottom up, right to left (although
3679 * left-to-right works OK too).
3681 * Note that at recovery time, journal replay occurs *before* the restart of
3682 * truncate against the orphan inode list.
3684 * The committed inode has the new, desired i_size (which is the same as
3685 * i_disksize in this case). After a crash, ext4_orphan_cleanup() will see
3686 * that this inode's truncate did not complete and it will again call
3687 * ext4_truncate() to have another go. So there will be instantiated blocks
3688 * to the right of the truncation point in a crashed ext4 filesystem. But
3689 * that's fine - as long as they are linked from the inode, the post-crash
3690 * ext4_truncate() run will find them and release them.
3692 void ext4_truncate(struct inode *inode)
3694 struct ext4_inode_info *ei = EXT4_I(inode);
3695 unsigned int credits;
3697 struct address_space *mapping = inode->i_mapping;
3700 * There is a possibility that we're either freeing the inode
3701 * or it completely new indode. In those cases we might not
3702 * have i_mutex locked because it's not necessary.
3704 if (!(inode->i_state & (I_NEW|I_FREEING)))
3705 WARN_ON(!mutex_is_locked(&inode->i_mutex));
3706 trace_ext4_truncate_enter(inode);
3708 if (!ext4_can_truncate(inode))
3711 ext4_clear_inode_flag(inode, EXT4_INODE_EOFBLOCKS);
3713 if (inode->i_size == 0 && !test_opt(inode->i_sb, NO_AUTO_DA_ALLOC))
3714 ext4_set_inode_state(inode, EXT4_STATE_DA_ALLOC_CLOSE);
3716 if (ext4_has_inline_data(inode)) {
3719 ext4_inline_data_truncate(inode, &has_inline);
3724 /* If we zero-out tail of the page, we have to create jinode for jbd2 */
3725 if (inode->i_size & (inode->i_sb->s_blocksize - 1)) {
3726 if (ext4_inode_attach_jinode(inode) < 0)
3730 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3731 credits = ext4_writepage_trans_blocks(inode);
3733 credits = ext4_blocks_for_truncate(inode);
3735 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
3736 if (IS_ERR(handle)) {
3737 ext4_std_error(inode->i_sb, PTR_ERR(handle));
3741 if (inode->i_size & (inode->i_sb->s_blocksize - 1))
3742 ext4_block_truncate_page(handle, mapping, inode->i_size);
3745 * We add the inode to the orphan list, so that if this
3746 * truncate spans multiple transactions, and we crash, we will
3747 * resume the truncate when the filesystem recovers. It also
3748 * marks the inode dirty, to catch the new size.
3750 * Implication: the file must always be in a sane, consistent
3751 * truncatable state while each transaction commits.
3753 if (ext4_orphan_add(handle, inode))
3756 down_write(&EXT4_I(inode)->i_data_sem);
3758 ext4_discard_preallocations(inode);
3760 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3761 ext4_ext_truncate(handle, inode);
3763 ext4_ind_truncate(handle, inode);
3765 up_write(&ei->i_data_sem);
3768 ext4_handle_sync(handle);
3772 * If this was a simple ftruncate() and the file will remain alive,
3773 * then we need to clear up the orphan record which we created above.
3774 * However, if this was a real unlink then we were called by
3775 * ext4_delete_inode(), and we allow that function to clean up the
3776 * orphan info for us.
3779 ext4_orphan_del(handle, inode);
3781 inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
3782 ext4_mark_inode_dirty(handle, inode);
3783 ext4_journal_stop(handle);
3785 trace_ext4_truncate_exit(inode);
3789 * ext4_get_inode_loc returns with an extra refcount against the inode's
3790 * underlying buffer_head on success. If 'in_mem' is true, we have all
3791 * data in memory that is needed to recreate the on-disk version of this
3794 static int __ext4_get_inode_loc(struct inode *inode,
3795 struct ext4_iloc *iloc, int in_mem)
3797 struct ext4_group_desc *gdp;
3798 struct buffer_head *bh;
3799 struct super_block *sb = inode->i_sb;
3801 int inodes_per_block, inode_offset;
3804 if (!ext4_valid_inum(sb, inode->i_ino))
3807 iloc->block_group = (inode->i_ino - 1) / EXT4_INODES_PER_GROUP(sb);
3808 gdp = ext4_get_group_desc(sb, iloc->block_group, NULL);
3813 * Figure out the offset within the block group inode table
3815 inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
3816 inode_offset = ((inode->i_ino - 1) %
3817 EXT4_INODES_PER_GROUP(sb));
3818 block = ext4_inode_table(sb, gdp) + (inode_offset / inodes_per_block);
3819 iloc->offset = (inode_offset % inodes_per_block) * EXT4_INODE_SIZE(sb);
3821 bh = sb_getblk(sb, block);
3824 if (!buffer_uptodate(bh)) {
3828 * If the buffer has the write error flag, we have failed
3829 * to write out another inode in the same block. In this
3830 * case, we don't have to read the block because we may
3831 * read the old inode data successfully.
3833 if (buffer_write_io_error(bh) && !buffer_uptodate(bh))
3834 set_buffer_uptodate(bh);
3836 if (buffer_uptodate(bh)) {
3837 /* someone brought it uptodate while we waited */
3843 * If we have all information of the inode in memory and this
3844 * is the only valid inode in the block, we need not read the
3848 struct buffer_head *bitmap_bh;
3851 start = inode_offset & ~(inodes_per_block - 1);
3853 /* Is the inode bitmap in cache? */
3854 bitmap_bh = sb_getblk(sb, ext4_inode_bitmap(sb, gdp));
3855 if (unlikely(!bitmap_bh))
3859 * If the inode bitmap isn't in cache then the
3860 * optimisation may end up performing two reads instead
3861 * of one, so skip it.
3863 if (!buffer_uptodate(bitmap_bh)) {
3867 for (i = start; i < start + inodes_per_block; i++) {
3868 if (i == inode_offset)
3870 if (ext4_test_bit(i, bitmap_bh->b_data))
3874 if (i == start + inodes_per_block) {
3875 /* all other inodes are free, so skip I/O */
3876 memset(bh->b_data, 0, bh->b_size);
3877 set_buffer_uptodate(bh);
3885 * If we need to do any I/O, try to pre-readahead extra
3886 * blocks from the inode table.
3888 if (EXT4_SB(sb)->s_inode_readahead_blks) {
3889 ext4_fsblk_t b, end, table;
3891 __u32 ra_blks = EXT4_SB(sb)->s_inode_readahead_blks;
3893 table = ext4_inode_table(sb, gdp);
3894 /* s_inode_readahead_blks is always a power of 2 */
3895 b = block & ~((ext4_fsblk_t) ra_blks - 1);
3899 num = EXT4_INODES_PER_GROUP(sb);
3900 if (ext4_has_group_desc_csum(sb))
3901 num -= ext4_itable_unused_count(sb, gdp);
3902 table += num / inodes_per_block;
3906 sb_breadahead(sb, b++);
3910 * There are other valid inodes in the buffer, this inode
3911 * has in-inode xattrs, or we don't have this inode in memory.
3912 * Read the block from disk.
3914 trace_ext4_load_inode(inode);
3916 bh->b_end_io = end_buffer_read_sync;
3917 submit_bh(READ | REQ_META | REQ_PRIO, bh);
3919 if (!buffer_uptodate(bh)) {
3920 EXT4_ERROR_INODE_BLOCK(inode, block,
3921 "unable to read itable block");
3931 int ext4_get_inode_loc(struct inode *inode, struct ext4_iloc *iloc)
3933 /* We have all inode data except xattrs in memory here. */
3934 return __ext4_get_inode_loc(inode, iloc,
3935 !ext4_test_inode_state(inode, EXT4_STATE_XATTR));
3938 void ext4_set_inode_flags(struct inode *inode)
3940 unsigned int flags = EXT4_I(inode)->i_flags;
3941 unsigned int new_fl = 0;
3943 if (flags & EXT4_SYNC_FL)
3945 if (flags & EXT4_APPEND_FL)
3947 if (flags & EXT4_IMMUTABLE_FL)
3948 new_fl |= S_IMMUTABLE;
3949 if (flags & EXT4_NOATIME_FL)
3950 new_fl |= S_NOATIME;
3951 if (flags & EXT4_DIRSYNC_FL)
3952 new_fl |= S_DIRSYNC;
3953 set_mask_bits(&inode->i_flags,
3954 S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME|S_DIRSYNC, new_fl);
3957 /* Propagate flags from i_flags to EXT4_I(inode)->i_flags */
3958 void ext4_get_inode_flags(struct ext4_inode_info *ei)
3960 unsigned int vfs_fl;
3961 unsigned long old_fl, new_fl;
3964 vfs_fl = ei->vfs_inode.i_flags;
3965 old_fl = ei->i_flags;
3966 new_fl = old_fl & ~(EXT4_SYNC_FL|EXT4_APPEND_FL|
3967 EXT4_IMMUTABLE_FL|EXT4_NOATIME_FL|
3969 if (vfs_fl & S_SYNC)
3970 new_fl |= EXT4_SYNC_FL;
3971 if (vfs_fl & S_APPEND)
3972 new_fl |= EXT4_APPEND_FL;
3973 if (vfs_fl & S_IMMUTABLE)
3974 new_fl |= EXT4_IMMUTABLE_FL;
3975 if (vfs_fl & S_NOATIME)
3976 new_fl |= EXT4_NOATIME_FL;
3977 if (vfs_fl & S_DIRSYNC)
3978 new_fl |= EXT4_DIRSYNC_FL;
3979 } while (cmpxchg(&ei->i_flags, old_fl, new_fl) != old_fl);
3982 static blkcnt_t ext4_inode_blocks(struct ext4_inode *raw_inode,
3983 struct ext4_inode_info *ei)
3986 struct inode *inode = &(ei->vfs_inode);
3987 struct super_block *sb = inode->i_sb;
3989 if (EXT4_HAS_RO_COMPAT_FEATURE(sb,
3990 EXT4_FEATURE_RO_COMPAT_HUGE_FILE)) {
3991 /* we are using combined 48 bit field */
3992 i_blocks = ((u64)le16_to_cpu(raw_inode->i_blocks_high)) << 32 |
3993 le32_to_cpu(raw_inode->i_blocks_lo);
3994 if (ext4_test_inode_flag(inode, EXT4_INODE_HUGE_FILE)) {
3995 /* i_blocks represent file system block size */
3996 return i_blocks << (inode->i_blkbits - 9);
4001 return le32_to_cpu(raw_inode->i_blocks_lo);
4005 static inline void ext4_iget_extra_inode(struct inode *inode,
4006 struct ext4_inode *raw_inode,
4007 struct ext4_inode_info *ei)
4009 __le32 *magic = (void *)raw_inode +
4010 EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize;
4011 if (*magic == cpu_to_le32(EXT4_XATTR_MAGIC)) {
4012 ext4_set_inode_state(inode, EXT4_STATE_XATTR);
4013 ext4_find_inline_data_nolock(inode);
4015 EXT4_I(inode)->i_inline_off = 0;
4018 struct inode *ext4_iget(struct super_block *sb, unsigned long ino)
4020 struct ext4_iloc iloc;
4021 struct ext4_inode *raw_inode;
4022 struct ext4_inode_info *ei;
4023 struct inode *inode;
4024 journal_t *journal = EXT4_SB(sb)->s_journal;
4030 inode = iget_locked(sb, ino);
4032 return ERR_PTR(-ENOMEM);
4033 if (!(inode->i_state & I_NEW))
4039 ret = __ext4_get_inode_loc(inode, &iloc, 0);
4042 raw_inode = ext4_raw_inode(&iloc);
4044 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4045 ei->i_extra_isize = le16_to_cpu(raw_inode->i_extra_isize);
4046 if (EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize >
4047 EXT4_INODE_SIZE(inode->i_sb)) {
4048 EXT4_ERROR_INODE(inode, "bad extra_isize (%u != %u)",
4049 EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize,
4050 EXT4_INODE_SIZE(inode->i_sb));
4055 ei->i_extra_isize = 0;
4057 /* Precompute checksum seed for inode metadata */
4058 if (EXT4_HAS_RO_COMPAT_FEATURE(sb,
4059 EXT4_FEATURE_RO_COMPAT_METADATA_CSUM)) {
4060 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4062 __le32 inum = cpu_to_le32(inode->i_ino);
4063 __le32 gen = raw_inode->i_generation;
4064 csum = ext4_chksum(sbi, sbi->s_csum_seed, (__u8 *)&inum,
4066 ei->i_csum_seed = ext4_chksum(sbi, csum, (__u8 *)&gen,
4070 if (!ext4_inode_csum_verify(inode, raw_inode, ei)) {
4071 EXT4_ERROR_INODE(inode, "checksum invalid");
4076 inode->i_mode = le16_to_cpu(raw_inode->i_mode);
4077 i_uid = (uid_t)le16_to_cpu(raw_inode->i_uid_low);
4078 i_gid = (gid_t)le16_to_cpu(raw_inode->i_gid_low);
4079 if (!(test_opt(inode->i_sb, NO_UID32))) {
4080 i_uid |= le16_to_cpu(raw_inode->i_uid_high) << 16;
4081 i_gid |= le16_to_cpu(raw_inode->i_gid_high) << 16;
4083 i_uid_write(inode, i_uid);
4084 i_gid_write(inode, i_gid);
4085 set_nlink(inode, le16_to_cpu(raw_inode->i_links_count));
4087 ext4_clear_state_flags(ei); /* Only relevant on 32-bit archs */
4088 ei->i_inline_off = 0;
4089 ei->i_dir_start_lookup = 0;
4090 ei->i_dtime = le32_to_cpu(raw_inode->i_dtime);
4091 /* We now have enough fields to check if the inode was active or not.
4092 * This is needed because nfsd might try to access dead inodes
4093 * the test is that same one that e2fsck uses
4094 * NeilBrown 1999oct15
4096 if (inode->i_nlink == 0) {
4097 if ((inode->i_mode == 0 ||
4098 !(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_ORPHAN_FS)) &&
4099 ino != EXT4_BOOT_LOADER_INO) {
4100 /* this inode is deleted */
4104 /* The only unlinked inodes we let through here have
4105 * valid i_mode and are being read by the orphan
4106 * recovery code: that's fine, we're about to complete
4107 * the process of deleting those.
4108 * OR it is the EXT4_BOOT_LOADER_INO which is
4109 * not initialized on a new filesystem. */
4111 ei->i_flags = le32_to_cpu(raw_inode->i_flags);
4112 inode->i_blocks = ext4_inode_blocks(raw_inode, ei);
4113 ei->i_file_acl = le32_to_cpu(raw_inode->i_file_acl_lo);
4114 if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_64BIT))
4116 ((__u64)le16_to_cpu(raw_inode->i_file_acl_high)) << 32;
4117 inode->i_size = ext4_isize(raw_inode);
4118 ei->i_disksize = inode->i_size;
4120 ei->i_reserved_quota = 0;
4122 inode->i_generation = le32_to_cpu(raw_inode->i_generation);
4123 ei->i_block_group = iloc.block_group;
4124 ei->i_last_alloc_group = ~0;
4126 * NOTE! The in-memory inode i_data array is in little-endian order
4127 * even on big-endian machines: we do NOT byteswap the block numbers!
4129 for (block = 0; block < EXT4_N_BLOCKS; block++)
4130 ei->i_data[block] = raw_inode->i_block[block];
4131 INIT_LIST_HEAD(&ei->i_orphan);
4134 * Set transaction id's of transactions that have to be committed
4135 * to finish f[data]sync. We set them to currently running transaction
4136 * as we cannot be sure that the inode or some of its metadata isn't
4137 * part of the transaction - the inode could have been reclaimed and
4138 * now it is reread from disk.
4141 transaction_t *transaction;
4144 read_lock(&journal->j_state_lock);
4145 if (journal->j_running_transaction)
4146 transaction = journal->j_running_transaction;
4148 transaction = journal->j_committing_transaction;
4150 tid = transaction->t_tid;
4152 tid = journal->j_commit_sequence;
4153 read_unlock(&journal->j_state_lock);
4154 ei->i_sync_tid = tid;
4155 ei->i_datasync_tid = tid;
4158 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4159 if (ei->i_extra_isize == 0) {
4160 /* The extra space is currently unused. Use it. */
4161 ei->i_extra_isize = sizeof(struct ext4_inode) -
4162 EXT4_GOOD_OLD_INODE_SIZE;
4164 ext4_iget_extra_inode(inode, raw_inode, ei);
4168 EXT4_INODE_GET_XTIME(i_ctime, inode, raw_inode);
4169 EXT4_INODE_GET_XTIME(i_mtime, inode, raw_inode);
4170 EXT4_INODE_GET_XTIME(i_atime, inode, raw_inode);
4171 EXT4_EINODE_GET_XTIME(i_crtime, ei, raw_inode);
4173 inode->i_version = le32_to_cpu(raw_inode->i_disk_version);
4174 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4175 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
4177 (__u64)(le32_to_cpu(raw_inode->i_version_hi)) << 32;
4181 if (ei->i_file_acl &&
4182 !ext4_data_block_valid(EXT4_SB(sb), ei->i_file_acl, 1)) {
4183 EXT4_ERROR_INODE(inode, "bad extended attribute block %llu",
4187 } else if (!ext4_has_inline_data(inode)) {
4188 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
4189 if ((S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
4190 (S_ISLNK(inode->i_mode) &&
4191 !ext4_inode_is_fast_symlink(inode))))
4192 /* Validate extent which is part of inode */
4193 ret = ext4_ext_check_inode(inode);
4194 } else if (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
4195 (S_ISLNK(inode->i_mode) &&
4196 !ext4_inode_is_fast_symlink(inode))) {
4197 /* Validate block references which are part of inode */
4198 ret = ext4_ind_check_inode(inode);
4204 if (S_ISREG(inode->i_mode)) {
4205 inode->i_op = &ext4_file_inode_operations;
4206 inode->i_fop = &ext4_file_operations;
4207 ext4_set_aops(inode);
4208 } else if (S_ISDIR(inode->i_mode)) {
4209 inode->i_op = &ext4_dir_inode_operations;
4210 inode->i_fop = &ext4_dir_operations;
4211 } else if (S_ISLNK(inode->i_mode)) {
4212 if (ext4_inode_is_fast_symlink(inode)) {
4213 inode->i_op = &ext4_fast_symlink_inode_operations;
4214 nd_terminate_link(ei->i_data, inode->i_size,
4215 sizeof(ei->i_data) - 1);
4217 inode->i_op = &ext4_symlink_inode_operations;
4218 ext4_set_aops(inode);
4220 } else if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode) ||
4221 S_ISFIFO(inode->i_mode) || S_ISSOCK(inode->i_mode)) {
4222 inode->i_op = &ext4_special_inode_operations;
4223 if (raw_inode->i_block[0])
4224 init_special_inode(inode, inode->i_mode,
4225 old_decode_dev(le32_to_cpu(raw_inode->i_block[0])));
4227 init_special_inode(inode, inode->i_mode,
4228 new_decode_dev(le32_to_cpu(raw_inode->i_block[1])));
4229 } else if (ino == EXT4_BOOT_LOADER_INO) {
4230 make_bad_inode(inode);
4233 EXT4_ERROR_INODE(inode, "bogus i_mode (%o)", inode->i_mode);
4237 ext4_set_inode_flags(inode);
4238 unlock_new_inode(inode);
4244 return ERR_PTR(ret);
4247 static int ext4_inode_blocks_set(handle_t *handle,
4248 struct ext4_inode *raw_inode,
4249 struct ext4_inode_info *ei)
4251 struct inode *inode = &(ei->vfs_inode);
4252 u64 i_blocks = inode->i_blocks;
4253 struct super_block *sb = inode->i_sb;
4255 if (i_blocks <= ~0U) {
4257 * i_blocks can be represented in a 32 bit variable
4258 * as multiple of 512 bytes
4260 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
4261 raw_inode->i_blocks_high = 0;
4262 ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
4265 if (!EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_HUGE_FILE))
4268 if (i_blocks <= 0xffffffffffffULL) {
4270 * i_blocks can be represented in a 48 bit variable
4271 * as multiple of 512 bytes
4273 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
4274 raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
4275 ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
4277 ext4_set_inode_flag(inode, EXT4_INODE_HUGE_FILE);
4278 /* i_block is stored in file system block size */
4279 i_blocks = i_blocks >> (inode->i_blkbits - 9);
4280 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
4281 raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
4287 * Post the struct inode info into an on-disk inode location in the
4288 * buffer-cache. This gobbles the caller's reference to the
4289 * buffer_head in the inode location struct.
4291 * The caller must have write access to iloc->bh.
4293 static int ext4_do_update_inode(handle_t *handle,
4294 struct inode *inode,
4295 struct ext4_iloc *iloc)
4297 struct ext4_inode *raw_inode = ext4_raw_inode(iloc);
4298 struct ext4_inode_info *ei = EXT4_I(inode);
4299 struct buffer_head *bh = iloc->bh;
4300 int err = 0, rc, block;
4301 int need_datasync = 0;
4305 /* For fields not not tracking in the in-memory inode,
4306 * initialise them to zero for new inodes. */
4307 if (ext4_test_inode_state(inode, EXT4_STATE_NEW))
4308 memset(raw_inode, 0, EXT4_SB(inode->i_sb)->s_inode_size);
4310 ext4_get_inode_flags(ei);
4311 raw_inode->i_mode = cpu_to_le16(inode->i_mode);
4312 i_uid = i_uid_read(inode);
4313 i_gid = i_gid_read(inode);
4314 if (!(test_opt(inode->i_sb, NO_UID32))) {
4315 raw_inode->i_uid_low = cpu_to_le16(low_16_bits(i_uid));
4316 raw_inode->i_gid_low = cpu_to_le16(low_16_bits(i_gid));
4318 * Fix up interoperability with old kernels. Otherwise, old inodes get
4319 * re-used with the upper 16 bits of the uid/gid intact
4322 raw_inode->i_uid_high =
4323 cpu_to_le16(high_16_bits(i_uid));
4324 raw_inode->i_gid_high =
4325 cpu_to_le16(high_16_bits(i_gid));
4327 raw_inode->i_uid_high = 0;
4328 raw_inode->i_gid_high = 0;
4331 raw_inode->i_uid_low = cpu_to_le16(fs_high2lowuid(i_uid));
4332 raw_inode->i_gid_low = cpu_to_le16(fs_high2lowgid(i_gid));
4333 raw_inode->i_uid_high = 0;
4334 raw_inode->i_gid_high = 0;
4336 raw_inode->i_links_count = cpu_to_le16(inode->i_nlink);
4338 EXT4_INODE_SET_XTIME(i_ctime, inode, raw_inode);
4339 EXT4_INODE_SET_XTIME(i_mtime, inode, raw_inode);
4340 EXT4_INODE_SET_XTIME(i_atime, inode, raw_inode);
4341 EXT4_EINODE_SET_XTIME(i_crtime, ei, raw_inode);
4343 if (ext4_inode_blocks_set(handle, raw_inode, ei))
4345 raw_inode->i_dtime = cpu_to_le32(ei->i_dtime);
4346 raw_inode->i_flags = cpu_to_le32(ei->i_flags & 0xFFFFFFFF);
4347 if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
4348 cpu_to_le32(EXT4_OS_HURD))
4349 raw_inode->i_file_acl_high =
4350 cpu_to_le16(ei->i_file_acl >> 32);
4351 raw_inode->i_file_acl_lo = cpu_to_le32(ei->i_file_acl);
4352 if (ei->i_disksize != ext4_isize(raw_inode)) {
4353 ext4_isize_set(raw_inode, ei->i_disksize);
4356 if (ei->i_disksize > 0x7fffffffULL) {
4357 struct super_block *sb = inode->i_sb;
4358 if (!EXT4_HAS_RO_COMPAT_FEATURE(sb,
4359 EXT4_FEATURE_RO_COMPAT_LARGE_FILE) ||
4360 EXT4_SB(sb)->s_es->s_rev_level ==
4361 cpu_to_le32(EXT4_GOOD_OLD_REV)) {
4362 /* If this is the first large file
4363 * created, add a flag to the superblock.
4365 err = ext4_journal_get_write_access(handle,
4366 EXT4_SB(sb)->s_sbh);
4369 ext4_update_dynamic_rev(sb);
4370 EXT4_SET_RO_COMPAT_FEATURE(sb,
4371 EXT4_FEATURE_RO_COMPAT_LARGE_FILE);
4372 ext4_handle_sync(handle);
4373 err = ext4_handle_dirty_super(handle, sb);
4376 raw_inode->i_generation = cpu_to_le32(inode->i_generation);
4377 if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) {
4378 if (old_valid_dev(inode->i_rdev)) {
4379 raw_inode->i_block[0] =
4380 cpu_to_le32(old_encode_dev(inode->i_rdev));
4381 raw_inode->i_block[1] = 0;
4383 raw_inode->i_block[0] = 0;
4384 raw_inode->i_block[1] =
4385 cpu_to_le32(new_encode_dev(inode->i_rdev));
4386 raw_inode->i_block[2] = 0;
4388 } else if (!ext4_has_inline_data(inode)) {
4389 for (block = 0; block < EXT4_N_BLOCKS; block++)
4390 raw_inode->i_block[block] = ei->i_data[block];
4393 raw_inode->i_disk_version = cpu_to_le32(inode->i_version);
4394 if (ei->i_extra_isize) {
4395 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
4396 raw_inode->i_version_hi =
4397 cpu_to_le32(inode->i_version >> 32);
4398 raw_inode->i_extra_isize = cpu_to_le16(ei->i_extra_isize);
4401 ext4_inode_csum_set(inode, raw_inode, ei);
4403 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
4404 rc = ext4_handle_dirty_metadata(handle, NULL, bh);
4407 ext4_clear_inode_state(inode, EXT4_STATE_NEW);
4409 ext4_update_inode_fsync_trans(handle, inode, need_datasync);
4412 ext4_std_error(inode->i_sb, err);
4417 * ext4_write_inode()
4419 * We are called from a few places:
4421 * - Within generic_file_write() for O_SYNC files.
4422 * Here, there will be no transaction running. We wait for any running
4423 * transaction to commit.
4425 * - Within sys_sync(), kupdate and such.
4426 * We wait on commit, if tol to.
4428 * - Within prune_icache() (PF_MEMALLOC == true)
4429 * Here we simply return. We can't afford to block kswapd on the
4432 * In all cases it is actually safe for us to return without doing anything,
4433 * because the inode has been copied into a raw inode buffer in
4434 * ext4_mark_inode_dirty(). This is a correctness thing for O_SYNC and for
4437 * Note that we are absolutely dependent upon all inode dirtiers doing the
4438 * right thing: they *must* call mark_inode_dirty() after dirtying info in
4439 * which we are interested.
4441 * It would be a bug for them to not do this. The code:
4443 * mark_inode_dirty(inode)
4445 * inode->i_size = expr;
4447 * is in error because a kswapd-driven write_inode() could occur while
4448 * `stuff()' is running, and the new i_size will be lost. Plus the inode
4449 * will no longer be on the superblock's dirty inode list.
4451 int ext4_write_inode(struct inode *inode, struct writeback_control *wbc)
4455 if (current->flags & PF_MEMALLOC)
4458 if (EXT4_SB(inode->i_sb)->s_journal) {
4459 if (ext4_journal_current_handle()) {
4460 jbd_debug(1, "called recursively, non-PF_MEMALLOC!\n");
4465 if (wbc->sync_mode != WB_SYNC_ALL)
4468 err = ext4_force_commit(inode->i_sb);
4470 struct ext4_iloc iloc;
4472 err = __ext4_get_inode_loc(inode, &iloc, 0);
4475 if (wbc->sync_mode == WB_SYNC_ALL)
4476 sync_dirty_buffer(iloc.bh);
4477 if (buffer_req(iloc.bh) && !buffer_uptodate(iloc.bh)) {
4478 EXT4_ERROR_INODE_BLOCK(inode, iloc.bh->b_blocknr,
4479 "IO error syncing inode");
4488 * In data=journal mode ext4_journalled_invalidatepage() may fail to invalidate
4489 * buffers that are attached to a page stradding i_size and are undergoing
4490 * commit. In that case we have to wait for commit to finish and try again.
4492 static void ext4_wait_for_tail_page_commit(struct inode *inode)
4496 journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
4497 tid_t commit_tid = 0;
4500 offset = inode->i_size & (PAGE_CACHE_SIZE - 1);
4502 * All buffers in the last page remain valid? Then there's nothing to
4503 * do. We do the check mainly to optimize the common PAGE_CACHE_SIZE ==
4506 if (offset > PAGE_CACHE_SIZE - (1 << inode->i_blkbits))
4509 page = find_lock_page(inode->i_mapping,
4510 inode->i_size >> PAGE_CACHE_SHIFT);
4513 ret = __ext4_journalled_invalidatepage(page, offset,
4514 PAGE_CACHE_SIZE - offset);
4516 page_cache_release(page);
4520 read_lock(&journal->j_state_lock);
4521 if (journal->j_committing_transaction)
4522 commit_tid = journal->j_committing_transaction->t_tid;
4523 read_unlock(&journal->j_state_lock);
4525 jbd2_log_wait_commit(journal, commit_tid);
4532 * Called from notify_change.
4534 * We want to trap VFS attempts to truncate the file as soon as
4535 * possible. In particular, we want to make sure that when the VFS
4536 * shrinks i_size, we put the inode on the orphan list and modify
4537 * i_disksize immediately, so that during the subsequent flushing of
4538 * dirty pages and freeing of disk blocks, we can guarantee that any
4539 * commit will leave the blocks being flushed in an unused state on
4540 * disk. (On recovery, the inode will get truncated and the blocks will
4541 * be freed, so we have a strong guarantee that no future commit will
4542 * leave these blocks visible to the user.)
4544 * Another thing we have to assure is that if we are in ordered mode
4545 * and inode is still attached to the committing transaction, we must
4546 * we start writeout of all the dirty pages which are being truncated.
4547 * This way we are sure that all the data written in the previous
4548 * transaction are already on disk (truncate waits for pages under
4551 * Called with inode->i_mutex down.
4553 int ext4_setattr(struct dentry *dentry, struct iattr *attr)
4555 struct inode *inode = dentry->d_inode;
4558 const unsigned int ia_valid = attr->ia_valid;
4560 error = inode_change_ok(inode, attr);
4564 if (is_quota_modification(inode, attr))
4565 dquot_initialize(inode);
4566 if ((ia_valid & ATTR_UID && !uid_eq(attr->ia_uid, inode->i_uid)) ||
4567 (ia_valid & ATTR_GID && !gid_eq(attr->ia_gid, inode->i_gid))) {
4570 /* (user+group)*(old+new) structure, inode write (sb,
4571 * inode block, ? - but truncate inode update has it) */
4572 handle = ext4_journal_start(inode, EXT4_HT_QUOTA,
4573 (EXT4_MAXQUOTAS_INIT_BLOCKS(inode->i_sb) +
4574 EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb)) + 3);
4575 if (IS_ERR(handle)) {
4576 error = PTR_ERR(handle);
4579 error = dquot_transfer(inode, attr);
4581 ext4_journal_stop(handle);
4584 /* Update corresponding info in inode so that everything is in
4585 * one transaction */
4586 if (attr->ia_valid & ATTR_UID)
4587 inode->i_uid = attr->ia_uid;
4588 if (attr->ia_valid & ATTR_GID)
4589 inode->i_gid = attr->ia_gid;
4590 error = ext4_mark_inode_dirty(handle, inode);
4591 ext4_journal_stop(handle);
4594 if (attr->ia_valid & ATTR_SIZE && attr->ia_size != inode->i_size) {
4597 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
4598 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4600 if (attr->ia_size > sbi->s_bitmap_maxbytes)
4604 if (IS_I_VERSION(inode) && attr->ia_size != inode->i_size)
4605 inode_inc_iversion(inode);
4607 if (S_ISREG(inode->i_mode) &&
4608 (attr->ia_size < inode->i_size)) {
4609 if (ext4_should_order_data(inode)) {
4610 error = ext4_begin_ordered_truncate(inode,
4615 handle = ext4_journal_start(inode, EXT4_HT_INODE, 3);
4616 if (IS_ERR(handle)) {
4617 error = PTR_ERR(handle);
4620 if (ext4_handle_valid(handle)) {
4621 error = ext4_orphan_add(handle, inode);
4624 down_write(&EXT4_I(inode)->i_data_sem);
4625 EXT4_I(inode)->i_disksize = attr->ia_size;
4626 rc = ext4_mark_inode_dirty(handle, inode);
4630 * We have to update i_size under i_data_sem together
4631 * with i_disksize to avoid races with writeback code
4632 * running ext4_wb_update_i_disksize().
4635 i_size_write(inode, attr->ia_size);
4636 up_write(&EXT4_I(inode)->i_data_sem);
4637 ext4_journal_stop(handle);
4639 ext4_orphan_del(NULL, inode);
4643 i_size_write(inode, attr->ia_size);
4646 * Blocks are going to be removed from the inode. Wait
4647 * for dio in flight. Temporarily disable
4648 * dioread_nolock to prevent livelock.
4651 if (!ext4_should_journal_data(inode)) {
4652 ext4_inode_block_unlocked_dio(inode);
4653 inode_dio_wait(inode);
4654 ext4_inode_resume_unlocked_dio(inode);
4656 ext4_wait_for_tail_page_commit(inode);
4659 * Truncate pagecache after we've waited for commit
4660 * in data=journal mode to make pages freeable.
4662 truncate_pagecache(inode, inode->i_size);
4665 * We want to call ext4_truncate() even if attr->ia_size ==
4666 * inode->i_size for cases like truncation of fallocated space
4668 if (attr->ia_valid & ATTR_SIZE)
4669 ext4_truncate(inode);
4672 setattr_copy(inode, attr);
4673 mark_inode_dirty(inode);
4677 * If the call to ext4_truncate failed to get a transaction handle at
4678 * all, we need to clean up the in-core orphan list manually.
4680 if (orphan && inode->i_nlink)
4681 ext4_orphan_del(NULL, inode);
4683 if (!rc && (ia_valid & ATTR_MODE))
4684 rc = posix_acl_chmod(inode, inode->i_mode);
4687 ext4_std_error(inode->i_sb, error);
4693 int ext4_getattr(struct vfsmount *mnt, struct dentry *dentry,
4696 struct inode *inode;
4697 unsigned long long delalloc_blocks;
4699 inode = dentry->d_inode;
4700 generic_fillattr(inode, stat);
4703 * If there is inline data in the inode, the inode will normally not
4704 * have data blocks allocated (it may have an external xattr block).
4705 * Report at least one sector for such files, so tools like tar, rsync,
4706 * others doen't incorrectly think the file is completely sparse.
4708 if (unlikely(ext4_has_inline_data(inode)))
4709 stat->blocks += (stat->size + 511) >> 9;
4712 * We can't update i_blocks if the block allocation is delayed
4713 * otherwise in the case of system crash before the real block
4714 * allocation is done, we will have i_blocks inconsistent with
4715 * on-disk file blocks.
4716 * We always keep i_blocks updated together with real
4717 * allocation. But to not confuse with user, stat
4718 * will return the blocks that include the delayed allocation
4719 * blocks for this file.
4721 delalloc_blocks = EXT4_C2B(EXT4_SB(inode->i_sb),
4722 EXT4_I(inode)->i_reserved_data_blocks);
4723 stat->blocks += delalloc_blocks << (inode->i_sb->s_blocksize_bits - 9);
4727 static int ext4_index_trans_blocks(struct inode *inode, int lblocks,
4730 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
4731 return ext4_ind_trans_blocks(inode, lblocks);
4732 return ext4_ext_index_trans_blocks(inode, pextents);
4736 * Account for index blocks, block groups bitmaps and block group
4737 * descriptor blocks if modify datablocks and index blocks
4738 * worse case, the indexs blocks spread over different block groups
4740 * If datablocks are discontiguous, they are possible to spread over
4741 * different block groups too. If they are contiguous, with flexbg,
4742 * they could still across block group boundary.
4744 * Also account for superblock, inode, quota and xattr blocks
4746 static int ext4_meta_trans_blocks(struct inode *inode, int lblocks,
4749 ext4_group_t groups, ngroups = ext4_get_groups_count(inode->i_sb);
4755 * How many index blocks need to touch to map @lblocks logical blocks
4756 * to @pextents physical extents?
4758 idxblocks = ext4_index_trans_blocks(inode, lblocks, pextents);
4763 * Now let's see how many group bitmaps and group descriptors need
4766 groups = idxblocks + pextents;
4768 if (groups > ngroups)
4770 if (groups > EXT4_SB(inode->i_sb)->s_gdb_count)
4771 gdpblocks = EXT4_SB(inode->i_sb)->s_gdb_count;
4773 /* bitmaps and block group descriptor blocks */
4774 ret += groups + gdpblocks;
4776 /* Blocks for super block, inode, quota and xattr blocks */
4777 ret += EXT4_META_TRANS_BLOCKS(inode->i_sb);
4783 * Calculate the total number of credits to reserve to fit
4784 * the modification of a single pages into a single transaction,
4785 * which may include multiple chunks of block allocations.
4787 * This could be called via ext4_write_begin()
4789 * We need to consider the worse case, when
4790 * one new block per extent.
4792 int ext4_writepage_trans_blocks(struct inode *inode)
4794 int bpp = ext4_journal_blocks_per_page(inode);
4797 ret = ext4_meta_trans_blocks(inode, bpp, bpp);
4799 /* Account for data blocks for journalled mode */
4800 if (ext4_should_journal_data(inode))
4806 * Calculate the journal credits for a chunk of data modification.
4808 * This is called from DIO, fallocate or whoever calling
4809 * ext4_map_blocks() to map/allocate a chunk of contiguous disk blocks.
4811 * journal buffers for data blocks are not included here, as DIO
4812 * and fallocate do no need to journal data buffers.
4814 int ext4_chunk_trans_blocks(struct inode *inode, int nrblocks)
4816 return ext4_meta_trans_blocks(inode, nrblocks, 1);
4820 * The caller must have previously called ext4_reserve_inode_write().
4821 * Give this, we know that the caller already has write access to iloc->bh.
4823 int ext4_mark_iloc_dirty(handle_t *handle,
4824 struct inode *inode, struct ext4_iloc *iloc)
4828 if (IS_I_VERSION(inode))
4829 inode_inc_iversion(inode);
4831 /* the do_update_inode consumes one bh->b_count */
4834 /* ext4_do_update_inode() does jbd2_journal_dirty_metadata */
4835 err = ext4_do_update_inode(handle, inode, iloc);
4841 * On success, We end up with an outstanding reference count against
4842 * iloc->bh. This _must_ be cleaned up later.
4846 ext4_reserve_inode_write(handle_t *handle, struct inode *inode,
4847 struct ext4_iloc *iloc)
4851 err = ext4_get_inode_loc(inode, iloc);
4853 BUFFER_TRACE(iloc->bh, "get_write_access");
4854 err = ext4_journal_get_write_access(handle, iloc->bh);
4860 ext4_std_error(inode->i_sb, err);
4865 * Expand an inode by new_extra_isize bytes.
4866 * Returns 0 on success or negative error number on failure.
4868 static int ext4_expand_extra_isize(struct inode *inode,
4869 unsigned int new_extra_isize,
4870 struct ext4_iloc iloc,
4873 struct ext4_inode *raw_inode;
4874 struct ext4_xattr_ibody_header *header;
4876 if (EXT4_I(inode)->i_extra_isize >= new_extra_isize)
4879 raw_inode = ext4_raw_inode(&iloc);
4881 header = IHDR(inode, raw_inode);
4883 /* No extended attributes present */
4884 if (!ext4_test_inode_state(inode, EXT4_STATE_XATTR) ||
4885 header->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC)) {
4886 memset((void *)raw_inode + EXT4_GOOD_OLD_INODE_SIZE, 0,
4888 EXT4_I(inode)->i_extra_isize = new_extra_isize;
4892 /* try to expand with EAs present */
4893 return ext4_expand_extra_isize_ea(inode, new_extra_isize,
4898 * What we do here is to mark the in-core inode as clean with respect to inode
4899 * dirtiness (it may still be data-dirty).
4900 * This means that the in-core inode may be reaped by prune_icache
4901 * without having to perform any I/O. This is a very good thing,
4902 * because *any* task may call prune_icache - even ones which
4903 * have a transaction open against a different journal.
4905 * Is this cheating? Not really. Sure, we haven't written the
4906 * inode out, but prune_icache isn't a user-visible syncing function.
4907 * Whenever the user wants stuff synced (sys_sync, sys_msync, sys_fsync)
4908 * we start and wait on commits.
4910 int ext4_mark_inode_dirty(handle_t *handle, struct inode *inode)
4912 struct ext4_iloc iloc;
4913 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4914 static unsigned int mnt_count;
4918 trace_ext4_mark_inode_dirty(inode, _RET_IP_);
4919 err = ext4_reserve_inode_write(handle, inode, &iloc);
4920 if (ext4_handle_valid(handle) &&
4921 EXT4_I(inode)->i_extra_isize < sbi->s_want_extra_isize &&
4922 !ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND)) {
4924 * We need extra buffer credits since we may write into EA block
4925 * with this same handle. If journal_extend fails, then it will
4926 * only result in a minor loss of functionality for that inode.
4927 * If this is felt to be critical, then e2fsck should be run to
4928 * force a large enough s_min_extra_isize.
4930 if ((jbd2_journal_extend(handle,
4931 EXT4_DATA_TRANS_BLOCKS(inode->i_sb))) == 0) {
4932 ret = ext4_expand_extra_isize(inode,
4933 sbi->s_want_extra_isize,
4936 ext4_set_inode_state(inode,
4937 EXT4_STATE_NO_EXPAND);
4939 le16_to_cpu(sbi->s_es->s_mnt_count)) {
4940 ext4_warning(inode->i_sb,
4941 "Unable to expand inode %lu. Delete"
4942 " some EAs or run e2fsck.",
4945 le16_to_cpu(sbi->s_es->s_mnt_count);
4951 err = ext4_mark_iloc_dirty(handle, inode, &iloc);
4956 * ext4_dirty_inode() is called from __mark_inode_dirty()
4958 * We're really interested in the case where a file is being extended.
4959 * i_size has been changed by generic_commit_write() and we thus need
4960 * to include the updated inode in the current transaction.
4962 * Also, dquot_alloc_block() will always dirty the inode when blocks
4963 * are allocated to the file.
4965 * If the inode is marked synchronous, we don't honour that here - doing
4966 * so would cause a commit on atime updates, which we don't bother doing.
4967 * We handle synchronous inodes at the highest possible level.
4969 void ext4_dirty_inode(struct inode *inode, int flags)
4973 handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
4977 ext4_mark_inode_dirty(handle, inode);
4979 ext4_journal_stop(handle);
4986 * Bind an inode's backing buffer_head into this transaction, to prevent
4987 * it from being flushed to disk early. Unlike
4988 * ext4_reserve_inode_write, this leaves behind no bh reference and
4989 * returns no iloc structure, so the caller needs to repeat the iloc
4990 * lookup to mark the inode dirty later.
4992 static int ext4_pin_inode(handle_t *handle, struct inode *inode)
4994 struct ext4_iloc iloc;
4998 err = ext4_get_inode_loc(inode, &iloc);
5000 BUFFER_TRACE(iloc.bh, "get_write_access");
5001 err = jbd2_journal_get_write_access(handle, iloc.bh);
5003 err = ext4_handle_dirty_metadata(handle,
5009 ext4_std_error(inode->i_sb, err);
5014 int ext4_change_inode_journal_flag(struct inode *inode, int val)
5021 * We have to be very careful here: changing a data block's
5022 * journaling status dynamically is dangerous. If we write a
5023 * data block to the journal, change the status and then delete
5024 * that block, we risk forgetting to revoke the old log record
5025 * from the journal and so a subsequent replay can corrupt data.
5026 * So, first we make sure that the journal is empty and that
5027 * nobody is changing anything.
5030 journal = EXT4_JOURNAL(inode);
5033 if (is_journal_aborted(journal))
5035 /* We have to allocate physical blocks for delalloc blocks
5036 * before flushing journal. otherwise delalloc blocks can not
5037 * be allocated any more. even more truncate on delalloc blocks
5038 * could trigger BUG by flushing delalloc blocks in journal.
5039 * There is no delalloc block in non-journal data mode.
5041 if (val && test_opt(inode->i_sb, DELALLOC)) {
5042 err = ext4_alloc_da_blocks(inode);
5047 /* Wait for all existing dio workers */
5048 ext4_inode_block_unlocked_dio(inode);
5049 inode_dio_wait(inode);
5051 jbd2_journal_lock_updates(journal);
5054 * OK, there are no updates running now, and all cached data is
5055 * synced to disk. We are now in a completely consistent state
5056 * which doesn't have anything in the journal, and we know that
5057 * no filesystem updates are running, so it is safe to modify
5058 * the inode's in-core data-journaling state flag now.
5062 ext4_set_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
5064 jbd2_journal_flush(journal);
5065 ext4_clear_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
5067 ext4_set_aops(inode);
5069 jbd2_journal_unlock_updates(journal);
5070 ext4_inode_resume_unlocked_dio(inode);
5072 /* Finally we can mark the inode as dirty. */
5074 handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
5076 return PTR_ERR(handle);
5078 err = ext4_mark_inode_dirty(handle, inode);
5079 ext4_handle_sync(handle);
5080 ext4_journal_stop(handle);
5081 ext4_std_error(inode->i_sb, err);
5086 static int ext4_bh_unmapped(handle_t *handle, struct buffer_head *bh)
5088 return !buffer_mapped(bh);
5091 int ext4_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
5093 struct page *page = vmf->page;
5097 struct file *file = vma->vm_file;
5098 struct inode *inode = file_inode(file);
5099 struct address_space *mapping = inode->i_mapping;
5101 get_block_t *get_block;
5104 sb_start_pagefault(inode->i_sb);
5105 file_update_time(vma->vm_file);
5106 /* Delalloc case is easy... */
5107 if (test_opt(inode->i_sb, DELALLOC) &&
5108 !ext4_should_journal_data(inode) &&
5109 !ext4_nonda_switch(inode->i_sb)) {
5111 ret = __block_page_mkwrite(vma, vmf,
5112 ext4_da_get_block_prep);
5113 } while (ret == -ENOSPC &&
5114 ext4_should_retry_alloc(inode->i_sb, &retries));
5119 size = i_size_read(inode);
5120 /* Page got truncated from under us? */
5121 if (page->mapping != mapping || page_offset(page) > size) {
5123 ret = VM_FAULT_NOPAGE;
5127 if (page->index == size >> PAGE_CACHE_SHIFT)
5128 len = size & ~PAGE_CACHE_MASK;
5130 len = PAGE_CACHE_SIZE;
5132 * Return if we have all the buffers mapped. This avoids the need to do
5133 * journal_start/journal_stop which can block and take a long time
5135 if (page_has_buffers(page)) {
5136 if (!ext4_walk_page_buffers(NULL, page_buffers(page),
5138 ext4_bh_unmapped)) {
5139 /* Wait so that we don't change page under IO */
5140 wait_for_stable_page(page);
5141 ret = VM_FAULT_LOCKED;
5146 /* OK, we need to fill the hole... */
5147 if (ext4_should_dioread_nolock(inode))
5148 get_block = ext4_get_block_write;
5150 get_block = ext4_get_block;
5152 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
5153 ext4_writepage_trans_blocks(inode));
5154 if (IS_ERR(handle)) {
5155 ret = VM_FAULT_SIGBUS;
5158 ret = __block_page_mkwrite(vma, vmf, get_block);
5159 if (!ret && ext4_should_journal_data(inode)) {
5160 if (ext4_walk_page_buffers(handle, page_buffers(page), 0,
5161 PAGE_CACHE_SIZE, NULL, do_journal_get_write_access)) {
5163 ret = VM_FAULT_SIGBUS;
5164 ext4_journal_stop(handle);
5167 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
5169 ext4_journal_stop(handle);
5170 if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
5173 ret = block_page_mkwrite_return(ret);
5175 sb_end_pagefault(inode->i_sb);