2 * linux/fs/ext4/inode.c
4 * Copyright (C) 1992, 1993, 1994, 1995
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
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 /* Lookup extent status tree firstly */
519 if (ext4_es_lookup_extent(inode, map->m_lblk, &es)) {
520 ext4_es_lru_add(inode);
521 if (ext4_es_is_written(&es) || ext4_es_is_unwritten(&es)) {
522 map->m_pblk = ext4_es_pblock(&es) +
523 map->m_lblk - es.es_lblk;
524 map->m_flags |= ext4_es_is_written(&es) ?
525 EXT4_MAP_MAPPED : EXT4_MAP_UNWRITTEN;
526 retval = es.es_len - (map->m_lblk - es.es_lblk);
527 if (retval > map->m_len)
530 } else if (ext4_es_is_delayed(&es) || ext4_es_is_hole(&es)) {
535 #ifdef ES_AGGRESSIVE_TEST
536 ext4_map_blocks_es_recheck(handle, inode, map,
543 * Try to see if we can get the block without requesting a new
546 if (!(flags & EXT4_GET_BLOCKS_NO_LOCK))
547 down_read((&EXT4_I(inode)->i_data_sem));
548 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
549 retval = ext4_ext_map_blocks(handle, inode, map, flags &
550 EXT4_GET_BLOCKS_KEEP_SIZE);
552 retval = ext4_ind_map_blocks(handle, inode, map, flags &
553 EXT4_GET_BLOCKS_KEEP_SIZE);
559 if (unlikely(retval != map->m_len)) {
560 ext4_warning(inode->i_sb,
561 "ES len assertion failed for inode "
562 "%lu: retval %d != map->m_len %d",
563 inode->i_ino, retval, map->m_len);
567 status = map->m_flags & EXT4_MAP_UNWRITTEN ?
568 EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
569 if (!(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) &&
570 ext4_find_delalloc_range(inode, map->m_lblk,
571 map->m_lblk + map->m_len - 1))
572 status |= EXTENT_STATUS_DELAYED;
573 ret = ext4_es_insert_extent(inode, map->m_lblk,
574 map->m_len, map->m_pblk, status);
578 if (!(flags & EXT4_GET_BLOCKS_NO_LOCK))
579 up_read((&EXT4_I(inode)->i_data_sem));
582 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
583 int ret = check_block_validity(inode, map);
588 /* If it is only a block(s) look up */
589 if ((flags & EXT4_GET_BLOCKS_CREATE) == 0)
593 * Returns if the blocks have already allocated
595 * Note that if blocks have been preallocated
596 * ext4_ext_get_block() returns the create = 0
597 * with buffer head unmapped.
599 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED)
603 * Here we clear m_flags because after allocating an new extent,
604 * it will be set again.
606 map->m_flags &= ~EXT4_MAP_FLAGS;
609 * New blocks allocate and/or writing to uninitialized extent
610 * will possibly result in updating i_data, so we take
611 * the write lock of i_data_sem, and call get_blocks()
612 * with create == 1 flag.
614 down_write((&EXT4_I(inode)->i_data_sem));
617 * if the caller is from delayed allocation writeout path
618 * we have already reserved fs blocks for allocation
619 * let the underlying get_block() function know to
620 * avoid double accounting
622 if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
623 ext4_set_inode_state(inode, EXT4_STATE_DELALLOC_RESERVED);
625 * We need to check for EXT4 here because migrate
626 * could have changed the inode type in between
628 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
629 retval = ext4_ext_map_blocks(handle, inode, map, flags);
631 retval = ext4_ind_map_blocks(handle, inode, map, flags);
633 if (retval > 0 && map->m_flags & EXT4_MAP_NEW) {
635 * We allocated new blocks which will result in
636 * i_data's format changing. Force the migrate
637 * to fail by clearing migrate flags
639 ext4_clear_inode_state(inode, EXT4_STATE_EXT_MIGRATE);
643 * Update reserved blocks/metadata blocks after successful
644 * block allocation which had been deferred till now. We don't
645 * support fallocate for non extent files. So we can update
646 * reserve space here.
649 (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE))
650 ext4_da_update_reserve_space(inode, retval, 1);
652 if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
653 ext4_clear_inode_state(inode, EXT4_STATE_DELALLOC_RESERVED);
659 if (unlikely(retval != map->m_len)) {
660 ext4_warning(inode->i_sb,
661 "ES len assertion failed for inode "
662 "%lu: retval %d != map->m_len %d",
663 inode->i_ino, retval, map->m_len);
668 * If the extent has been zeroed out, we don't need to update
669 * extent status tree.
671 if ((flags & EXT4_GET_BLOCKS_PRE_IO) &&
672 ext4_es_lookup_extent(inode, map->m_lblk, &es)) {
673 if (ext4_es_is_written(&es))
676 status = map->m_flags & EXT4_MAP_UNWRITTEN ?
677 EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
678 if (!(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) &&
679 ext4_find_delalloc_range(inode, map->m_lblk,
680 map->m_lblk + map->m_len - 1))
681 status |= EXTENT_STATUS_DELAYED;
682 ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
683 map->m_pblk, status);
689 up_write((&EXT4_I(inode)->i_data_sem));
690 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
691 int ret = check_block_validity(inode, map);
698 /* Maximum number of blocks we map for direct IO at once. */
699 #define DIO_MAX_BLOCKS 4096
701 static int _ext4_get_block(struct inode *inode, sector_t iblock,
702 struct buffer_head *bh, int flags)
704 handle_t *handle = ext4_journal_current_handle();
705 struct ext4_map_blocks map;
706 int ret = 0, started = 0;
709 if (ext4_has_inline_data(inode))
713 map.m_len = bh->b_size >> inode->i_blkbits;
715 if (flags && !(flags & EXT4_GET_BLOCKS_NO_LOCK) && !handle) {
716 /* Direct IO write... */
717 if (map.m_len > DIO_MAX_BLOCKS)
718 map.m_len = DIO_MAX_BLOCKS;
719 dio_credits = ext4_chunk_trans_blocks(inode, map.m_len);
720 handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS,
722 if (IS_ERR(handle)) {
723 ret = PTR_ERR(handle);
729 ret = ext4_map_blocks(handle, inode, &map, flags);
731 ext4_io_end_t *io_end = ext4_inode_aio(inode);
733 map_bh(bh, inode->i_sb, map.m_pblk);
734 bh->b_state = (bh->b_state & ~EXT4_MAP_FLAGS) | map.m_flags;
735 if (io_end && io_end->flag & EXT4_IO_END_UNWRITTEN)
736 set_buffer_defer_completion(bh);
737 bh->b_size = inode->i_sb->s_blocksize * map.m_len;
741 ext4_journal_stop(handle);
745 int ext4_get_block(struct inode *inode, sector_t iblock,
746 struct buffer_head *bh, int create)
748 return _ext4_get_block(inode, iblock, bh,
749 create ? EXT4_GET_BLOCKS_CREATE : 0);
753 * `handle' can be NULL if create is zero
755 struct buffer_head *ext4_getblk(handle_t *handle, struct inode *inode,
756 ext4_lblk_t block, int create, int *errp)
758 struct ext4_map_blocks map;
759 struct buffer_head *bh;
762 J_ASSERT(handle != NULL || create == 0);
766 err = ext4_map_blocks(handle, inode, &map,
767 create ? EXT4_GET_BLOCKS_CREATE : 0);
769 /* ensure we send some value back into *errp */
772 if (create && err == 0)
773 err = -ENOSPC; /* should never happen */
779 bh = sb_getblk(inode->i_sb, map.m_pblk);
784 if (map.m_flags & EXT4_MAP_NEW) {
785 J_ASSERT(create != 0);
786 J_ASSERT(handle != NULL);
789 * Now that we do not always journal data, we should
790 * keep in mind whether this should always journal the
791 * new buffer as metadata. For now, regular file
792 * writes use ext4_get_block instead, so it's not a
796 BUFFER_TRACE(bh, "call get_create_access");
797 fatal = ext4_journal_get_create_access(handle, bh);
798 if (!fatal && !buffer_uptodate(bh)) {
799 memset(bh->b_data, 0, inode->i_sb->s_blocksize);
800 set_buffer_uptodate(bh);
803 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
804 err = ext4_handle_dirty_metadata(handle, inode, bh);
808 BUFFER_TRACE(bh, "not a new buffer");
818 struct buffer_head *ext4_bread(handle_t *handle, struct inode *inode,
819 ext4_lblk_t block, int create, int *err)
821 struct buffer_head *bh;
823 bh = ext4_getblk(handle, inode, block, create, err);
826 if (buffer_uptodate(bh))
828 ll_rw_block(READ | REQ_META | REQ_PRIO, 1, &bh);
830 if (buffer_uptodate(bh))
837 int ext4_walk_page_buffers(handle_t *handle,
838 struct buffer_head *head,
842 int (*fn)(handle_t *handle,
843 struct buffer_head *bh))
845 struct buffer_head *bh;
846 unsigned block_start, block_end;
847 unsigned blocksize = head->b_size;
849 struct buffer_head *next;
851 for (bh = head, block_start = 0;
852 ret == 0 && (bh != head || !block_start);
853 block_start = block_end, bh = next) {
854 next = bh->b_this_page;
855 block_end = block_start + blocksize;
856 if (block_end <= from || block_start >= to) {
857 if (partial && !buffer_uptodate(bh))
861 err = (*fn)(handle, bh);
869 * To preserve ordering, it is essential that the hole instantiation and
870 * the data write be encapsulated in a single transaction. We cannot
871 * close off a transaction and start a new one between the ext4_get_block()
872 * and the commit_write(). So doing the jbd2_journal_start at the start of
873 * prepare_write() is the right place.
875 * Also, this function can nest inside ext4_writepage(). In that case, we
876 * *know* that ext4_writepage() has generated enough buffer credits to do the
877 * whole page. So we won't block on the journal in that case, which is good,
878 * because the caller may be PF_MEMALLOC.
880 * By accident, ext4 can be reentered when a transaction is open via
881 * quota file writes. If we were to commit the transaction while thus
882 * reentered, there can be a deadlock - we would be holding a quota
883 * lock, and the commit would never complete if another thread had a
884 * transaction open and was blocking on the quota lock - a ranking
887 * So what we do is to rely on the fact that jbd2_journal_stop/journal_start
888 * will _not_ run commit under these circumstances because handle->h_ref
889 * is elevated. We'll still have enough credits for the tiny quotafile
892 int do_journal_get_write_access(handle_t *handle,
893 struct buffer_head *bh)
895 int dirty = buffer_dirty(bh);
898 if (!buffer_mapped(bh) || buffer_freed(bh))
901 * __block_write_begin() could have dirtied some buffers. Clean
902 * the dirty bit as jbd2_journal_get_write_access() could complain
903 * otherwise about fs integrity issues. Setting of the dirty bit
904 * by __block_write_begin() isn't a real problem here as we clear
905 * the bit before releasing a page lock and thus writeback cannot
906 * ever write the buffer.
909 clear_buffer_dirty(bh);
910 ret = ext4_journal_get_write_access(handle, bh);
912 ret = ext4_handle_dirty_metadata(handle, NULL, bh);
916 static int ext4_get_block_write_nolock(struct inode *inode, sector_t iblock,
917 struct buffer_head *bh_result, int create);
918 static int ext4_write_begin(struct file *file, struct address_space *mapping,
919 loff_t pos, unsigned len, unsigned flags,
920 struct page **pagep, void **fsdata)
922 struct inode *inode = mapping->host;
923 int ret, needed_blocks;
930 trace_ext4_write_begin(inode, pos, len, flags);
932 * Reserve one block more for addition to orphan list in case
933 * we allocate blocks but write fails for some reason
935 needed_blocks = ext4_writepage_trans_blocks(inode) + 1;
936 index = pos >> PAGE_CACHE_SHIFT;
937 from = pos & (PAGE_CACHE_SIZE - 1);
940 if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
941 ret = ext4_try_to_write_inline_data(mapping, inode, pos, len,
950 * grab_cache_page_write_begin() can take a long time if the
951 * system is thrashing due to memory pressure, or if the page
952 * is being written back. So grab it first before we start
953 * the transaction handle. This also allows us to allocate
954 * the page (if needed) without using GFP_NOFS.
957 page = grab_cache_page_write_begin(mapping, index, flags);
963 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE, needed_blocks);
964 if (IS_ERR(handle)) {
965 page_cache_release(page);
966 return PTR_ERR(handle);
970 if (page->mapping != mapping) {
971 /* The page got truncated from under us */
973 page_cache_release(page);
974 ext4_journal_stop(handle);
977 /* In case writeback began while the page was unlocked */
978 wait_for_stable_page(page);
980 if (ext4_should_dioread_nolock(inode))
981 ret = __block_write_begin(page, pos, len, ext4_get_block_write);
983 ret = __block_write_begin(page, pos, len, ext4_get_block);
985 if (!ret && ext4_should_journal_data(inode)) {
986 ret = ext4_walk_page_buffers(handle, page_buffers(page),
988 do_journal_get_write_access);
994 * __block_write_begin may have instantiated a few blocks
995 * outside i_size. Trim these off again. Don't need
996 * i_size_read because we hold i_mutex.
998 * Add inode to orphan list in case we crash before
1001 if (pos + len > inode->i_size && ext4_can_truncate(inode))
1002 ext4_orphan_add(handle, inode);
1004 ext4_journal_stop(handle);
1005 if (pos + len > inode->i_size) {
1006 ext4_truncate_failed_write(inode);
1008 * If truncate failed early the inode might
1009 * still be on the orphan list; we need to
1010 * make sure the inode is removed from the
1011 * orphan list in that case.
1014 ext4_orphan_del(NULL, inode);
1017 if (ret == -ENOSPC &&
1018 ext4_should_retry_alloc(inode->i_sb, &retries))
1020 page_cache_release(page);
1027 /* For write_end() in data=journal mode */
1028 static int write_end_fn(handle_t *handle, struct buffer_head *bh)
1031 if (!buffer_mapped(bh) || buffer_freed(bh))
1033 set_buffer_uptodate(bh);
1034 ret = ext4_handle_dirty_metadata(handle, NULL, bh);
1035 clear_buffer_meta(bh);
1036 clear_buffer_prio(bh);
1041 * We need to pick up the new inode size which generic_commit_write gave us
1042 * `file' can be NULL - eg, when called from page_symlink().
1044 * ext4 never places buffers on inode->i_mapping->private_list. metadata
1045 * buffers are managed internally.
1047 static int ext4_write_end(struct file *file,
1048 struct address_space *mapping,
1049 loff_t pos, unsigned len, unsigned copied,
1050 struct page *page, void *fsdata)
1052 handle_t *handle = ext4_journal_current_handle();
1053 struct inode *inode = mapping->host;
1055 int i_size_changed = 0;
1057 trace_ext4_write_end(inode, pos, len, copied);
1058 if (ext4_test_inode_state(inode, EXT4_STATE_ORDERED_MODE)) {
1059 ret = ext4_jbd2_file_inode(handle, inode);
1062 page_cache_release(page);
1067 if (ext4_has_inline_data(inode)) {
1068 ret = ext4_write_inline_data_end(inode, pos, len,
1074 copied = block_write_end(file, mapping, pos,
1075 len, copied, page, fsdata);
1078 * No need to use i_size_read() here, the i_size
1079 * cannot change under us because we hole i_mutex.
1081 * But it's important to update i_size while still holding page lock:
1082 * page writeout could otherwise come in and zero beyond i_size.
1084 if (pos + copied > inode->i_size) {
1085 i_size_write(inode, pos + copied);
1089 if (pos + copied > EXT4_I(inode)->i_disksize) {
1090 /* We need to mark inode dirty even if
1091 * new_i_size is less that inode->i_size
1092 * but greater than i_disksize. (hint delalloc)
1094 ext4_update_i_disksize(inode, (pos + copied));
1098 page_cache_release(page);
1101 * Don't mark the inode dirty under page lock. First, it unnecessarily
1102 * makes the holding time of page lock longer. Second, it forces lock
1103 * ordering of page lock and transaction start for journaling
1107 ext4_mark_inode_dirty(handle, inode);
1109 if (pos + len > inode->i_size && ext4_can_truncate(inode))
1110 /* if we have allocated more blocks and copied
1111 * less. We will have blocks allocated outside
1112 * inode->i_size. So truncate them
1114 ext4_orphan_add(handle, inode);
1116 ret2 = ext4_journal_stop(handle);
1120 if (pos + len > inode->i_size) {
1121 ext4_truncate_failed_write(inode);
1123 * If truncate failed early the inode might still be
1124 * on the orphan list; we need to make sure the inode
1125 * is removed from the orphan list in that case.
1128 ext4_orphan_del(NULL, inode);
1131 return ret ? ret : copied;
1134 static int ext4_journalled_write_end(struct file *file,
1135 struct address_space *mapping,
1136 loff_t pos, unsigned len, unsigned copied,
1137 struct page *page, void *fsdata)
1139 handle_t *handle = ext4_journal_current_handle();
1140 struct inode *inode = mapping->host;
1146 trace_ext4_journalled_write_end(inode, pos, len, copied);
1147 from = pos & (PAGE_CACHE_SIZE - 1);
1150 BUG_ON(!ext4_handle_valid(handle));
1152 if (ext4_has_inline_data(inode))
1153 copied = ext4_write_inline_data_end(inode, pos, len,
1157 if (!PageUptodate(page))
1159 page_zero_new_buffers(page, from+copied, to);
1162 ret = ext4_walk_page_buffers(handle, page_buffers(page), from,
1163 to, &partial, write_end_fn);
1165 SetPageUptodate(page);
1167 new_i_size = pos + copied;
1168 if (new_i_size > inode->i_size)
1169 i_size_write(inode, pos+copied);
1170 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
1171 EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
1172 if (new_i_size > EXT4_I(inode)->i_disksize) {
1173 ext4_update_i_disksize(inode, new_i_size);
1174 ret2 = ext4_mark_inode_dirty(handle, inode);
1180 page_cache_release(page);
1181 if (pos + len > inode->i_size && ext4_can_truncate(inode))
1182 /* if we have allocated more blocks and copied
1183 * less. We will have blocks allocated outside
1184 * inode->i_size. So truncate them
1186 ext4_orphan_add(handle, inode);
1188 ret2 = ext4_journal_stop(handle);
1191 if (pos + len > inode->i_size) {
1192 ext4_truncate_failed_write(inode);
1194 * If truncate failed early the inode might still be
1195 * on the orphan list; we need to make sure the inode
1196 * is removed from the orphan list in that case.
1199 ext4_orphan_del(NULL, inode);
1202 return ret ? ret : copied;
1206 * Reserve a metadata for a single block located at lblock
1208 static int ext4_da_reserve_metadata(struct inode *inode, ext4_lblk_t lblock)
1210 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1211 struct ext4_inode_info *ei = EXT4_I(inode);
1212 unsigned int md_needed;
1213 ext4_lblk_t save_last_lblock;
1217 * recalculate the amount of metadata blocks to reserve
1218 * in order to allocate nrblocks
1219 * worse case is one extent per block
1221 spin_lock(&ei->i_block_reservation_lock);
1223 * ext4_calc_metadata_amount() has side effects, which we have
1224 * to be prepared undo if we fail to claim space.
1226 save_len = ei->i_da_metadata_calc_len;
1227 save_last_lblock = ei->i_da_metadata_calc_last_lblock;
1228 md_needed = EXT4_NUM_B2C(sbi,
1229 ext4_calc_metadata_amount(inode, lblock));
1230 trace_ext4_da_reserve_space(inode, md_needed);
1233 * We do still charge estimated metadata to the sb though;
1234 * we cannot afford to run out of free blocks.
1236 if (ext4_claim_free_clusters(sbi, md_needed, 0)) {
1237 ei->i_da_metadata_calc_len = save_len;
1238 ei->i_da_metadata_calc_last_lblock = save_last_lblock;
1239 spin_unlock(&ei->i_block_reservation_lock);
1242 ei->i_reserved_meta_blocks += md_needed;
1243 spin_unlock(&ei->i_block_reservation_lock);
1245 return 0; /* success */
1249 * Reserve a single cluster located at lblock
1251 static int ext4_da_reserve_space(struct inode *inode, ext4_lblk_t lblock)
1253 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1254 struct ext4_inode_info *ei = EXT4_I(inode);
1255 unsigned int md_needed;
1257 ext4_lblk_t save_last_lblock;
1261 * We will charge metadata quota at writeout time; this saves
1262 * us from metadata over-estimation, though we may go over by
1263 * a small amount in the end. Here we just reserve for data.
1265 ret = dquot_reserve_block(inode, EXT4_C2B(sbi, 1));
1270 * recalculate the amount of metadata blocks to reserve
1271 * in order to allocate nrblocks
1272 * worse case is one extent per block
1274 spin_lock(&ei->i_block_reservation_lock);
1276 * ext4_calc_metadata_amount() has side effects, which we have
1277 * to be prepared undo if we fail to claim space.
1279 save_len = ei->i_da_metadata_calc_len;
1280 save_last_lblock = ei->i_da_metadata_calc_last_lblock;
1281 md_needed = EXT4_NUM_B2C(sbi,
1282 ext4_calc_metadata_amount(inode, lblock));
1283 trace_ext4_da_reserve_space(inode, md_needed);
1286 * We do still charge estimated metadata to the sb though;
1287 * we cannot afford to run out of free blocks.
1289 if (ext4_claim_free_clusters(sbi, md_needed + 1, 0)) {
1290 ei->i_da_metadata_calc_len = save_len;
1291 ei->i_da_metadata_calc_last_lblock = save_last_lblock;
1292 spin_unlock(&ei->i_block_reservation_lock);
1293 dquot_release_reservation_block(inode, EXT4_C2B(sbi, 1));
1296 ei->i_reserved_data_blocks++;
1297 ei->i_reserved_meta_blocks += md_needed;
1298 spin_unlock(&ei->i_block_reservation_lock);
1300 return 0; /* success */
1303 static void ext4_da_release_space(struct inode *inode, int to_free)
1305 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1306 struct ext4_inode_info *ei = EXT4_I(inode);
1309 return; /* Nothing to release, exit */
1311 spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
1313 trace_ext4_da_release_space(inode, to_free);
1314 if (unlikely(to_free > ei->i_reserved_data_blocks)) {
1316 * if there aren't enough reserved blocks, then the
1317 * counter is messed up somewhere. Since this
1318 * function is called from invalidate page, it's
1319 * harmless to return without any action.
1321 ext4_warning(inode->i_sb, "ext4_da_release_space: "
1322 "ino %lu, to_free %d with only %d reserved "
1323 "data blocks", inode->i_ino, to_free,
1324 ei->i_reserved_data_blocks);
1326 to_free = ei->i_reserved_data_blocks;
1328 ei->i_reserved_data_blocks -= to_free;
1330 if (ei->i_reserved_data_blocks == 0) {
1332 * We can release all of the reserved metadata blocks
1333 * only when we have written all of the delayed
1334 * allocation blocks.
1335 * Note that in case of bigalloc, i_reserved_meta_blocks,
1336 * i_reserved_data_blocks, etc. refer to number of clusters.
1338 percpu_counter_sub(&sbi->s_dirtyclusters_counter,
1339 ei->i_reserved_meta_blocks);
1340 ei->i_reserved_meta_blocks = 0;
1341 ei->i_da_metadata_calc_len = 0;
1344 /* update fs dirty data blocks counter */
1345 percpu_counter_sub(&sbi->s_dirtyclusters_counter, to_free);
1347 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
1349 dquot_release_reservation_block(inode, EXT4_C2B(sbi, to_free));
1352 static void ext4_da_page_release_reservation(struct page *page,
1353 unsigned int offset,
1354 unsigned int length)
1357 struct buffer_head *head, *bh;
1358 unsigned int curr_off = 0;
1359 struct inode *inode = page->mapping->host;
1360 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1361 unsigned int stop = offset + length;
1365 BUG_ON(stop > PAGE_CACHE_SIZE || stop < length);
1367 head = page_buffers(page);
1370 unsigned int next_off = curr_off + bh->b_size;
1372 if (next_off > stop)
1375 if ((offset <= curr_off) && (buffer_delay(bh))) {
1377 clear_buffer_delay(bh);
1379 curr_off = next_off;
1380 } while ((bh = bh->b_this_page) != head);
1383 lblk = page->index << (PAGE_CACHE_SHIFT - inode->i_blkbits);
1384 ext4_es_remove_extent(inode, lblk, to_release);
1387 /* If we have released all the blocks belonging to a cluster, then we
1388 * need to release the reserved space for that cluster. */
1389 num_clusters = EXT4_NUM_B2C(sbi, to_release);
1390 while (num_clusters > 0) {
1391 lblk = (page->index << (PAGE_CACHE_SHIFT - inode->i_blkbits)) +
1392 ((num_clusters - 1) << sbi->s_cluster_bits);
1393 if (sbi->s_cluster_ratio == 1 ||
1394 !ext4_find_delalloc_cluster(inode, lblk))
1395 ext4_da_release_space(inode, 1);
1402 * Delayed allocation stuff
1405 struct mpage_da_data {
1406 struct inode *inode;
1407 struct writeback_control *wbc;
1409 pgoff_t first_page; /* The first page to write */
1410 pgoff_t next_page; /* Current page to examine */
1411 pgoff_t last_page; /* Last page to examine */
1413 * Extent to map - this can be after first_page because that can be
1414 * fully mapped. We somewhat abuse m_flags to store whether the extent
1415 * is delalloc or unwritten.
1417 struct ext4_map_blocks map;
1418 struct ext4_io_submit io_submit; /* IO submission data */
1421 static void mpage_release_unused_pages(struct mpage_da_data *mpd,
1426 struct pagevec pvec;
1427 struct inode *inode = mpd->inode;
1428 struct address_space *mapping = inode->i_mapping;
1430 /* This is necessary when next_page == 0. */
1431 if (mpd->first_page >= mpd->next_page)
1434 index = mpd->first_page;
1435 end = mpd->next_page - 1;
1437 ext4_lblk_t start, last;
1438 start = index << (PAGE_CACHE_SHIFT - inode->i_blkbits);
1439 last = end << (PAGE_CACHE_SHIFT - inode->i_blkbits);
1440 ext4_es_remove_extent(inode, start, last - start + 1);
1443 pagevec_init(&pvec, 0);
1444 while (index <= end) {
1445 nr_pages = pagevec_lookup(&pvec, mapping, index, PAGEVEC_SIZE);
1448 for (i = 0; i < nr_pages; i++) {
1449 struct page *page = pvec.pages[i];
1450 if (page->index > end)
1452 BUG_ON(!PageLocked(page));
1453 BUG_ON(PageWriteback(page));
1455 block_invalidatepage(page, 0, PAGE_CACHE_SIZE);
1456 ClearPageUptodate(page);
1460 index = pvec.pages[nr_pages - 1]->index + 1;
1461 pagevec_release(&pvec);
1465 static void ext4_print_free_blocks(struct inode *inode)
1467 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1468 struct super_block *sb = inode->i_sb;
1469 struct ext4_inode_info *ei = EXT4_I(inode);
1471 ext4_msg(sb, KERN_CRIT, "Total free blocks count %lld",
1472 EXT4_C2B(EXT4_SB(inode->i_sb),
1473 ext4_count_free_clusters(sb)));
1474 ext4_msg(sb, KERN_CRIT, "Free/Dirty block details");
1475 ext4_msg(sb, KERN_CRIT, "free_blocks=%lld",
1476 (long long) EXT4_C2B(EXT4_SB(sb),
1477 percpu_counter_sum(&sbi->s_freeclusters_counter)));
1478 ext4_msg(sb, KERN_CRIT, "dirty_blocks=%lld",
1479 (long long) EXT4_C2B(EXT4_SB(sb),
1480 percpu_counter_sum(&sbi->s_dirtyclusters_counter)));
1481 ext4_msg(sb, KERN_CRIT, "Block reservation details");
1482 ext4_msg(sb, KERN_CRIT, "i_reserved_data_blocks=%u",
1483 ei->i_reserved_data_blocks);
1484 ext4_msg(sb, KERN_CRIT, "i_reserved_meta_blocks=%u",
1485 ei->i_reserved_meta_blocks);
1486 ext4_msg(sb, KERN_CRIT, "i_allocated_meta_blocks=%u",
1487 ei->i_allocated_meta_blocks);
1491 static int ext4_bh_delay_or_unwritten(handle_t *handle, struct buffer_head *bh)
1493 return (buffer_delay(bh) || buffer_unwritten(bh)) && buffer_dirty(bh);
1497 * This function is grabs code from the very beginning of
1498 * ext4_map_blocks, but assumes that the caller is from delayed write
1499 * time. This function looks up the requested blocks and sets the
1500 * buffer delay bit under the protection of i_data_sem.
1502 static int ext4_da_map_blocks(struct inode *inode, sector_t iblock,
1503 struct ext4_map_blocks *map,
1504 struct buffer_head *bh)
1506 struct extent_status es;
1508 sector_t invalid_block = ~((sector_t) 0xffff);
1509 #ifdef ES_AGGRESSIVE_TEST
1510 struct ext4_map_blocks orig_map;
1512 memcpy(&orig_map, map, sizeof(*map));
1515 if (invalid_block < ext4_blocks_count(EXT4_SB(inode->i_sb)->s_es))
1519 ext_debug("ext4_da_map_blocks(): inode %lu, max_blocks %u,"
1520 "logical block %lu\n", inode->i_ino, map->m_len,
1521 (unsigned long) map->m_lblk);
1523 /* Lookup extent status tree firstly */
1524 if (ext4_es_lookup_extent(inode, iblock, &es)) {
1525 ext4_es_lru_add(inode);
1526 if (ext4_es_is_hole(&es)) {
1528 down_read((&EXT4_I(inode)->i_data_sem));
1533 * Delayed extent could be allocated by fallocate.
1534 * So we need to check it.
1536 if (ext4_es_is_delayed(&es) && !ext4_es_is_unwritten(&es)) {
1537 map_bh(bh, inode->i_sb, invalid_block);
1539 set_buffer_delay(bh);
1543 map->m_pblk = ext4_es_pblock(&es) + iblock - es.es_lblk;
1544 retval = es.es_len - (iblock - es.es_lblk);
1545 if (retval > map->m_len)
1546 retval = map->m_len;
1547 map->m_len = retval;
1548 if (ext4_es_is_written(&es))
1549 map->m_flags |= EXT4_MAP_MAPPED;
1550 else if (ext4_es_is_unwritten(&es))
1551 map->m_flags |= EXT4_MAP_UNWRITTEN;
1555 #ifdef ES_AGGRESSIVE_TEST
1556 ext4_map_blocks_es_recheck(NULL, inode, map, &orig_map, 0);
1562 * Try to see if we can get the block without requesting a new
1563 * file system block.
1565 down_read((&EXT4_I(inode)->i_data_sem));
1566 if (ext4_has_inline_data(inode)) {
1568 * We will soon create blocks for this page, and let
1569 * us pretend as if the blocks aren't allocated yet.
1570 * In case of clusters, we have to handle the work
1571 * of mapping from cluster so that the reserved space
1572 * is calculated properly.
1574 if ((EXT4_SB(inode->i_sb)->s_cluster_ratio > 1) &&
1575 ext4_find_delalloc_cluster(inode, map->m_lblk))
1576 map->m_flags |= EXT4_MAP_FROM_CLUSTER;
1578 } else if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
1579 retval = ext4_ext_map_blocks(NULL, inode, map,
1580 EXT4_GET_BLOCKS_NO_PUT_HOLE);
1582 retval = ext4_ind_map_blocks(NULL, inode, map,
1583 EXT4_GET_BLOCKS_NO_PUT_HOLE);
1589 * XXX: __block_prepare_write() unmaps passed block,
1593 * If the block was allocated from previously allocated cluster,
1594 * then we don't need to reserve it again. However we still need
1595 * to reserve metadata for every block we're going to write.
1597 if (!(map->m_flags & EXT4_MAP_FROM_CLUSTER)) {
1598 ret = ext4_da_reserve_space(inode, iblock);
1600 /* not enough space to reserve */
1605 ret = ext4_da_reserve_metadata(inode, iblock);
1607 /* not enough space to reserve */
1613 ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
1614 ~0, EXTENT_STATUS_DELAYED);
1620 /* Clear EXT4_MAP_FROM_CLUSTER flag since its purpose is served
1621 * and it should not appear on the bh->b_state.
1623 map->m_flags &= ~EXT4_MAP_FROM_CLUSTER;
1625 map_bh(bh, inode->i_sb, invalid_block);
1627 set_buffer_delay(bh);
1628 } else if (retval > 0) {
1630 unsigned int status;
1632 if (unlikely(retval != map->m_len)) {
1633 ext4_warning(inode->i_sb,
1634 "ES len assertion failed for inode "
1635 "%lu: retval %d != map->m_len %d",
1636 inode->i_ino, retval, map->m_len);
1640 status = map->m_flags & EXT4_MAP_UNWRITTEN ?
1641 EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
1642 ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
1643 map->m_pblk, status);
1649 up_read((&EXT4_I(inode)->i_data_sem));
1655 * This is a special get_blocks_t callback which is used by
1656 * ext4_da_write_begin(). It will either return mapped block or
1657 * reserve space for a single block.
1659 * For delayed buffer_head we have BH_Mapped, BH_New, BH_Delay set.
1660 * We also have b_blocknr = -1 and b_bdev initialized properly
1662 * For unwritten buffer_head we have BH_Mapped, BH_New, BH_Unwritten set.
1663 * We also have b_blocknr = physicalblock mapping unwritten extent and b_bdev
1664 * initialized properly.
1666 int ext4_da_get_block_prep(struct inode *inode, sector_t iblock,
1667 struct buffer_head *bh, int create)
1669 struct ext4_map_blocks map;
1672 BUG_ON(create == 0);
1673 BUG_ON(bh->b_size != inode->i_sb->s_blocksize);
1675 map.m_lblk = iblock;
1679 * first, we need to know whether the block is allocated already
1680 * preallocated blocks are unmapped but should treated
1681 * the same as allocated blocks.
1683 ret = ext4_da_map_blocks(inode, iblock, &map, bh);
1687 map_bh(bh, inode->i_sb, map.m_pblk);
1688 bh->b_state = (bh->b_state & ~EXT4_MAP_FLAGS) | map.m_flags;
1690 if (buffer_unwritten(bh)) {
1691 /* A delayed write to unwritten bh should be marked
1692 * new and mapped. Mapped ensures that we don't do
1693 * get_block multiple times when we write to the same
1694 * offset and new ensures that we do proper zero out
1695 * for partial write.
1698 set_buffer_mapped(bh);
1703 static int bget_one(handle_t *handle, struct buffer_head *bh)
1709 static int bput_one(handle_t *handle, struct buffer_head *bh)
1715 static int __ext4_journalled_writepage(struct page *page,
1718 struct address_space *mapping = page->mapping;
1719 struct inode *inode = mapping->host;
1720 struct buffer_head *page_bufs = NULL;
1721 handle_t *handle = NULL;
1722 int ret = 0, err = 0;
1723 int inline_data = ext4_has_inline_data(inode);
1724 struct buffer_head *inode_bh = NULL;
1726 ClearPageChecked(page);
1729 BUG_ON(page->index != 0);
1730 BUG_ON(len > ext4_get_max_inline_size(inode));
1731 inode_bh = ext4_journalled_write_inline_data(inode, len, page);
1732 if (inode_bh == NULL)
1735 page_bufs = page_buffers(page);
1740 ext4_walk_page_buffers(handle, page_bufs, 0, len,
1743 /* As soon as we unlock the page, it can go away, but we have
1744 * references to buffers so we are safe */
1747 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
1748 ext4_writepage_trans_blocks(inode));
1749 if (IS_ERR(handle)) {
1750 ret = PTR_ERR(handle);
1754 BUG_ON(!ext4_handle_valid(handle));
1757 ret = ext4_journal_get_write_access(handle, inode_bh);
1759 err = ext4_handle_dirty_metadata(handle, inode, inode_bh);
1762 ret = ext4_walk_page_buffers(handle, page_bufs, 0, len, NULL,
1763 do_journal_get_write_access);
1765 err = ext4_walk_page_buffers(handle, page_bufs, 0, len, NULL,
1770 EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
1771 err = ext4_journal_stop(handle);
1775 if (!ext4_has_inline_data(inode))
1776 ext4_walk_page_buffers(NULL, page_bufs, 0, len,
1778 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
1785 * Note that we don't need to start a transaction unless we're journaling data
1786 * because we should have holes filled from ext4_page_mkwrite(). We even don't
1787 * need to file the inode to the transaction's list in ordered mode because if
1788 * we are writing back data added by write(), the inode is already there and if
1789 * we are writing back data modified via mmap(), no one guarantees in which
1790 * transaction the data will hit the disk. In case we are journaling data, we
1791 * cannot start transaction directly because transaction start ranks above page
1792 * lock so we have to do some magic.
1794 * This function can get called via...
1795 * - ext4_writepages after taking page lock (have journal handle)
1796 * - journal_submit_inode_data_buffers (no journal handle)
1797 * - shrink_page_list via the kswapd/direct reclaim (no journal handle)
1798 * - grab_page_cache when doing write_begin (have journal handle)
1800 * We don't do any block allocation in this function. If we have page with
1801 * multiple blocks we need to write those buffer_heads that are mapped. This
1802 * is important for mmaped based write. So if we do with blocksize 1K
1803 * truncate(f, 1024);
1804 * a = mmap(f, 0, 4096);
1806 * truncate(f, 4096);
1807 * we have in the page first buffer_head mapped via page_mkwrite call back
1808 * but other buffer_heads would be unmapped but dirty (dirty done via the
1809 * do_wp_page). So writepage should write the first block. If we modify
1810 * the mmap area beyond 1024 we will again get a page_fault and the
1811 * page_mkwrite callback will do the block allocation and mark the
1812 * buffer_heads mapped.
1814 * We redirty the page if we have any buffer_heads that is either delay or
1815 * unwritten in the page.
1817 * We can get recursively called as show below.
1819 * ext4_writepage() -> kmalloc() -> __alloc_pages() -> page_launder() ->
1822 * But since we don't do any block allocation we should not deadlock.
1823 * Page also have the dirty flag cleared so we don't get recurive page_lock.
1825 static int ext4_writepage(struct page *page,
1826 struct writeback_control *wbc)
1831 struct buffer_head *page_bufs = NULL;
1832 struct inode *inode = page->mapping->host;
1833 struct ext4_io_submit io_submit;
1835 trace_ext4_writepage(page);
1836 size = i_size_read(inode);
1837 if (page->index == size >> PAGE_CACHE_SHIFT)
1838 len = size & ~PAGE_CACHE_MASK;
1840 len = PAGE_CACHE_SIZE;
1842 page_bufs = page_buffers(page);
1844 * We cannot do block allocation or other extent handling in this
1845 * function. If there are buffers needing that, we have to redirty
1846 * the page. But we may reach here when we do a journal commit via
1847 * journal_submit_inode_data_buffers() and in that case we must write
1848 * allocated buffers to achieve data=ordered mode guarantees.
1850 if (ext4_walk_page_buffers(NULL, page_bufs, 0, len, NULL,
1851 ext4_bh_delay_or_unwritten)) {
1852 redirty_page_for_writepage(wbc, page);
1853 if (current->flags & PF_MEMALLOC) {
1855 * For memory cleaning there's no point in writing only
1856 * some buffers. So just bail out. Warn if we came here
1857 * from direct reclaim.
1859 WARN_ON_ONCE((current->flags & (PF_MEMALLOC|PF_KSWAPD))
1866 if (PageChecked(page) && ext4_should_journal_data(inode))
1868 * It's mmapped pagecache. Add buffers and journal it. There
1869 * doesn't seem much point in redirtying the page here.
1871 return __ext4_journalled_writepage(page, len);
1873 ext4_io_submit_init(&io_submit, wbc);
1874 io_submit.io_end = ext4_init_io_end(inode, GFP_NOFS);
1875 if (!io_submit.io_end) {
1876 redirty_page_for_writepage(wbc, page);
1880 ret = ext4_bio_write_page(&io_submit, page, len, wbc);
1881 ext4_io_submit(&io_submit);
1882 /* Drop io_end reference we got from init */
1883 ext4_put_io_end_defer(io_submit.io_end);
1887 static int mpage_submit_page(struct mpage_da_data *mpd, struct page *page)
1890 loff_t size = i_size_read(mpd->inode);
1893 BUG_ON(page->index != mpd->first_page);
1894 if (page->index == size >> PAGE_CACHE_SHIFT)
1895 len = size & ~PAGE_CACHE_MASK;
1897 len = PAGE_CACHE_SIZE;
1898 clear_page_dirty_for_io(page);
1899 err = ext4_bio_write_page(&mpd->io_submit, page, len, mpd->wbc);
1901 mpd->wbc->nr_to_write--;
1907 #define BH_FLAGS ((1 << BH_Unwritten) | (1 << BH_Delay))
1910 * mballoc gives us at most this number of blocks...
1911 * XXX: That seems to be only a limitation of ext4_mb_normalize_request().
1912 * The rest of mballoc seems to handle chunks up to full group size.
1914 #define MAX_WRITEPAGES_EXTENT_LEN 2048
1917 * mpage_add_bh_to_extent - try to add bh to extent of blocks to map
1919 * @mpd - extent of blocks
1920 * @lblk - logical number of the block in the file
1921 * @bh - buffer head we want to add to the extent
1923 * The function is used to collect contig. blocks in the same state. If the
1924 * buffer doesn't require mapping for writeback and we haven't started the
1925 * extent of buffers to map yet, the function returns 'true' immediately - the
1926 * caller can write the buffer right away. Otherwise the function returns true
1927 * if the block has been added to the extent, false if the block couldn't be
1930 static bool mpage_add_bh_to_extent(struct mpage_da_data *mpd, ext4_lblk_t lblk,
1931 struct buffer_head *bh)
1933 struct ext4_map_blocks *map = &mpd->map;
1935 /* Buffer that doesn't need mapping for writeback? */
1936 if (!buffer_dirty(bh) || !buffer_mapped(bh) ||
1937 (!buffer_delay(bh) && !buffer_unwritten(bh))) {
1938 /* So far no extent to map => we write the buffer right away */
1939 if (map->m_len == 0)
1944 /* First block in the extent? */
1945 if (map->m_len == 0) {
1948 map->m_flags = bh->b_state & BH_FLAGS;
1952 /* Don't go larger than mballoc is willing to allocate */
1953 if (map->m_len >= MAX_WRITEPAGES_EXTENT_LEN)
1956 /* Can we merge the block to our big extent? */
1957 if (lblk == map->m_lblk + map->m_len &&
1958 (bh->b_state & BH_FLAGS) == map->m_flags) {
1966 * mpage_process_page_bufs - submit page buffers for IO or add them to extent
1968 * @mpd - extent of blocks for mapping
1969 * @head - the first buffer in the page
1970 * @bh - buffer we should start processing from
1971 * @lblk - logical number of the block in the file corresponding to @bh
1973 * Walk through page buffers from @bh upto @head (exclusive) and either submit
1974 * the page for IO if all buffers in this page were mapped and there's no
1975 * accumulated extent of buffers to map or add buffers in the page to the
1976 * extent of buffers to map. The function returns 1 if the caller can continue
1977 * by processing the next page, 0 if it should stop adding buffers to the
1978 * extent to map because we cannot extend it anymore. It can also return value
1979 * < 0 in case of error during IO submission.
1981 static int mpage_process_page_bufs(struct mpage_da_data *mpd,
1982 struct buffer_head *head,
1983 struct buffer_head *bh,
1986 struct inode *inode = mpd->inode;
1988 ext4_lblk_t blocks = (i_size_read(inode) + (1 << inode->i_blkbits) - 1)
1989 >> inode->i_blkbits;
1992 BUG_ON(buffer_locked(bh));
1994 if (lblk >= blocks || !mpage_add_bh_to_extent(mpd, lblk, bh)) {
1995 /* Found extent to map? */
1998 /* Everything mapped so far and we hit EOF */
2001 } while (lblk++, (bh = bh->b_this_page) != head);
2002 /* So far everything mapped? Submit the page for IO. */
2003 if (mpd->map.m_len == 0) {
2004 err = mpage_submit_page(mpd, head->b_page);
2008 return lblk < blocks;
2012 * mpage_map_buffers - update buffers corresponding to changed extent and
2013 * submit fully mapped pages for IO
2015 * @mpd - description of extent to map, on return next extent to map
2017 * Scan buffers corresponding to changed extent (we expect corresponding pages
2018 * to be already locked) and update buffer state according to new extent state.
2019 * We map delalloc buffers to their physical location, clear unwritten bits,
2020 * and mark buffers as uninit when we perform writes to uninitialized extents
2021 * and do extent conversion after IO is finished. If the last page is not fully
2022 * mapped, we update @map to the next extent in the last page that needs
2023 * mapping. Otherwise we submit the page for IO.
2025 static int mpage_map_and_submit_buffers(struct mpage_da_data *mpd)
2027 struct pagevec pvec;
2029 struct inode *inode = mpd->inode;
2030 struct buffer_head *head, *bh;
2031 int bpp_bits = PAGE_CACHE_SHIFT - inode->i_blkbits;
2037 start = mpd->map.m_lblk >> bpp_bits;
2038 end = (mpd->map.m_lblk + mpd->map.m_len - 1) >> bpp_bits;
2039 lblk = start << bpp_bits;
2040 pblock = mpd->map.m_pblk;
2042 pagevec_init(&pvec, 0);
2043 while (start <= end) {
2044 nr_pages = pagevec_lookup(&pvec, inode->i_mapping, start,
2048 for (i = 0; i < nr_pages; i++) {
2049 struct page *page = pvec.pages[i];
2051 if (page->index > end)
2053 /* Up to 'end' pages must be contiguous */
2054 BUG_ON(page->index != start);
2055 bh = head = page_buffers(page);
2057 if (lblk < mpd->map.m_lblk)
2059 if (lblk >= mpd->map.m_lblk + mpd->map.m_len) {
2061 * Buffer after end of mapped extent.
2062 * Find next buffer in the page to map.
2065 mpd->map.m_flags = 0;
2067 * FIXME: If dioread_nolock supports
2068 * blocksize < pagesize, we need to make
2069 * sure we add size mapped so far to
2070 * io_end->size as the following call
2071 * can submit the page for IO.
2073 err = mpage_process_page_bufs(mpd, head,
2075 pagevec_release(&pvec);
2080 if (buffer_delay(bh)) {
2081 clear_buffer_delay(bh);
2082 bh->b_blocknr = pblock++;
2084 clear_buffer_unwritten(bh);
2085 } while (lblk++, (bh = bh->b_this_page) != head);
2088 * FIXME: This is going to break if dioread_nolock
2089 * supports blocksize < pagesize as we will try to
2090 * convert potentially unmapped parts of inode.
2092 mpd->io_submit.io_end->size += PAGE_CACHE_SIZE;
2093 /* Page fully mapped - let IO run! */
2094 err = mpage_submit_page(mpd, page);
2096 pagevec_release(&pvec);
2101 pagevec_release(&pvec);
2103 /* Extent fully mapped and matches with page boundary. We are done. */
2105 mpd->map.m_flags = 0;
2109 static int mpage_map_one_extent(handle_t *handle, struct mpage_da_data *mpd)
2111 struct inode *inode = mpd->inode;
2112 struct ext4_map_blocks *map = &mpd->map;
2113 int get_blocks_flags;
2116 trace_ext4_da_write_pages_extent(inode, map);
2118 * Call ext4_map_blocks() to allocate any delayed allocation blocks, or
2119 * to convert an uninitialized extent to be initialized (in the case
2120 * where we have written into one or more preallocated blocks). It is
2121 * possible that we're going to need more metadata blocks than
2122 * previously reserved. However we must not fail because we're in
2123 * writeback and there is nothing we can do about it so it might result
2124 * in data loss. So use reserved blocks to allocate metadata if
2127 * We pass in the magic EXT4_GET_BLOCKS_DELALLOC_RESERVE if the blocks
2128 * in question are delalloc blocks. This affects functions in many
2129 * different parts of the allocation call path. This flag exists
2130 * primarily because we don't want to change *many* call functions, so
2131 * ext4_map_blocks() will set the EXT4_STATE_DELALLOC_RESERVED flag
2132 * once the inode's allocation semaphore is taken.
2134 get_blocks_flags = EXT4_GET_BLOCKS_CREATE |
2135 EXT4_GET_BLOCKS_METADATA_NOFAIL;
2136 if (ext4_should_dioread_nolock(inode))
2137 get_blocks_flags |= EXT4_GET_BLOCKS_IO_CREATE_EXT;
2138 if (map->m_flags & (1 << BH_Delay))
2139 get_blocks_flags |= EXT4_GET_BLOCKS_DELALLOC_RESERVE;
2141 err = ext4_map_blocks(handle, inode, map, get_blocks_flags);
2144 if (map->m_flags & EXT4_MAP_UNINIT) {
2145 if (!mpd->io_submit.io_end->handle &&
2146 ext4_handle_valid(handle)) {
2147 mpd->io_submit.io_end->handle = handle->h_rsv_handle;
2148 handle->h_rsv_handle = NULL;
2150 ext4_set_io_unwritten_flag(inode, mpd->io_submit.io_end);
2153 BUG_ON(map->m_len == 0);
2154 if (map->m_flags & EXT4_MAP_NEW) {
2155 struct block_device *bdev = inode->i_sb->s_bdev;
2158 for (i = 0; i < map->m_len; i++)
2159 unmap_underlying_metadata(bdev, map->m_pblk + i);
2165 * mpage_map_and_submit_extent - map extent starting at mpd->lblk of length
2166 * mpd->len and submit pages underlying it for IO
2168 * @handle - handle for journal operations
2169 * @mpd - extent to map
2170 * @give_up_on_write - we set this to true iff there is a fatal error and there
2171 * is no hope of writing the data. The caller should discard
2172 * dirty pages to avoid infinite loops.
2174 * The function maps extent starting at mpd->lblk of length mpd->len. If it is
2175 * delayed, blocks are allocated, if it is unwritten, we may need to convert
2176 * them to initialized or split the described range from larger unwritten
2177 * extent. Note that we need not map all the described range since allocation
2178 * can return less blocks or the range is covered by more unwritten extents. We
2179 * cannot map more because we are limited by reserved transaction credits. On
2180 * the other hand we always make sure that the last touched page is fully
2181 * mapped so that it can be written out (and thus forward progress is
2182 * guaranteed). After mapping we submit all mapped pages for IO.
2184 static int mpage_map_and_submit_extent(handle_t *handle,
2185 struct mpage_da_data *mpd,
2186 bool *give_up_on_write)
2188 struct inode *inode = mpd->inode;
2189 struct ext4_map_blocks *map = &mpd->map;
2193 mpd->io_submit.io_end->offset =
2194 ((loff_t)map->m_lblk) << inode->i_blkbits;
2196 err = mpage_map_one_extent(handle, mpd);
2198 struct super_block *sb = inode->i_sb;
2200 if (EXT4_SB(sb)->s_mount_flags & EXT4_MF_FS_ABORTED)
2201 goto invalidate_dirty_pages;
2203 * Let the uper layers retry transient errors.
2204 * In the case of ENOSPC, if ext4_count_free_blocks()
2205 * is non-zero, a commit should free up blocks.
2207 if ((err == -ENOMEM) ||
2208 (err == -ENOSPC && ext4_count_free_clusters(sb)))
2210 ext4_msg(sb, KERN_CRIT,
2211 "Delayed block allocation failed for "
2212 "inode %lu at logical offset %llu with"
2213 " max blocks %u with error %d",
2215 (unsigned long long)map->m_lblk,
2216 (unsigned)map->m_len, -err);
2217 ext4_msg(sb, KERN_CRIT,
2218 "This should not happen!! Data will "
2221 ext4_print_free_blocks(inode);
2222 invalidate_dirty_pages:
2223 *give_up_on_write = true;
2227 * Update buffer state, submit mapped pages, and get us new
2230 err = mpage_map_and_submit_buffers(mpd);
2233 } while (map->m_len);
2235 /* Update on-disk size after IO is submitted */
2236 disksize = ((loff_t)mpd->first_page) << PAGE_CACHE_SHIFT;
2237 if (disksize > EXT4_I(inode)->i_disksize) {
2240 ext4_wb_update_i_disksize(inode, disksize);
2241 err2 = ext4_mark_inode_dirty(handle, inode);
2243 ext4_error(inode->i_sb,
2244 "Failed to mark inode %lu dirty",
2253 * Calculate the total number of credits to reserve for one writepages
2254 * iteration. This is called from ext4_writepages(). We map an extent of
2255 * up to MAX_WRITEPAGES_EXTENT_LEN blocks and then we go on and finish mapping
2256 * the last partial page. So in total we can map MAX_WRITEPAGES_EXTENT_LEN +
2257 * bpp - 1 blocks in bpp different extents.
2259 static int ext4_da_writepages_trans_blocks(struct inode *inode)
2261 int bpp = ext4_journal_blocks_per_page(inode);
2263 return ext4_meta_trans_blocks(inode,
2264 MAX_WRITEPAGES_EXTENT_LEN + bpp - 1, bpp);
2268 * mpage_prepare_extent_to_map - find & lock contiguous range of dirty pages
2269 * and underlying extent to map
2271 * @mpd - where to look for pages
2273 * Walk dirty pages in the mapping. If they are fully mapped, submit them for
2274 * IO immediately. When we find a page which isn't mapped we start accumulating
2275 * extent of buffers underlying these pages that needs mapping (formed by
2276 * either delayed or unwritten buffers). We also lock the pages containing
2277 * these buffers. The extent found is returned in @mpd structure (starting at
2278 * mpd->lblk with length mpd->len blocks).
2280 * Note that this function can attach bios to one io_end structure which are
2281 * neither logically nor physically contiguous. Although it may seem as an
2282 * unnecessary complication, it is actually inevitable in blocksize < pagesize
2283 * case as we need to track IO to all buffers underlying a page in one io_end.
2285 static int mpage_prepare_extent_to_map(struct mpage_da_data *mpd)
2287 struct address_space *mapping = mpd->inode->i_mapping;
2288 struct pagevec pvec;
2289 unsigned int nr_pages;
2290 long left = mpd->wbc->nr_to_write;
2291 pgoff_t index = mpd->first_page;
2292 pgoff_t end = mpd->last_page;
2295 int blkbits = mpd->inode->i_blkbits;
2297 struct buffer_head *head;
2299 if (mpd->wbc->sync_mode == WB_SYNC_ALL || mpd->wbc->tagged_writepages)
2300 tag = PAGECACHE_TAG_TOWRITE;
2302 tag = PAGECACHE_TAG_DIRTY;
2304 pagevec_init(&pvec, 0);
2306 mpd->next_page = index;
2307 while (index <= end) {
2308 nr_pages = pagevec_lookup_tag(&pvec, mapping, &index, tag,
2309 min(end - index, (pgoff_t)PAGEVEC_SIZE-1) + 1);
2313 for (i = 0; i < nr_pages; i++) {
2314 struct page *page = pvec.pages[i];
2317 * At this point, the page may be truncated or
2318 * invalidated (changing page->mapping to NULL), or
2319 * even swizzled back from swapper_space to tmpfs file
2320 * mapping. However, page->index will not change
2321 * because we have a reference on the page.
2323 if (page->index > end)
2327 * Accumulated enough dirty pages? This doesn't apply
2328 * to WB_SYNC_ALL mode. For integrity sync we have to
2329 * keep going because someone may be concurrently
2330 * dirtying pages, and we might have synced a lot of
2331 * newly appeared dirty pages, but have not synced all
2332 * of the old dirty pages.
2334 if (mpd->wbc->sync_mode == WB_SYNC_NONE && left <= 0)
2337 /* If we can't merge this page, we are done. */
2338 if (mpd->map.m_len > 0 && mpd->next_page != page->index)
2343 * If the page is no longer dirty, or its mapping no
2344 * longer corresponds to inode we are writing (which
2345 * means it has been truncated or invalidated), or the
2346 * page is already under writeback and we are not doing
2347 * a data integrity writeback, skip the page
2349 if (!PageDirty(page) ||
2350 (PageWriteback(page) &&
2351 (mpd->wbc->sync_mode == WB_SYNC_NONE)) ||
2352 unlikely(page->mapping != mapping)) {
2357 wait_on_page_writeback(page);
2358 BUG_ON(PageWriteback(page));
2360 if (mpd->map.m_len == 0)
2361 mpd->first_page = page->index;
2362 mpd->next_page = page->index + 1;
2363 /* Add all dirty buffers to mpd */
2364 lblk = ((ext4_lblk_t)page->index) <<
2365 (PAGE_CACHE_SHIFT - blkbits);
2366 head = page_buffers(page);
2367 err = mpage_process_page_bufs(mpd, head, head, lblk);
2373 pagevec_release(&pvec);
2378 pagevec_release(&pvec);
2382 static int __writepage(struct page *page, struct writeback_control *wbc,
2385 struct address_space *mapping = data;
2386 int ret = ext4_writepage(page, wbc);
2387 mapping_set_error(mapping, ret);
2391 static int ext4_writepages(struct address_space *mapping,
2392 struct writeback_control *wbc)
2394 pgoff_t writeback_index = 0;
2395 long nr_to_write = wbc->nr_to_write;
2396 int range_whole = 0;
2398 handle_t *handle = NULL;
2399 struct mpage_da_data mpd;
2400 struct inode *inode = mapping->host;
2401 int needed_blocks, rsv_blocks = 0, ret = 0;
2402 struct ext4_sb_info *sbi = EXT4_SB(mapping->host->i_sb);
2404 struct blk_plug plug;
2405 bool give_up_on_write = false;
2407 trace_ext4_writepages(inode, wbc);
2410 * No pages to write? This is mainly a kludge to avoid starting
2411 * a transaction for special inodes like journal inode on last iput()
2412 * because that could violate lock ordering on umount
2414 if (!mapping->nrpages || !mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
2415 goto out_writepages;
2417 if (ext4_should_journal_data(inode)) {
2418 struct blk_plug plug;
2420 blk_start_plug(&plug);
2421 ret = write_cache_pages(mapping, wbc, __writepage, mapping);
2422 blk_finish_plug(&plug);
2423 goto out_writepages;
2427 * If the filesystem has aborted, it is read-only, so return
2428 * right away instead of dumping stack traces later on that
2429 * will obscure the real source of the problem. We test
2430 * EXT4_MF_FS_ABORTED instead of sb->s_flag's MS_RDONLY because
2431 * the latter could be true if the filesystem is mounted
2432 * read-only, and in that case, ext4_writepages should
2433 * *never* be called, so if that ever happens, we would want
2436 if (unlikely(sbi->s_mount_flags & EXT4_MF_FS_ABORTED)) {
2438 goto out_writepages;
2441 if (ext4_should_dioread_nolock(inode)) {
2443 * We may need to convert up to one extent per block in
2444 * the page and we may dirty the inode.
2446 rsv_blocks = 1 + (PAGE_CACHE_SIZE >> inode->i_blkbits);
2450 * If we have inline data and arrive here, it means that
2451 * we will soon create the block for the 1st page, so
2452 * we'd better clear the inline data here.
2454 if (ext4_has_inline_data(inode)) {
2455 /* Just inode will be modified... */
2456 handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
2457 if (IS_ERR(handle)) {
2458 ret = PTR_ERR(handle);
2459 goto out_writepages;
2461 BUG_ON(ext4_test_inode_state(inode,
2462 EXT4_STATE_MAY_INLINE_DATA));
2463 ext4_destroy_inline_data(handle, inode);
2464 ext4_journal_stop(handle);
2467 if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
2470 if (wbc->range_cyclic) {
2471 writeback_index = mapping->writeback_index;
2472 if (writeback_index)
2474 mpd.first_page = writeback_index;
2477 mpd.first_page = wbc->range_start >> PAGE_CACHE_SHIFT;
2478 mpd.last_page = wbc->range_end >> PAGE_CACHE_SHIFT;
2483 ext4_io_submit_init(&mpd.io_submit, wbc);
2485 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
2486 tag_pages_for_writeback(mapping, mpd.first_page, mpd.last_page);
2488 blk_start_plug(&plug);
2489 while (!done && mpd.first_page <= mpd.last_page) {
2490 /* For each extent of pages we use new io_end */
2491 mpd.io_submit.io_end = ext4_init_io_end(inode, GFP_KERNEL);
2492 if (!mpd.io_submit.io_end) {
2498 * We have two constraints: We find one extent to map and we
2499 * must always write out whole page (makes a difference when
2500 * blocksize < pagesize) so that we don't block on IO when we
2501 * try to write out the rest of the page. Journalled mode is
2502 * not supported by delalloc.
2504 BUG_ON(ext4_should_journal_data(inode));
2505 needed_blocks = ext4_da_writepages_trans_blocks(inode);
2507 /* start a new transaction */
2508 handle = ext4_journal_start_with_reserve(inode,
2509 EXT4_HT_WRITE_PAGE, needed_blocks, rsv_blocks);
2510 if (IS_ERR(handle)) {
2511 ret = PTR_ERR(handle);
2512 ext4_msg(inode->i_sb, KERN_CRIT, "%s: jbd2_start: "
2513 "%ld pages, ino %lu; err %d", __func__,
2514 wbc->nr_to_write, inode->i_ino, ret);
2515 /* Release allocated io_end */
2516 ext4_put_io_end(mpd.io_submit.io_end);
2520 trace_ext4_da_write_pages(inode, mpd.first_page, mpd.wbc);
2521 ret = mpage_prepare_extent_to_map(&mpd);
2524 ret = mpage_map_and_submit_extent(handle, &mpd,
2528 * We scanned the whole range (or exhausted
2529 * nr_to_write), submitted what was mapped and
2530 * didn't find anything needing mapping. We are
2536 ext4_journal_stop(handle);
2537 /* Submit prepared bio */
2538 ext4_io_submit(&mpd.io_submit);
2539 /* Unlock pages we didn't use */
2540 mpage_release_unused_pages(&mpd, give_up_on_write);
2541 /* Drop our io_end reference we got from init */
2542 ext4_put_io_end(mpd.io_submit.io_end);
2544 if (ret == -ENOSPC && sbi->s_journal) {
2546 * Commit the transaction which would
2547 * free blocks released in the transaction
2550 jbd2_journal_force_commit_nested(sbi->s_journal);
2554 /* Fatal error - ENOMEM, EIO... */
2558 blk_finish_plug(&plug);
2559 if (!ret && !cycled && wbc->nr_to_write > 0) {
2561 mpd.last_page = writeback_index - 1;
2567 if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
2569 * Set the writeback_index so that range_cyclic
2570 * mode will write it back later
2572 mapping->writeback_index = mpd.first_page;
2575 trace_ext4_writepages_result(inode, wbc, ret,
2576 nr_to_write - wbc->nr_to_write);
2580 static int ext4_nonda_switch(struct super_block *sb)
2582 s64 free_clusters, dirty_clusters;
2583 struct ext4_sb_info *sbi = EXT4_SB(sb);
2586 * switch to non delalloc mode if we are running low
2587 * on free block. The free block accounting via percpu
2588 * counters can get slightly wrong with percpu_counter_batch getting
2589 * accumulated on each CPU without updating global counters
2590 * Delalloc need an accurate free block accounting. So switch
2591 * to non delalloc when we are near to error range.
2594 percpu_counter_read_positive(&sbi->s_freeclusters_counter);
2596 percpu_counter_read_positive(&sbi->s_dirtyclusters_counter);
2598 * Start pushing delalloc when 1/2 of free blocks are dirty.
2600 if (dirty_clusters && (free_clusters < 2 * dirty_clusters))
2601 try_to_writeback_inodes_sb(sb, WB_REASON_FS_FREE_SPACE);
2603 if (2 * free_clusters < 3 * dirty_clusters ||
2604 free_clusters < (dirty_clusters + EXT4_FREECLUSTERS_WATERMARK)) {
2606 * free block count is less than 150% of dirty blocks
2607 * or free blocks is less than watermark
2614 static int ext4_da_write_begin(struct file *file, struct address_space *mapping,
2615 loff_t pos, unsigned len, unsigned flags,
2616 struct page **pagep, void **fsdata)
2618 int ret, retries = 0;
2621 struct inode *inode = mapping->host;
2624 index = pos >> PAGE_CACHE_SHIFT;
2626 if (ext4_nonda_switch(inode->i_sb)) {
2627 *fsdata = (void *)FALL_BACK_TO_NONDELALLOC;
2628 return ext4_write_begin(file, mapping, pos,
2629 len, flags, pagep, fsdata);
2631 *fsdata = (void *)0;
2632 trace_ext4_da_write_begin(inode, pos, len, flags);
2634 if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
2635 ret = ext4_da_write_inline_data_begin(mapping, inode,
2645 * grab_cache_page_write_begin() can take a long time if the
2646 * system is thrashing due to memory pressure, or if the page
2647 * is being written back. So grab it first before we start
2648 * the transaction handle. This also allows us to allocate
2649 * the page (if needed) without using GFP_NOFS.
2652 page = grab_cache_page_write_begin(mapping, index, flags);
2658 * With delayed allocation, we don't log the i_disksize update
2659 * if there is delayed block allocation. But we still need
2660 * to journalling the i_disksize update if writes to the end
2661 * of file which has an already mapped buffer.
2664 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE, 1);
2665 if (IS_ERR(handle)) {
2666 page_cache_release(page);
2667 return PTR_ERR(handle);
2671 if (page->mapping != mapping) {
2672 /* The page got truncated from under us */
2674 page_cache_release(page);
2675 ext4_journal_stop(handle);
2678 /* In case writeback began while the page was unlocked */
2679 wait_for_stable_page(page);
2681 ret = __block_write_begin(page, pos, len, ext4_da_get_block_prep);
2684 ext4_journal_stop(handle);
2686 * block_write_begin may have instantiated a few blocks
2687 * outside i_size. Trim these off again. Don't need
2688 * i_size_read because we hold i_mutex.
2690 if (pos + len > inode->i_size)
2691 ext4_truncate_failed_write(inode);
2693 if (ret == -ENOSPC &&
2694 ext4_should_retry_alloc(inode->i_sb, &retries))
2697 page_cache_release(page);
2706 * Check if we should update i_disksize
2707 * when write to the end of file but not require block allocation
2709 static int ext4_da_should_update_i_disksize(struct page *page,
2710 unsigned long offset)
2712 struct buffer_head *bh;
2713 struct inode *inode = page->mapping->host;
2717 bh = page_buffers(page);
2718 idx = offset >> inode->i_blkbits;
2720 for (i = 0; i < idx; i++)
2721 bh = bh->b_this_page;
2723 if (!buffer_mapped(bh) || (buffer_delay(bh)) || buffer_unwritten(bh))
2728 static int ext4_da_write_end(struct file *file,
2729 struct address_space *mapping,
2730 loff_t pos, unsigned len, unsigned copied,
2731 struct page *page, void *fsdata)
2733 struct inode *inode = mapping->host;
2735 handle_t *handle = ext4_journal_current_handle();
2737 unsigned long start, end;
2738 int write_mode = (int)(unsigned long)fsdata;
2740 if (write_mode == FALL_BACK_TO_NONDELALLOC)
2741 return ext4_write_end(file, mapping, pos,
2742 len, copied, page, fsdata);
2744 trace_ext4_da_write_end(inode, pos, len, copied);
2745 start = pos & (PAGE_CACHE_SIZE - 1);
2746 end = start + copied - 1;
2749 * generic_write_end() will run mark_inode_dirty() if i_size
2750 * changes. So let's piggyback the i_disksize mark_inode_dirty
2753 new_i_size = pos + copied;
2754 if (copied && new_i_size > EXT4_I(inode)->i_disksize) {
2755 if (ext4_has_inline_data(inode) ||
2756 ext4_da_should_update_i_disksize(page, end)) {
2757 down_write(&EXT4_I(inode)->i_data_sem);
2758 if (new_i_size > EXT4_I(inode)->i_disksize)
2759 EXT4_I(inode)->i_disksize = new_i_size;
2760 up_write(&EXT4_I(inode)->i_data_sem);
2761 /* We need to mark inode dirty even if
2762 * new_i_size is less that inode->i_size
2763 * bu greater than i_disksize.(hint delalloc)
2765 ext4_mark_inode_dirty(handle, inode);
2769 if (write_mode != CONVERT_INLINE_DATA &&
2770 ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA) &&
2771 ext4_has_inline_data(inode))
2772 ret2 = ext4_da_write_inline_data_end(inode, pos, len, copied,
2775 ret2 = generic_write_end(file, mapping, pos, len, copied,
2781 ret2 = ext4_journal_stop(handle);
2785 return ret ? ret : copied;
2788 static void ext4_da_invalidatepage(struct page *page, unsigned int offset,
2789 unsigned int length)
2792 * Drop reserved blocks
2794 BUG_ON(!PageLocked(page));
2795 if (!page_has_buffers(page))
2798 ext4_da_page_release_reservation(page, offset, length);
2801 ext4_invalidatepage(page, offset, length);
2807 * Force all delayed allocation blocks to be allocated for a given inode.
2809 int ext4_alloc_da_blocks(struct inode *inode)
2811 trace_ext4_alloc_da_blocks(inode);
2813 if (!EXT4_I(inode)->i_reserved_data_blocks &&
2814 !EXT4_I(inode)->i_reserved_meta_blocks)
2818 * We do something simple for now. The filemap_flush() will
2819 * also start triggering a write of the data blocks, which is
2820 * not strictly speaking necessary (and for users of
2821 * laptop_mode, not even desirable). However, to do otherwise
2822 * would require replicating code paths in:
2824 * ext4_writepages() ->
2825 * write_cache_pages() ---> (via passed in callback function)
2826 * __mpage_da_writepage() -->
2827 * mpage_add_bh_to_extent()
2828 * mpage_da_map_blocks()
2830 * The problem is that write_cache_pages(), located in
2831 * mm/page-writeback.c, marks pages clean in preparation for
2832 * doing I/O, which is not desirable if we're not planning on
2835 * We could call write_cache_pages(), and then redirty all of
2836 * the pages by calling redirty_page_for_writepage() but that
2837 * would be ugly in the extreme. So instead we would need to
2838 * replicate parts of the code in the above functions,
2839 * simplifying them because we wouldn't actually intend to
2840 * write out the pages, but rather only collect contiguous
2841 * logical block extents, call the multi-block allocator, and
2842 * then update the buffer heads with the block allocations.
2844 * For now, though, we'll cheat by calling filemap_flush(),
2845 * which will map the blocks, and start the I/O, but not
2846 * actually wait for the I/O to complete.
2848 return filemap_flush(inode->i_mapping);
2852 * bmap() is special. It gets used by applications such as lilo and by
2853 * the swapper to find the on-disk block of a specific piece of data.
2855 * Naturally, this is dangerous if the block concerned is still in the
2856 * journal. If somebody makes a swapfile on an ext4 data-journaling
2857 * filesystem and enables swap, then they may get a nasty shock when the
2858 * data getting swapped to that swapfile suddenly gets overwritten by
2859 * the original zero's written out previously to the journal and
2860 * awaiting writeback in the kernel's buffer cache.
2862 * So, if we see any bmap calls here on a modified, data-journaled file,
2863 * take extra steps to flush any blocks which might be in the cache.
2865 static sector_t ext4_bmap(struct address_space *mapping, sector_t block)
2867 struct inode *inode = mapping->host;
2872 * We can get here for an inline file via the FIBMAP ioctl
2874 if (ext4_has_inline_data(inode))
2877 if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY) &&
2878 test_opt(inode->i_sb, DELALLOC)) {
2880 * With delalloc we want to sync the file
2881 * so that we can make sure we allocate
2884 filemap_write_and_wait(mapping);
2887 if (EXT4_JOURNAL(inode) &&
2888 ext4_test_inode_state(inode, EXT4_STATE_JDATA)) {
2890 * This is a REALLY heavyweight approach, but the use of
2891 * bmap on dirty files is expected to be extremely rare:
2892 * only if we run lilo or swapon on a freshly made file
2893 * do we expect this to happen.
2895 * (bmap requires CAP_SYS_RAWIO so this does not
2896 * represent an unprivileged user DOS attack --- we'd be
2897 * in trouble if mortal users could trigger this path at
2900 * NB. EXT4_STATE_JDATA is not set on files other than
2901 * regular files. If somebody wants to bmap a directory
2902 * or symlink and gets confused because the buffer
2903 * hasn't yet been flushed to disk, they deserve
2904 * everything they get.
2907 ext4_clear_inode_state(inode, EXT4_STATE_JDATA);
2908 journal = EXT4_JOURNAL(inode);
2909 jbd2_journal_lock_updates(journal);
2910 err = jbd2_journal_flush(journal);
2911 jbd2_journal_unlock_updates(journal);
2917 return generic_block_bmap(mapping, block, ext4_get_block);
2920 static int ext4_readpage(struct file *file, struct page *page)
2923 struct inode *inode = page->mapping->host;
2925 trace_ext4_readpage(page);
2927 if (ext4_has_inline_data(inode))
2928 ret = ext4_readpage_inline(inode, page);
2931 return mpage_readpage(page, ext4_get_block);
2937 ext4_readpages(struct file *file, struct address_space *mapping,
2938 struct list_head *pages, unsigned nr_pages)
2940 struct inode *inode = mapping->host;
2942 /* If the file has inline data, no need to do readpages. */
2943 if (ext4_has_inline_data(inode))
2946 return mpage_readpages(mapping, pages, nr_pages, ext4_get_block);
2949 static void ext4_invalidatepage(struct page *page, unsigned int offset,
2950 unsigned int length)
2952 trace_ext4_invalidatepage(page, offset, length);
2954 /* No journalling happens on data buffers when this function is used */
2955 WARN_ON(page_has_buffers(page) && buffer_jbd(page_buffers(page)));
2957 block_invalidatepage(page, offset, length);
2960 static int __ext4_journalled_invalidatepage(struct page *page,
2961 unsigned int offset,
2962 unsigned int length)
2964 journal_t *journal = EXT4_JOURNAL(page->mapping->host);
2966 trace_ext4_journalled_invalidatepage(page, offset, length);
2969 * If it's a full truncate we just forget about the pending dirtying
2971 if (offset == 0 && length == PAGE_CACHE_SIZE)
2972 ClearPageChecked(page);
2974 return jbd2_journal_invalidatepage(journal, page, offset, length);
2977 /* Wrapper for aops... */
2978 static void ext4_journalled_invalidatepage(struct page *page,
2979 unsigned int offset,
2980 unsigned int length)
2982 WARN_ON(__ext4_journalled_invalidatepage(page, offset, length) < 0);
2985 static int ext4_releasepage(struct page *page, gfp_t wait)
2987 journal_t *journal = EXT4_JOURNAL(page->mapping->host);
2989 trace_ext4_releasepage(page);
2991 /* Page has dirty journalled data -> cannot release */
2992 if (PageChecked(page))
2995 return jbd2_journal_try_to_free_buffers(journal, page, wait);
2997 return try_to_free_buffers(page);
3001 * ext4_get_block used when preparing for a DIO write or buffer write.
3002 * We allocate an uinitialized extent if blocks haven't been allocated.
3003 * The extent will be converted to initialized after the IO is complete.
3005 int ext4_get_block_write(struct inode *inode, sector_t iblock,
3006 struct buffer_head *bh_result, int create)
3008 ext4_debug("ext4_get_block_write: inode %lu, create flag %d\n",
3009 inode->i_ino, create);
3010 return _ext4_get_block(inode, iblock, bh_result,
3011 EXT4_GET_BLOCKS_IO_CREATE_EXT);
3014 static int ext4_get_block_write_nolock(struct inode *inode, sector_t iblock,
3015 struct buffer_head *bh_result, int create)
3017 ext4_debug("ext4_get_block_write_nolock: inode %lu, create flag %d\n",
3018 inode->i_ino, create);
3019 return _ext4_get_block(inode, iblock, bh_result,
3020 EXT4_GET_BLOCKS_NO_LOCK);
3023 static void ext4_end_io_dio(struct kiocb *iocb, loff_t offset,
3024 ssize_t size, void *private)
3026 ext4_io_end_t *io_end = iocb->private;
3028 /* if not async direct IO just return */
3032 ext_debug("ext4_end_io_dio(): io_end 0x%p "
3033 "for inode %lu, iocb 0x%p, offset %llu, size %zd\n",
3034 iocb->private, io_end->inode->i_ino, iocb, offset,
3037 iocb->private = NULL;
3038 io_end->offset = offset;
3039 io_end->size = size;
3040 ext4_put_io_end(io_end);
3044 * For ext4 extent files, ext4 will do direct-io write to holes,
3045 * preallocated extents, and those write extend the file, no need to
3046 * fall back to buffered IO.
3048 * For holes, we fallocate those blocks, mark them as uninitialized
3049 * If those blocks were preallocated, we mark sure they are split, but
3050 * still keep the range to write as uninitialized.
3052 * The unwritten extents will be converted to written when DIO is completed.
3053 * For async direct IO, since the IO may still pending when return, we
3054 * set up an end_io call back function, which will do the conversion
3055 * when async direct IO completed.
3057 * If the O_DIRECT write will extend the file then add this inode to the
3058 * orphan list. So recovery will truncate it back to the original size
3059 * if the machine crashes during the write.
3062 static ssize_t ext4_ext_direct_IO(int rw, struct kiocb *iocb,
3063 const struct iovec *iov, loff_t offset,
3064 unsigned long nr_segs)
3066 struct file *file = iocb->ki_filp;
3067 struct inode *inode = file->f_mapping->host;
3069 size_t count = iov_length(iov, nr_segs);
3071 get_block_t *get_block_func = NULL;
3073 loff_t final_size = offset + count;
3074 ext4_io_end_t *io_end = NULL;
3076 /* Use the old path for reads and writes beyond i_size. */
3077 if (rw != WRITE || final_size > inode->i_size)
3078 return ext4_ind_direct_IO(rw, iocb, iov, offset, nr_segs);
3080 BUG_ON(iocb->private == NULL);
3083 * Make all waiters for direct IO properly wait also for extent
3084 * conversion. This also disallows race between truncate() and
3085 * overwrite DIO as i_dio_count needs to be incremented under i_mutex.
3088 atomic_inc(&inode->i_dio_count);
3090 /* If we do a overwrite dio, i_mutex locking can be released */
3091 overwrite = *((int *)iocb->private);
3094 down_read(&EXT4_I(inode)->i_data_sem);
3095 mutex_unlock(&inode->i_mutex);
3099 * We could direct write to holes and fallocate.
3101 * Allocated blocks to fill the hole are marked as
3102 * uninitialized to prevent parallel buffered read to expose
3103 * the stale data before DIO complete the data IO.
3105 * As to previously fallocated extents, ext4 get_block will
3106 * just simply mark the buffer mapped but still keep the
3107 * extents uninitialized.
3109 * For non AIO case, we will convert those unwritten extents
3110 * to written after return back from blockdev_direct_IO.
3112 * For async DIO, the conversion needs to be deferred when the
3113 * IO is completed. The ext4 end_io callback function will be
3114 * called to take care of the conversion work. Here for async
3115 * case, we allocate an io_end structure to hook to the iocb.
3117 iocb->private = NULL;
3118 ext4_inode_aio_set(inode, NULL);
3119 if (!is_sync_kiocb(iocb)) {
3120 io_end = ext4_init_io_end(inode, GFP_NOFS);
3126 * Grab reference for DIO. Will be dropped in ext4_end_io_dio()
3128 iocb->private = ext4_get_io_end(io_end);
3130 * we save the io structure for current async direct
3131 * IO, so that later ext4_map_blocks() could flag the
3132 * io structure whether there is a unwritten extents
3133 * needs to be converted when IO is completed.
3135 ext4_inode_aio_set(inode, io_end);
3139 get_block_func = ext4_get_block_write_nolock;
3141 get_block_func = ext4_get_block_write;
3142 dio_flags = DIO_LOCKING;
3144 ret = __blockdev_direct_IO(rw, iocb, inode,
3145 inode->i_sb->s_bdev, iov,
3153 * Put our reference to io_end. This can free the io_end structure e.g.
3154 * in sync IO case or in case of error. It can even perform extent
3155 * conversion if all bios we submitted finished before we got here.
3156 * Note that in that case iocb->private can be already set to NULL
3160 ext4_inode_aio_set(inode, NULL);
3161 ext4_put_io_end(io_end);
3163 * When no IO was submitted ext4_end_io_dio() was not
3164 * called so we have to put iocb's reference.
3166 if (ret <= 0 && ret != -EIOCBQUEUED && iocb->private) {
3167 WARN_ON(iocb->private != io_end);
3168 WARN_ON(io_end->flag & EXT4_IO_END_UNWRITTEN);
3169 ext4_put_io_end(io_end);
3170 iocb->private = NULL;
3173 if (ret > 0 && !overwrite && ext4_test_inode_state(inode,
3174 EXT4_STATE_DIO_UNWRITTEN)) {
3177 * for non AIO case, since the IO is already
3178 * completed, we could do the conversion right here
3180 err = ext4_convert_unwritten_extents(NULL, inode,
3184 ext4_clear_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN);
3189 inode_dio_done(inode);
3190 /* take i_mutex locking again if we do a ovewrite dio */
3192 up_read(&EXT4_I(inode)->i_data_sem);
3193 mutex_lock(&inode->i_mutex);
3199 static ssize_t ext4_direct_IO(int rw, struct kiocb *iocb,
3200 const struct iovec *iov, loff_t offset,
3201 unsigned long nr_segs)
3203 struct file *file = iocb->ki_filp;
3204 struct inode *inode = file->f_mapping->host;
3208 * If we are doing data journalling we don't support O_DIRECT
3210 if (ext4_should_journal_data(inode))
3213 /* Let buffer I/O handle the inline data case. */
3214 if (ext4_has_inline_data(inode))
3217 trace_ext4_direct_IO_enter(inode, offset, iov_length(iov, nr_segs), rw);
3218 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3219 ret = ext4_ext_direct_IO(rw, iocb, iov, offset, nr_segs);
3221 ret = ext4_ind_direct_IO(rw, iocb, iov, offset, nr_segs);
3222 trace_ext4_direct_IO_exit(inode, offset,
3223 iov_length(iov, nr_segs), rw, ret);
3228 * Pages can be marked dirty completely asynchronously from ext4's journalling
3229 * activity. By filemap_sync_pte(), try_to_unmap_one(), etc. We cannot do
3230 * much here because ->set_page_dirty is called under VFS locks. The page is
3231 * not necessarily locked.
3233 * We cannot just dirty the page and leave attached buffers clean, because the
3234 * buffers' dirty state is "definitive". We cannot just set the buffers dirty
3235 * or jbddirty because all the journalling code will explode.
3237 * So what we do is to mark the page "pending dirty" and next time writepage
3238 * is called, propagate that into the buffers appropriately.
3240 static int ext4_journalled_set_page_dirty(struct page *page)
3242 SetPageChecked(page);
3243 return __set_page_dirty_nobuffers(page);
3246 static const struct address_space_operations ext4_aops = {
3247 .readpage = ext4_readpage,
3248 .readpages = ext4_readpages,
3249 .writepage = ext4_writepage,
3250 .writepages = ext4_writepages,
3251 .write_begin = ext4_write_begin,
3252 .write_end = ext4_write_end,
3254 .invalidatepage = ext4_invalidatepage,
3255 .releasepage = ext4_releasepage,
3256 .direct_IO = ext4_direct_IO,
3257 .migratepage = buffer_migrate_page,
3258 .is_partially_uptodate = block_is_partially_uptodate,
3259 .error_remove_page = generic_error_remove_page,
3262 static const struct address_space_operations ext4_journalled_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_journalled_write_end,
3269 .set_page_dirty = ext4_journalled_set_page_dirty,
3271 .invalidatepage = ext4_journalled_invalidatepage,
3272 .releasepage = ext4_releasepage,
3273 .direct_IO = ext4_direct_IO,
3274 .is_partially_uptodate = block_is_partially_uptodate,
3275 .error_remove_page = generic_error_remove_page,
3278 static const struct address_space_operations ext4_da_aops = {
3279 .readpage = ext4_readpage,
3280 .readpages = ext4_readpages,
3281 .writepage = ext4_writepage,
3282 .writepages = ext4_writepages,
3283 .write_begin = ext4_da_write_begin,
3284 .write_end = ext4_da_write_end,
3286 .invalidatepage = ext4_da_invalidatepage,
3287 .releasepage = ext4_releasepage,
3288 .direct_IO = ext4_direct_IO,
3289 .migratepage = buffer_migrate_page,
3290 .is_partially_uptodate = block_is_partially_uptodate,
3291 .error_remove_page = generic_error_remove_page,
3294 void ext4_set_aops(struct inode *inode)
3296 switch (ext4_inode_journal_mode(inode)) {
3297 case EXT4_INODE_ORDERED_DATA_MODE:
3298 ext4_set_inode_state(inode, EXT4_STATE_ORDERED_MODE);
3300 case EXT4_INODE_WRITEBACK_DATA_MODE:
3301 ext4_clear_inode_state(inode, EXT4_STATE_ORDERED_MODE);
3303 case EXT4_INODE_JOURNAL_DATA_MODE:
3304 inode->i_mapping->a_ops = &ext4_journalled_aops;
3309 if (test_opt(inode->i_sb, DELALLOC))
3310 inode->i_mapping->a_ops = &ext4_da_aops;
3312 inode->i_mapping->a_ops = &ext4_aops;
3316 * ext4_block_truncate_page() zeroes out a mapping from file offset `from'
3317 * up to the end of the block which corresponds to `from'.
3318 * This required during truncate. We need to physically zero the tail end
3319 * of that block so it doesn't yield old data if the file is later grown.
3321 int ext4_block_truncate_page(handle_t *handle,
3322 struct address_space *mapping, loff_t from)
3324 unsigned offset = from & (PAGE_CACHE_SIZE-1);
3327 struct inode *inode = mapping->host;
3329 blocksize = inode->i_sb->s_blocksize;
3330 length = blocksize - (offset & (blocksize - 1));
3332 return ext4_block_zero_page_range(handle, mapping, from, length);
3336 * ext4_block_zero_page_range() zeros out a mapping of length 'length'
3337 * starting from file offset 'from'. The range to be zero'd must
3338 * be contained with in one block. If the specified range exceeds
3339 * the end of the block it will be shortened to end of the block
3340 * that cooresponds to 'from'
3342 int ext4_block_zero_page_range(handle_t *handle,
3343 struct address_space *mapping, loff_t from, loff_t length)
3345 ext4_fsblk_t index = from >> PAGE_CACHE_SHIFT;
3346 unsigned offset = from & (PAGE_CACHE_SIZE-1);
3347 unsigned blocksize, max, pos;
3349 struct inode *inode = mapping->host;
3350 struct buffer_head *bh;
3354 page = find_or_create_page(mapping, from >> PAGE_CACHE_SHIFT,
3355 mapping_gfp_mask(mapping) & ~__GFP_FS);
3359 blocksize = inode->i_sb->s_blocksize;
3360 max = blocksize - (offset & (blocksize - 1));
3363 * correct length if it does not fall between
3364 * 'from' and the end of the block
3366 if (length > max || length < 0)
3369 iblock = index << (PAGE_CACHE_SHIFT - inode->i_sb->s_blocksize_bits);
3371 if (!page_has_buffers(page))
3372 create_empty_buffers(page, blocksize, 0);
3374 /* Find the buffer that contains "offset" */
3375 bh = page_buffers(page);
3377 while (offset >= pos) {
3378 bh = bh->b_this_page;
3382 if (buffer_freed(bh)) {
3383 BUFFER_TRACE(bh, "freed: skip");
3386 if (!buffer_mapped(bh)) {
3387 BUFFER_TRACE(bh, "unmapped");
3388 ext4_get_block(inode, iblock, bh, 0);
3389 /* unmapped? It's a hole - nothing to do */
3390 if (!buffer_mapped(bh)) {
3391 BUFFER_TRACE(bh, "still unmapped");
3396 /* Ok, it's mapped. Make sure it's up-to-date */
3397 if (PageUptodate(page))
3398 set_buffer_uptodate(bh);
3400 if (!buffer_uptodate(bh)) {
3402 ll_rw_block(READ, 1, &bh);
3404 /* Uhhuh. Read error. Complain and punt. */
3405 if (!buffer_uptodate(bh))
3408 if (ext4_should_journal_data(inode)) {
3409 BUFFER_TRACE(bh, "get write access");
3410 err = ext4_journal_get_write_access(handle, bh);
3414 zero_user(page, offset, length);
3415 BUFFER_TRACE(bh, "zeroed end of block");
3417 if (ext4_should_journal_data(inode)) {
3418 err = ext4_handle_dirty_metadata(handle, inode, bh);
3421 mark_buffer_dirty(bh);
3422 if (ext4_test_inode_state(inode, EXT4_STATE_ORDERED_MODE))
3423 err = ext4_jbd2_file_inode(handle, inode);
3428 page_cache_release(page);
3432 int ext4_zero_partial_blocks(handle_t *handle, struct inode *inode,
3433 loff_t lstart, loff_t length)
3435 struct super_block *sb = inode->i_sb;
3436 struct address_space *mapping = inode->i_mapping;
3437 unsigned partial_start, partial_end;
3438 ext4_fsblk_t start, end;
3439 loff_t byte_end = (lstart + length - 1);
3442 partial_start = lstart & (sb->s_blocksize - 1);
3443 partial_end = byte_end & (sb->s_blocksize - 1);
3445 start = lstart >> sb->s_blocksize_bits;
3446 end = byte_end >> sb->s_blocksize_bits;
3448 /* Handle partial zero within the single block */
3450 (partial_start || (partial_end != sb->s_blocksize - 1))) {
3451 err = ext4_block_zero_page_range(handle, mapping,
3455 /* Handle partial zero out on the start of the range */
3456 if (partial_start) {
3457 err = ext4_block_zero_page_range(handle, mapping,
3458 lstart, sb->s_blocksize);
3462 /* Handle partial zero out on the end of the range */
3463 if (partial_end != sb->s_blocksize - 1)
3464 err = ext4_block_zero_page_range(handle, mapping,
3465 byte_end - partial_end,
3470 int ext4_can_truncate(struct inode *inode)
3472 if (S_ISREG(inode->i_mode))
3474 if (S_ISDIR(inode->i_mode))
3476 if (S_ISLNK(inode->i_mode))
3477 return !ext4_inode_is_fast_symlink(inode);
3482 * ext4_punch_hole: punches a hole in a file by releaseing the blocks
3483 * associated with the given offset and length
3485 * @inode: File inode
3486 * @offset: The offset where the hole will begin
3487 * @len: The length of the hole
3489 * Returns: 0 on success or negative on failure
3492 int ext4_punch_hole(struct inode *inode, loff_t offset, loff_t length)
3494 struct super_block *sb = inode->i_sb;
3495 ext4_lblk_t first_block, stop_block;
3496 struct address_space *mapping = inode->i_mapping;
3497 loff_t first_block_offset, last_block_offset;
3499 unsigned int credits;
3502 if (!S_ISREG(inode->i_mode))
3505 trace_ext4_punch_hole(inode, offset, length);
3508 * Write out all dirty pages to avoid race conditions
3509 * Then release them.
3511 if (mapping->nrpages && mapping_tagged(mapping, PAGECACHE_TAG_DIRTY)) {
3512 ret = filemap_write_and_wait_range(mapping, offset,
3513 offset + length - 1);
3518 mutex_lock(&inode->i_mutex);
3519 /* It's not possible punch hole on append only file */
3520 if (IS_APPEND(inode) || IS_IMMUTABLE(inode)) {
3524 if (IS_SWAPFILE(inode)) {
3529 /* No need to punch hole beyond i_size */
3530 if (offset >= inode->i_size)
3534 * If the hole extends beyond i_size, set the hole
3535 * to end after the page that contains i_size
3537 if (offset + length > inode->i_size) {
3538 length = inode->i_size +
3539 PAGE_CACHE_SIZE - (inode->i_size & (PAGE_CACHE_SIZE - 1)) -
3543 if (offset & (sb->s_blocksize - 1) ||
3544 (offset + length) & (sb->s_blocksize - 1)) {
3546 * Attach jinode to inode for jbd2 if we do any zeroing of
3549 ret = ext4_inode_attach_jinode(inode);
3555 first_block_offset = round_up(offset, sb->s_blocksize);
3556 last_block_offset = round_down((offset + length), sb->s_blocksize) - 1;
3558 /* Now release the pages and zero block aligned part of pages*/
3559 if (last_block_offset > first_block_offset)
3560 truncate_pagecache_range(inode, first_block_offset,
3563 /* Wait all existing dio workers, newcomers will block on i_mutex */
3564 ext4_inode_block_unlocked_dio(inode);
3565 inode_dio_wait(inode);
3567 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3568 credits = ext4_writepage_trans_blocks(inode);
3570 credits = ext4_blocks_for_truncate(inode);
3571 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
3572 if (IS_ERR(handle)) {
3573 ret = PTR_ERR(handle);
3574 ext4_std_error(sb, ret);
3578 ret = ext4_zero_partial_blocks(handle, inode, offset,
3583 first_block = (offset + sb->s_blocksize - 1) >>
3584 EXT4_BLOCK_SIZE_BITS(sb);
3585 stop_block = (offset + length) >> EXT4_BLOCK_SIZE_BITS(sb);
3587 /* If there are no blocks to remove, return now */
3588 if (first_block >= stop_block)
3591 down_write(&EXT4_I(inode)->i_data_sem);
3592 ext4_discard_preallocations(inode);
3594 ret = ext4_es_remove_extent(inode, first_block,
3595 stop_block - first_block);
3597 up_write(&EXT4_I(inode)->i_data_sem);
3601 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3602 ret = ext4_ext_remove_space(inode, first_block,
3605 ret = ext4_free_hole_blocks(handle, inode, first_block,
3608 ext4_discard_preallocations(inode);
3609 up_write(&EXT4_I(inode)->i_data_sem);
3611 ext4_handle_sync(handle);
3612 inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
3613 ext4_mark_inode_dirty(handle, inode);
3615 ext4_journal_stop(handle);
3617 ext4_inode_resume_unlocked_dio(inode);
3619 mutex_unlock(&inode->i_mutex);
3623 int ext4_inode_attach_jinode(struct inode *inode)
3625 struct ext4_inode_info *ei = EXT4_I(inode);
3626 struct jbd2_inode *jinode;
3628 if (ei->jinode || !EXT4_SB(inode->i_sb)->s_journal)
3631 jinode = jbd2_alloc_inode(GFP_KERNEL);
3632 spin_lock(&inode->i_lock);
3635 spin_unlock(&inode->i_lock);
3638 ei->jinode = jinode;
3639 jbd2_journal_init_jbd_inode(ei->jinode, inode);
3642 spin_unlock(&inode->i_lock);
3643 if (unlikely(jinode != NULL))
3644 jbd2_free_inode(jinode);
3651 * We block out ext4_get_block() block instantiations across the entire
3652 * transaction, and VFS/VM ensures that ext4_truncate() cannot run
3653 * simultaneously on behalf of the same inode.
3655 * As we work through the truncate and commit bits of it to the journal there
3656 * is one core, guiding principle: the file's tree must always be consistent on
3657 * disk. We must be able to restart the truncate after a crash.
3659 * The file's tree may be transiently inconsistent in memory (although it
3660 * probably isn't), but whenever we close off and commit a journal transaction,
3661 * the contents of (the filesystem + the journal) must be consistent and
3662 * restartable. It's pretty simple, really: bottom up, right to left (although
3663 * left-to-right works OK too).
3665 * Note that at recovery time, journal replay occurs *before* the restart of
3666 * truncate against the orphan inode list.
3668 * The committed inode has the new, desired i_size (which is the same as
3669 * i_disksize in this case). After a crash, ext4_orphan_cleanup() will see
3670 * that this inode's truncate did not complete and it will again call
3671 * ext4_truncate() to have another go. So there will be instantiated blocks
3672 * to the right of the truncation point in a crashed ext4 filesystem. But
3673 * that's fine - as long as they are linked from the inode, the post-crash
3674 * ext4_truncate() run will find them and release them.
3676 void ext4_truncate(struct inode *inode)
3678 struct ext4_inode_info *ei = EXT4_I(inode);
3679 unsigned int credits;
3681 struct address_space *mapping = inode->i_mapping;
3684 * There is a possibility that we're either freeing the inode
3685 * or it completely new indode. In those cases we might not
3686 * have i_mutex locked because it's not necessary.
3688 if (!(inode->i_state & (I_NEW|I_FREEING)))
3689 WARN_ON(!mutex_is_locked(&inode->i_mutex));
3690 trace_ext4_truncate_enter(inode);
3692 if (!ext4_can_truncate(inode))
3695 ext4_clear_inode_flag(inode, EXT4_INODE_EOFBLOCKS);
3697 if (inode->i_size == 0 && !test_opt(inode->i_sb, NO_AUTO_DA_ALLOC))
3698 ext4_set_inode_state(inode, EXT4_STATE_DA_ALLOC_CLOSE);
3700 if (ext4_has_inline_data(inode)) {
3703 ext4_inline_data_truncate(inode, &has_inline);
3708 /* If we zero-out tail of the page, we have to create jinode for jbd2 */
3709 if (inode->i_size & (inode->i_sb->s_blocksize - 1)) {
3710 if (ext4_inode_attach_jinode(inode) < 0)
3714 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3715 credits = ext4_writepage_trans_blocks(inode);
3717 credits = ext4_blocks_for_truncate(inode);
3719 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
3720 if (IS_ERR(handle)) {
3721 ext4_std_error(inode->i_sb, PTR_ERR(handle));
3725 if (inode->i_size & (inode->i_sb->s_blocksize - 1))
3726 ext4_block_truncate_page(handle, mapping, inode->i_size);
3729 * We add the inode to the orphan list, so that if this
3730 * truncate spans multiple transactions, and we crash, we will
3731 * resume the truncate when the filesystem recovers. It also
3732 * marks the inode dirty, to catch the new size.
3734 * Implication: the file must always be in a sane, consistent
3735 * truncatable state while each transaction commits.
3737 if (ext4_orphan_add(handle, inode))
3740 down_write(&EXT4_I(inode)->i_data_sem);
3742 ext4_discard_preallocations(inode);
3744 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3745 ext4_ext_truncate(handle, inode);
3747 ext4_ind_truncate(handle, inode);
3749 up_write(&ei->i_data_sem);
3752 ext4_handle_sync(handle);
3756 * If this was a simple ftruncate() and the file will remain alive,
3757 * then we need to clear up the orphan record which we created above.
3758 * However, if this was a real unlink then we were called by
3759 * ext4_delete_inode(), and we allow that function to clean up the
3760 * orphan info for us.
3763 ext4_orphan_del(handle, inode);
3765 inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
3766 ext4_mark_inode_dirty(handle, inode);
3767 ext4_journal_stop(handle);
3769 trace_ext4_truncate_exit(inode);
3773 * ext4_get_inode_loc returns with an extra refcount against the inode's
3774 * underlying buffer_head on success. If 'in_mem' is true, we have all
3775 * data in memory that is needed to recreate the on-disk version of this
3778 static int __ext4_get_inode_loc(struct inode *inode,
3779 struct ext4_iloc *iloc, int in_mem)
3781 struct ext4_group_desc *gdp;
3782 struct buffer_head *bh;
3783 struct super_block *sb = inode->i_sb;
3785 int inodes_per_block, inode_offset;
3788 if (!ext4_valid_inum(sb, inode->i_ino))
3791 iloc->block_group = (inode->i_ino - 1) / EXT4_INODES_PER_GROUP(sb);
3792 gdp = ext4_get_group_desc(sb, iloc->block_group, NULL);
3797 * Figure out the offset within the block group inode table
3799 inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
3800 inode_offset = ((inode->i_ino - 1) %
3801 EXT4_INODES_PER_GROUP(sb));
3802 block = ext4_inode_table(sb, gdp) + (inode_offset / inodes_per_block);
3803 iloc->offset = (inode_offset % inodes_per_block) * EXT4_INODE_SIZE(sb);
3805 bh = sb_getblk(sb, block);
3808 if (!buffer_uptodate(bh)) {
3812 * If the buffer has the write error flag, we have failed
3813 * to write out another inode in the same block. In this
3814 * case, we don't have to read the block because we may
3815 * read the old inode data successfully.
3817 if (buffer_write_io_error(bh) && !buffer_uptodate(bh))
3818 set_buffer_uptodate(bh);
3820 if (buffer_uptodate(bh)) {
3821 /* someone brought it uptodate while we waited */
3827 * If we have all information of the inode in memory and this
3828 * is the only valid inode in the block, we need not read the
3832 struct buffer_head *bitmap_bh;
3835 start = inode_offset & ~(inodes_per_block - 1);
3837 /* Is the inode bitmap in cache? */
3838 bitmap_bh = sb_getblk(sb, ext4_inode_bitmap(sb, gdp));
3839 if (unlikely(!bitmap_bh))
3843 * If the inode bitmap isn't in cache then the
3844 * optimisation may end up performing two reads instead
3845 * of one, so skip it.
3847 if (!buffer_uptodate(bitmap_bh)) {
3851 for (i = start; i < start + inodes_per_block; i++) {
3852 if (i == inode_offset)
3854 if (ext4_test_bit(i, bitmap_bh->b_data))
3858 if (i == start + inodes_per_block) {
3859 /* all other inodes are free, so skip I/O */
3860 memset(bh->b_data, 0, bh->b_size);
3861 set_buffer_uptodate(bh);
3869 * If we need to do any I/O, try to pre-readahead extra
3870 * blocks from the inode table.
3872 if (EXT4_SB(sb)->s_inode_readahead_blks) {
3873 ext4_fsblk_t b, end, table;
3875 __u32 ra_blks = EXT4_SB(sb)->s_inode_readahead_blks;
3877 table = ext4_inode_table(sb, gdp);
3878 /* s_inode_readahead_blks is always a power of 2 */
3879 b = block & ~((ext4_fsblk_t) ra_blks - 1);
3883 num = EXT4_INODES_PER_GROUP(sb);
3884 if (ext4_has_group_desc_csum(sb))
3885 num -= ext4_itable_unused_count(sb, gdp);
3886 table += num / inodes_per_block;
3890 sb_breadahead(sb, b++);
3894 * There are other valid inodes in the buffer, this inode
3895 * has in-inode xattrs, or we don't have this inode in memory.
3896 * Read the block from disk.
3898 trace_ext4_load_inode(inode);
3900 bh->b_end_io = end_buffer_read_sync;
3901 submit_bh(READ | REQ_META | REQ_PRIO, bh);
3903 if (!buffer_uptodate(bh)) {
3904 EXT4_ERROR_INODE_BLOCK(inode, block,
3905 "unable to read itable block");
3915 int ext4_get_inode_loc(struct inode *inode, struct ext4_iloc *iloc)
3917 /* We have all inode data except xattrs in memory here. */
3918 return __ext4_get_inode_loc(inode, iloc,
3919 !ext4_test_inode_state(inode, EXT4_STATE_XATTR));
3922 void ext4_set_inode_flags(struct inode *inode)
3924 unsigned int flags = EXT4_I(inode)->i_flags;
3925 unsigned int new_fl = 0;
3927 if (flags & EXT4_SYNC_FL)
3929 if (flags & EXT4_APPEND_FL)
3931 if (flags & EXT4_IMMUTABLE_FL)
3932 new_fl |= S_IMMUTABLE;
3933 if (flags & EXT4_NOATIME_FL)
3934 new_fl |= S_NOATIME;
3935 if (flags & EXT4_DIRSYNC_FL)
3936 new_fl |= S_DIRSYNC;
3937 set_mask_bits(&inode->i_flags,
3938 S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME|S_DIRSYNC, new_fl);
3941 /* Propagate flags from i_flags to EXT4_I(inode)->i_flags */
3942 void ext4_get_inode_flags(struct ext4_inode_info *ei)
3944 unsigned int vfs_fl;
3945 unsigned long old_fl, new_fl;
3948 vfs_fl = ei->vfs_inode.i_flags;
3949 old_fl = ei->i_flags;
3950 new_fl = old_fl & ~(EXT4_SYNC_FL|EXT4_APPEND_FL|
3951 EXT4_IMMUTABLE_FL|EXT4_NOATIME_FL|
3953 if (vfs_fl & S_SYNC)
3954 new_fl |= EXT4_SYNC_FL;
3955 if (vfs_fl & S_APPEND)
3956 new_fl |= EXT4_APPEND_FL;
3957 if (vfs_fl & S_IMMUTABLE)
3958 new_fl |= EXT4_IMMUTABLE_FL;
3959 if (vfs_fl & S_NOATIME)
3960 new_fl |= EXT4_NOATIME_FL;
3961 if (vfs_fl & S_DIRSYNC)
3962 new_fl |= EXT4_DIRSYNC_FL;
3963 } while (cmpxchg(&ei->i_flags, old_fl, new_fl) != old_fl);
3966 static blkcnt_t ext4_inode_blocks(struct ext4_inode *raw_inode,
3967 struct ext4_inode_info *ei)
3970 struct inode *inode = &(ei->vfs_inode);
3971 struct super_block *sb = inode->i_sb;
3973 if (EXT4_HAS_RO_COMPAT_FEATURE(sb,
3974 EXT4_FEATURE_RO_COMPAT_HUGE_FILE)) {
3975 /* we are using combined 48 bit field */
3976 i_blocks = ((u64)le16_to_cpu(raw_inode->i_blocks_high)) << 32 |
3977 le32_to_cpu(raw_inode->i_blocks_lo);
3978 if (ext4_test_inode_flag(inode, EXT4_INODE_HUGE_FILE)) {
3979 /* i_blocks represent file system block size */
3980 return i_blocks << (inode->i_blkbits - 9);
3985 return le32_to_cpu(raw_inode->i_blocks_lo);
3989 static inline void ext4_iget_extra_inode(struct inode *inode,
3990 struct ext4_inode *raw_inode,
3991 struct ext4_inode_info *ei)
3993 __le32 *magic = (void *)raw_inode +
3994 EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize;
3995 if (*magic == cpu_to_le32(EXT4_XATTR_MAGIC)) {
3996 ext4_set_inode_state(inode, EXT4_STATE_XATTR);
3997 ext4_find_inline_data_nolock(inode);
3999 EXT4_I(inode)->i_inline_off = 0;
4002 struct inode *ext4_iget(struct super_block *sb, unsigned long ino)
4004 struct ext4_iloc iloc;
4005 struct ext4_inode *raw_inode;
4006 struct ext4_inode_info *ei;
4007 struct inode *inode;
4008 journal_t *journal = EXT4_SB(sb)->s_journal;
4014 inode = iget_locked(sb, ino);
4016 return ERR_PTR(-ENOMEM);
4017 if (!(inode->i_state & I_NEW))
4023 ret = __ext4_get_inode_loc(inode, &iloc, 0);
4026 raw_inode = ext4_raw_inode(&iloc);
4028 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4029 ei->i_extra_isize = le16_to_cpu(raw_inode->i_extra_isize);
4030 if (EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize >
4031 EXT4_INODE_SIZE(inode->i_sb)) {
4032 EXT4_ERROR_INODE(inode, "bad extra_isize (%u != %u)",
4033 EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize,
4034 EXT4_INODE_SIZE(inode->i_sb));
4039 ei->i_extra_isize = 0;
4041 /* Precompute checksum seed for inode metadata */
4042 if (EXT4_HAS_RO_COMPAT_FEATURE(sb,
4043 EXT4_FEATURE_RO_COMPAT_METADATA_CSUM)) {
4044 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4046 __le32 inum = cpu_to_le32(inode->i_ino);
4047 __le32 gen = raw_inode->i_generation;
4048 csum = ext4_chksum(sbi, sbi->s_csum_seed, (__u8 *)&inum,
4050 ei->i_csum_seed = ext4_chksum(sbi, csum, (__u8 *)&gen,
4054 if (!ext4_inode_csum_verify(inode, raw_inode, ei)) {
4055 EXT4_ERROR_INODE(inode, "checksum invalid");
4060 inode->i_mode = le16_to_cpu(raw_inode->i_mode);
4061 i_uid = (uid_t)le16_to_cpu(raw_inode->i_uid_low);
4062 i_gid = (gid_t)le16_to_cpu(raw_inode->i_gid_low);
4063 if (!(test_opt(inode->i_sb, NO_UID32))) {
4064 i_uid |= le16_to_cpu(raw_inode->i_uid_high) << 16;
4065 i_gid |= le16_to_cpu(raw_inode->i_gid_high) << 16;
4067 i_uid_write(inode, i_uid);
4068 i_gid_write(inode, i_gid);
4069 set_nlink(inode, le16_to_cpu(raw_inode->i_links_count));
4071 ext4_clear_state_flags(ei); /* Only relevant on 32-bit archs */
4072 ei->i_inline_off = 0;
4073 ei->i_dir_start_lookup = 0;
4074 ei->i_dtime = le32_to_cpu(raw_inode->i_dtime);
4075 /* We now have enough fields to check if the inode was active or not.
4076 * This is needed because nfsd might try to access dead inodes
4077 * the test is that same one that e2fsck uses
4078 * NeilBrown 1999oct15
4080 if (inode->i_nlink == 0) {
4081 if ((inode->i_mode == 0 ||
4082 !(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_ORPHAN_FS)) &&
4083 ino != EXT4_BOOT_LOADER_INO) {
4084 /* this inode is deleted */
4088 /* The only unlinked inodes we let through here have
4089 * valid i_mode and are being read by the orphan
4090 * recovery code: that's fine, we're about to complete
4091 * the process of deleting those.
4092 * OR it is the EXT4_BOOT_LOADER_INO which is
4093 * not initialized on a new filesystem. */
4095 ei->i_flags = le32_to_cpu(raw_inode->i_flags);
4096 inode->i_blocks = ext4_inode_blocks(raw_inode, ei);
4097 ei->i_file_acl = le32_to_cpu(raw_inode->i_file_acl_lo);
4098 if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_64BIT))
4100 ((__u64)le16_to_cpu(raw_inode->i_file_acl_high)) << 32;
4101 inode->i_size = ext4_isize(raw_inode);
4102 ei->i_disksize = inode->i_size;
4104 ei->i_reserved_quota = 0;
4106 inode->i_generation = le32_to_cpu(raw_inode->i_generation);
4107 ei->i_block_group = iloc.block_group;
4108 ei->i_last_alloc_group = ~0;
4110 * NOTE! The in-memory inode i_data array is in little-endian order
4111 * even on big-endian machines: we do NOT byteswap the block numbers!
4113 for (block = 0; block < EXT4_N_BLOCKS; block++)
4114 ei->i_data[block] = raw_inode->i_block[block];
4115 INIT_LIST_HEAD(&ei->i_orphan);
4118 * Set transaction id's of transactions that have to be committed
4119 * to finish f[data]sync. We set them to currently running transaction
4120 * as we cannot be sure that the inode or some of its metadata isn't
4121 * part of the transaction - the inode could have been reclaimed and
4122 * now it is reread from disk.
4125 transaction_t *transaction;
4128 read_lock(&journal->j_state_lock);
4129 if (journal->j_running_transaction)
4130 transaction = journal->j_running_transaction;
4132 transaction = journal->j_committing_transaction;
4134 tid = transaction->t_tid;
4136 tid = journal->j_commit_sequence;
4137 read_unlock(&journal->j_state_lock);
4138 ei->i_sync_tid = tid;
4139 ei->i_datasync_tid = tid;
4142 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4143 if (ei->i_extra_isize == 0) {
4144 /* The extra space is currently unused. Use it. */
4145 ei->i_extra_isize = sizeof(struct ext4_inode) -
4146 EXT4_GOOD_OLD_INODE_SIZE;
4148 ext4_iget_extra_inode(inode, raw_inode, ei);
4152 EXT4_INODE_GET_XTIME(i_ctime, inode, raw_inode);
4153 EXT4_INODE_GET_XTIME(i_mtime, inode, raw_inode);
4154 EXT4_INODE_GET_XTIME(i_atime, inode, raw_inode);
4155 EXT4_EINODE_GET_XTIME(i_crtime, ei, raw_inode);
4157 inode->i_version = le32_to_cpu(raw_inode->i_disk_version);
4158 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4159 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
4161 (__u64)(le32_to_cpu(raw_inode->i_version_hi)) << 32;
4165 if (ei->i_file_acl &&
4166 !ext4_data_block_valid(EXT4_SB(sb), ei->i_file_acl, 1)) {
4167 EXT4_ERROR_INODE(inode, "bad extended attribute block %llu",
4171 } else if (!ext4_has_inline_data(inode)) {
4172 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
4173 if ((S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
4174 (S_ISLNK(inode->i_mode) &&
4175 !ext4_inode_is_fast_symlink(inode))))
4176 /* Validate extent which is part of inode */
4177 ret = ext4_ext_check_inode(inode);
4178 } else if (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
4179 (S_ISLNK(inode->i_mode) &&
4180 !ext4_inode_is_fast_symlink(inode))) {
4181 /* Validate block references which are part of inode */
4182 ret = ext4_ind_check_inode(inode);
4188 if (S_ISREG(inode->i_mode)) {
4189 inode->i_op = &ext4_file_inode_operations;
4190 inode->i_fop = &ext4_file_operations;
4191 ext4_set_aops(inode);
4192 } else if (S_ISDIR(inode->i_mode)) {
4193 inode->i_op = &ext4_dir_inode_operations;
4194 inode->i_fop = &ext4_dir_operations;
4195 } else if (S_ISLNK(inode->i_mode)) {
4196 if (ext4_inode_is_fast_symlink(inode)) {
4197 inode->i_op = &ext4_fast_symlink_inode_operations;
4198 nd_terminate_link(ei->i_data, inode->i_size,
4199 sizeof(ei->i_data) - 1);
4201 inode->i_op = &ext4_symlink_inode_operations;
4202 ext4_set_aops(inode);
4204 } else if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode) ||
4205 S_ISFIFO(inode->i_mode) || S_ISSOCK(inode->i_mode)) {
4206 inode->i_op = &ext4_special_inode_operations;
4207 if (raw_inode->i_block[0])
4208 init_special_inode(inode, inode->i_mode,
4209 old_decode_dev(le32_to_cpu(raw_inode->i_block[0])));
4211 init_special_inode(inode, inode->i_mode,
4212 new_decode_dev(le32_to_cpu(raw_inode->i_block[1])));
4213 } else if (ino == EXT4_BOOT_LOADER_INO) {
4214 make_bad_inode(inode);
4217 EXT4_ERROR_INODE(inode, "bogus i_mode (%o)", inode->i_mode);
4221 ext4_set_inode_flags(inode);
4222 unlock_new_inode(inode);
4228 return ERR_PTR(ret);
4231 static int ext4_inode_blocks_set(handle_t *handle,
4232 struct ext4_inode *raw_inode,
4233 struct ext4_inode_info *ei)
4235 struct inode *inode = &(ei->vfs_inode);
4236 u64 i_blocks = inode->i_blocks;
4237 struct super_block *sb = inode->i_sb;
4239 if (i_blocks <= ~0U) {
4241 * i_blocks can be represented in a 32 bit variable
4242 * as multiple of 512 bytes
4244 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
4245 raw_inode->i_blocks_high = 0;
4246 ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
4249 if (!EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_HUGE_FILE))
4252 if (i_blocks <= 0xffffffffffffULL) {
4254 * i_blocks can be represented in a 48 bit variable
4255 * as multiple of 512 bytes
4257 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
4258 raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
4259 ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
4261 ext4_set_inode_flag(inode, EXT4_INODE_HUGE_FILE);
4262 /* i_block is stored in file system block size */
4263 i_blocks = i_blocks >> (inode->i_blkbits - 9);
4264 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
4265 raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
4271 * Post the struct inode info into an on-disk inode location in the
4272 * buffer-cache. This gobbles the caller's reference to the
4273 * buffer_head in the inode location struct.
4275 * The caller must have write access to iloc->bh.
4277 static int ext4_do_update_inode(handle_t *handle,
4278 struct inode *inode,
4279 struct ext4_iloc *iloc)
4281 struct ext4_inode *raw_inode = ext4_raw_inode(iloc);
4282 struct ext4_inode_info *ei = EXT4_I(inode);
4283 struct buffer_head *bh = iloc->bh;
4284 int err = 0, rc, block;
4285 int need_datasync = 0;
4289 /* For fields not not tracking in the in-memory inode,
4290 * initialise them to zero for new inodes. */
4291 if (ext4_test_inode_state(inode, EXT4_STATE_NEW))
4292 memset(raw_inode, 0, EXT4_SB(inode->i_sb)->s_inode_size);
4294 ext4_get_inode_flags(ei);
4295 raw_inode->i_mode = cpu_to_le16(inode->i_mode);
4296 i_uid = i_uid_read(inode);
4297 i_gid = i_gid_read(inode);
4298 if (!(test_opt(inode->i_sb, NO_UID32))) {
4299 raw_inode->i_uid_low = cpu_to_le16(low_16_bits(i_uid));
4300 raw_inode->i_gid_low = cpu_to_le16(low_16_bits(i_gid));
4302 * Fix up interoperability with old kernels. Otherwise, old inodes get
4303 * re-used with the upper 16 bits of the uid/gid intact
4306 raw_inode->i_uid_high =
4307 cpu_to_le16(high_16_bits(i_uid));
4308 raw_inode->i_gid_high =
4309 cpu_to_le16(high_16_bits(i_gid));
4311 raw_inode->i_uid_high = 0;
4312 raw_inode->i_gid_high = 0;
4315 raw_inode->i_uid_low = cpu_to_le16(fs_high2lowuid(i_uid));
4316 raw_inode->i_gid_low = cpu_to_le16(fs_high2lowgid(i_gid));
4317 raw_inode->i_uid_high = 0;
4318 raw_inode->i_gid_high = 0;
4320 raw_inode->i_links_count = cpu_to_le16(inode->i_nlink);
4322 EXT4_INODE_SET_XTIME(i_ctime, inode, raw_inode);
4323 EXT4_INODE_SET_XTIME(i_mtime, inode, raw_inode);
4324 EXT4_INODE_SET_XTIME(i_atime, inode, raw_inode);
4325 EXT4_EINODE_SET_XTIME(i_crtime, ei, raw_inode);
4327 if (ext4_inode_blocks_set(handle, raw_inode, ei))
4329 raw_inode->i_dtime = cpu_to_le32(ei->i_dtime);
4330 raw_inode->i_flags = cpu_to_le32(ei->i_flags & 0xFFFFFFFF);
4331 if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
4332 cpu_to_le32(EXT4_OS_HURD))
4333 raw_inode->i_file_acl_high =
4334 cpu_to_le16(ei->i_file_acl >> 32);
4335 raw_inode->i_file_acl_lo = cpu_to_le32(ei->i_file_acl);
4336 if (ei->i_disksize != ext4_isize(raw_inode)) {
4337 ext4_isize_set(raw_inode, ei->i_disksize);
4340 if (ei->i_disksize > 0x7fffffffULL) {
4341 struct super_block *sb = inode->i_sb;
4342 if (!EXT4_HAS_RO_COMPAT_FEATURE(sb,
4343 EXT4_FEATURE_RO_COMPAT_LARGE_FILE) ||
4344 EXT4_SB(sb)->s_es->s_rev_level ==
4345 cpu_to_le32(EXT4_GOOD_OLD_REV)) {
4346 /* If this is the first large file
4347 * created, add a flag to the superblock.
4349 err = ext4_journal_get_write_access(handle,
4350 EXT4_SB(sb)->s_sbh);
4353 ext4_update_dynamic_rev(sb);
4354 EXT4_SET_RO_COMPAT_FEATURE(sb,
4355 EXT4_FEATURE_RO_COMPAT_LARGE_FILE);
4356 ext4_handle_sync(handle);
4357 err = ext4_handle_dirty_super(handle, sb);
4360 raw_inode->i_generation = cpu_to_le32(inode->i_generation);
4361 if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) {
4362 if (old_valid_dev(inode->i_rdev)) {
4363 raw_inode->i_block[0] =
4364 cpu_to_le32(old_encode_dev(inode->i_rdev));
4365 raw_inode->i_block[1] = 0;
4367 raw_inode->i_block[0] = 0;
4368 raw_inode->i_block[1] =
4369 cpu_to_le32(new_encode_dev(inode->i_rdev));
4370 raw_inode->i_block[2] = 0;
4372 } else if (!ext4_has_inline_data(inode)) {
4373 for (block = 0; block < EXT4_N_BLOCKS; block++)
4374 raw_inode->i_block[block] = ei->i_data[block];
4377 raw_inode->i_disk_version = cpu_to_le32(inode->i_version);
4378 if (ei->i_extra_isize) {
4379 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
4380 raw_inode->i_version_hi =
4381 cpu_to_le32(inode->i_version >> 32);
4382 raw_inode->i_extra_isize = cpu_to_le16(ei->i_extra_isize);
4385 ext4_inode_csum_set(inode, raw_inode, ei);
4387 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
4388 rc = ext4_handle_dirty_metadata(handle, NULL, bh);
4391 ext4_clear_inode_state(inode, EXT4_STATE_NEW);
4393 ext4_update_inode_fsync_trans(handle, inode, need_datasync);
4396 ext4_std_error(inode->i_sb, err);
4401 * ext4_write_inode()
4403 * We are called from a few places:
4405 * - Within generic_file_write() for O_SYNC files.
4406 * Here, there will be no transaction running. We wait for any running
4407 * transaction to commit.
4409 * - Within sys_sync(), kupdate and such.
4410 * We wait on commit, if tol to.
4412 * - Within prune_icache() (PF_MEMALLOC == true)
4413 * Here we simply return. We can't afford to block kswapd on the
4416 * In all cases it is actually safe for us to return without doing anything,
4417 * because the inode has been copied into a raw inode buffer in
4418 * ext4_mark_inode_dirty(). This is a correctness thing for O_SYNC and for
4421 * Note that we are absolutely dependent upon all inode dirtiers doing the
4422 * right thing: they *must* call mark_inode_dirty() after dirtying info in
4423 * which we are interested.
4425 * It would be a bug for them to not do this. The code:
4427 * mark_inode_dirty(inode)
4429 * inode->i_size = expr;
4431 * is in error because a kswapd-driven write_inode() could occur while
4432 * `stuff()' is running, and the new i_size will be lost. Plus the inode
4433 * will no longer be on the superblock's dirty inode list.
4435 int ext4_write_inode(struct inode *inode, struct writeback_control *wbc)
4439 if (current->flags & PF_MEMALLOC)
4442 if (EXT4_SB(inode->i_sb)->s_journal) {
4443 if (ext4_journal_current_handle()) {
4444 jbd_debug(1, "called recursively, non-PF_MEMALLOC!\n");
4449 if (wbc->sync_mode != WB_SYNC_ALL)
4452 err = ext4_force_commit(inode->i_sb);
4454 struct ext4_iloc iloc;
4456 err = __ext4_get_inode_loc(inode, &iloc, 0);
4459 if (wbc->sync_mode == WB_SYNC_ALL)
4460 sync_dirty_buffer(iloc.bh);
4461 if (buffer_req(iloc.bh) && !buffer_uptodate(iloc.bh)) {
4462 EXT4_ERROR_INODE_BLOCK(inode, iloc.bh->b_blocknr,
4463 "IO error syncing inode");
4472 * In data=journal mode ext4_journalled_invalidatepage() may fail to invalidate
4473 * buffers that are attached to a page stradding i_size and are undergoing
4474 * commit. In that case we have to wait for commit to finish and try again.
4476 static void ext4_wait_for_tail_page_commit(struct inode *inode)
4480 journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
4481 tid_t commit_tid = 0;
4484 offset = inode->i_size & (PAGE_CACHE_SIZE - 1);
4486 * All buffers in the last page remain valid? Then there's nothing to
4487 * do. We do the check mainly to optimize the common PAGE_CACHE_SIZE ==
4490 if (offset > PAGE_CACHE_SIZE - (1 << inode->i_blkbits))
4493 page = find_lock_page(inode->i_mapping,
4494 inode->i_size >> PAGE_CACHE_SHIFT);
4497 ret = __ext4_journalled_invalidatepage(page, offset,
4498 PAGE_CACHE_SIZE - offset);
4500 page_cache_release(page);
4504 read_lock(&journal->j_state_lock);
4505 if (journal->j_committing_transaction)
4506 commit_tid = journal->j_committing_transaction->t_tid;
4507 read_unlock(&journal->j_state_lock);
4509 jbd2_log_wait_commit(journal, commit_tid);
4516 * Called from notify_change.
4518 * We want to trap VFS attempts to truncate the file as soon as
4519 * possible. In particular, we want to make sure that when the VFS
4520 * shrinks i_size, we put the inode on the orphan list and modify
4521 * i_disksize immediately, so that during the subsequent flushing of
4522 * dirty pages and freeing of disk blocks, we can guarantee that any
4523 * commit will leave the blocks being flushed in an unused state on
4524 * disk. (On recovery, the inode will get truncated and the blocks will
4525 * be freed, so we have a strong guarantee that no future commit will
4526 * leave these blocks visible to the user.)
4528 * Another thing we have to assure is that if we are in ordered mode
4529 * and inode is still attached to the committing transaction, we must
4530 * we start writeout of all the dirty pages which are being truncated.
4531 * This way we are sure that all the data written in the previous
4532 * transaction are already on disk (truncate waits for pages under
4535 * Called with inode->i_mutex down.
4537 int ext4_setattr(struct dentry *dentry, struct iattr *attr)
4539 struct inode *inode = dentry->d_inode;
4542 const unsigned int ia_valid = attr->ia_valid;
4544 error = inode_change_ok(inode, attr);
4548 if (is_quota_modification(inode, attr))
4549 dquot_initialize(inode);
4550 if ((ia_valid & ATTR_UID && !uid_eq(attr->ia_uid, inode->i_uid)) ||
4551 (ia_valid & ATTR_GID && !gid_eq(attr->ia_gid, inode->i_gid))) {
4554 /* (user+group)*(old+new) structure, inode write (sb,
4555 * inode block, ? - but truncate inode update has it) */
4556 handle = ext4_journal_start(inode, EXT4_HT_QUOTA,
4557 (EXT4_MAXQUOTAS_INIT_BLOCKS(inode->i_sb) +
4558 EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb)) + 3);
4559 if (IS_ERR(handle)) {
4560 error = PTR_ERR(handle);
4563 error = dquot_transfer(inode, attr);
4565 ext4_journal_stop(handle);
4568 /* Update corresponding info in inode so that everything is in
4569 * one transaction */
4570 if (attr->ia_valid & ATTR_UID)
4571 inode->i_uid = attr->ia_uid;
4572 if (attr->ia_valid & ATTR_GID)
4573 inode->i_gid = attr->ia_gid;
4574 error = ext4_mark_inode_dirty(handle, inode);
4575 ext4_journal_stop(handle);
4578 if (attr->ia_valid & ATTR_SIZE && attr->ia_size != inode->i_size) {
4581 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
4582 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4584 if (attr->ia_size > sbi->s_bitmap_maxbytes)
4588 if (IS_I_VERSION(inode) && attr->ia_size != inode->i_size)
4589 inode_inc_iversion(inode);
4591 if (S_ISREG(inode->i_mode) &&
4592 (attr->ia_size < inode->i_size)) {
4593 if (ext4_should_order_data(inode)) {
4594 error = ext4_begin_ordered_truncate(inode,
4599 handle = ext4_journal_start(inode, EXT4_HT_INODE, 3);
4600 if (IS_ERR(handle)) {
4601 error = PTR_ERR(handle);
4604 if (ext4_handle_valid(handle)) {
4605 error = ext4_orphan_add(handle, inode);
4608 down_write(&EXT4_I(inode)->i_data_sem);
4609 EXT4_I(inode)->i_disksize = attr->ia_size;
4610 rc = ext4_mark_inode_dirty(handle, inode);
4614 * We have to update i_size under i_data_sem together
4615 * with i_disksize to avoid races with writeback code
4616 * running ext4_wb_update_i_disksize().
4619 i_size_write(inode, attr->ia_size);
4620 up_write(&EXT4_I(inode)->i_data_sem);
4621 ext4_journal_stop(handle);
4623 ext4_orphan_del(NULL, inode);
4627 i_size_write(inode, attr->ia_size);
4630 * Blocks are going to be removed from the inode. Wait
4631 * for dio in flight. Temporarily disable
4632 * dioread_nolock to prevent livelock.
4635 if (!ext4_should_journal_data(inode)) {
4636 ext4_inode_block_unlocked_dio(inode);
4637 inode_dio_wait(inode);
4638 ext4_inode_resume_unlocked_dio(inode);
4640 ext4_wait_for_tail_page_commit(inode);
4643 * Truncate pagecache after we've waited for commit
4644 * in data=journal mode to make pages freeable.
4646 truncate_pagecache(inode, inode->i_size);
4649 * We want to call ext4_truncate() even if attr->ia_size ==
4650 * inode->i_size for cases like truncation of fallocated space
4652 if (attr->ia_valid & ATTR_SIZE)
4653 ext4_truncate(inode);
4656 setattr_copy(inode, attr);
4657 mark_inode_dirty(inode);
4661 * If the call to ext4_truncate failed to get a transaction handle at
4662 * all, we need to clean up the in-core orphan list manually.
4664 if (orphan && inode->i_nlink)
4665 ext4_orphan_del(NULL, inode);
4667 if (!rc && (ia_valid & ATTR_MODE))
4668 rc = posix_acl_chmod(inode, inode->i_mode);
4671 ext4_std_error(inode->i_sb, error);
4677 int ext4_getattr(struct vfsmount *mnt, struct dentry *dentry,
4680 struct inode *inode;
4681 unsigned long long delalloc_blocks;
4683 inode = dentry->d_inode;
4684 generic_fillattr(inode, stat);
4687 * If there is inline data in the inode, the inode will normally not
4688 * have data blocks allocated (it may have an external xattr block).
4689 * Report at least one sector for such files, so tools like tar, rsync,
4690 * others doen't incorrectly think the file is completely sparse.
4692 if (unlikely(ext4_has_inline_data(inode)))
4693 stat->blocks += (stat->size + 511) >> 9;
4696 * We can't update i_blocks if the block allocation is delayed
4697 * otherwise in the case of system crash before the real block
4698 * allocation is done, we will have i_blocks inconsistent with
4699 * on-disk file blocks.
4700 * We always keep i_blocks updated together with real
4701 * allocation. But to not confuse with user, stat
4702 * will return the blocks that include the delayed allocation
4703 * blocks for this file.
4705 delalloc_blocks = EXT4_C2B(EXT4_SB(inode->i_sb),
4706 EXT4_I(inode)->i_reserved_data_blocks);
4707 stat->blocks += delalloc_blocks << (inode->i_sb->s_blocksize_bits - 9);
4711 static int ext4_index_trans_blocks(struct inode *inode, int lblocks,
4714 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
4715 return ext4_ind_trans_blocks(inode, lblocks);
4716 return ext4_ext_index_trans_blocks(inode, pextents);
4720 * Account for index blocks, block groups bitmaps and block group
4721 * descriptor blocks if modify datablocks and index blocks
4722 * worse case, the indexs blocks spread over different block groups
4724 * If datablocks are discontiguous, they are possible to spread over
4725 * different block groups too. If they are contiguous, with flexbg,
4726 * they could still across block group boundary.
4728 * Also account for superblock, inode, quota and xattr blocks
4730 static int ext4_meta_trans_blocks(struct inode *inode, int lblocks,
4733 ext4_group_t groups, ngroups = ext4_get_groups_count(inode->i_sb);
4739 * How many index blocks need to touch to map @lblocks logical blocks
4740 * to @pextents physical extents?
4742 idxblocks = ext4_index_trans_blocks(inode, lblocks, pextents);
4747 * Now let's see how many group bitmaps and group descriptors need
4750 groups = idxblocks + pextents;
4752 if (groups > ngroups)
4754 if (groups > EXT4_SB(inode->i_sb)->s_gdb_count)
4755 gdpblocks = EXT4_SB(inode->i_sb)->s_gdb_count;
4757 /* bitmaps and block group descriptor blocks */
4758 ret += groups + gdpblocks;
4760 /* Blocks for super block, inode, quota and xattr blocks */
4761 ret += EXT4_META_TRANS_BLOCKS(inode->i_sb);
4767 * Calculate the total number of credits to reserve to fit
4768 * the modification of a single pages into a single transaction,
4769 * which may include multiple chunks of block allocations.
4771 * This could be called via ext4_write_begin()
4773 * We need to consider the worse case, when
4774 * one new block per extent.
4776 int ext4_writepage_trans_blocks(struct inode *inode)
4778 int bpp = ext4_journal_blocks_per_page(inode);
4781 ret = ext4_meta_trans_blocks(inode, bpp, bpp);
4783 /* Account for data blocks for journalled mode */
4784 if (ext4_should_journal_data(inode))
4790 * Calculate the journal credits for a chunk of data modification.
4792 * This is called from DIO, fallocate or whoever calling
4793 * ext4_map_blocks() to map/allocate a chunk of contiguous disk blocks.
4795 * journal buffers for data blocks are not included here, as DIO
4796 * and fallocate do no need to journal data buffers.
4798 int ext4_chunk_trans_blocks(struct inode *inode, int nrblocks)
4800 return ext4_meta_trans_blocks(inode, nrblocks, 1);
4804 * The caller must have previously called ext4_reserve_inode_write().
4805 * Give this, we know that the caller already has write access to iloc->bh.
4807 int ext4_mark_iloc_dirty(handle_t *handle,
4808 struct inode *inode, struct ext4_iloc *iloc)
4812 if (IS_I_VERSION(inode))
4813 inode_inc_iversion(inode);
4815 /* the do_update_inode consumes one bh->b_count */
4818 /* ext4_do_update_inode() does jbd2_journal_dirty_metadata */
4819 err = ext4_do_update_inode(handle, inode, iloc);
4825 * On success, We end up with an outstanding reference count against
4826 * iloc->bh. This _must_ be cleaned up later.
4830 ext4_reserve_inode_write(handle_t *handle, struct inode *inode,
4831 struct ext4_iloc *iloc)
4835 err = ext4_get_inode_loc(inode, iloc);
4837 BUFFER_TRACE(iloc->bh, "get_write_access");
4838 err = ext4_journal_get_write_access(handle, iloc->bh);
4844 ext4_std_error(inode->i_sb, err);
4849 * Expand an inode by new_extra_isize bytes.
4850 * Returns 0 on success or negative error number on failure.
4852 static int ext4_expand_extra_isize(struct inode *inode,
4853 unsigned int new_extra_isize,
4854 struct ext4_iloc iloc,
4857 struct ext4_inode *raw_inode;
4858 struct ext4_xattr_ibody_header *header;
4860 if (EXT4_I(inode)->i_extra_isize >= new_extra_isize)
4863 raw_inode = ext4_raw_inode(&iloc);
4865 header = IHDR(inode, raw_inode);
4867 /* No extended attributes present */
4868 if (!ext4_test_inode_state(inode, EXT4_STATE_XATTR) ||
4869 header->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC)) {
4870 memset((void *)raw_inode + EXT4_GOOD_OLD_INODE_SIZE, 0,
4872 EXT4_I(inode)->i_extra_isize = new_extra_isize;
4876 /* try to expand with EAs present */
4877 return ext4_expand_extra_isize_ea(inode, new_extra_isize,
4882 * What we do here is to mark the in-core inode as clean with respect to inode
4883 * dirtiness (it may still be data-dirty).
4884 * This means that the in-core inode may be reaped by prune_icache
4885 * without having to perform any I/O. This is a very good thing,
4886 * because *any* task may call prune_icache - even ones which
4887 * have a transaction open against a different journal.
4889 * Is this cheating? Not really. Sure, we haven't written the
4890 * inode out, but prune_icache isn't a user-visible syncing function.
4891 * Whenever the user wants stuff synced (sys_sync, sys_msync, sys_fsync)
4892 * we start and wait on commits.
4894 int ext4_mark_inode_dirty(handle_t *handle, struct inode *inode)
4896 struct ext4_iloc iloc;
4897 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4898 static unsigned int mnt_count;
4902 trace_ext4_mark_inode_dirty(inode, _RET_IP_);
4903 err = ext4_reserve_inode_write(handle, inode, &iloc);
4904 if (ext4_handle_valid(handle) &&
4905 EXT4_I(inode)->i_extra_isize < sbi->s_want_extra_isize &&
4906 !ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND)) {
4908 * We need extra buffer credits since we may write into EA block
4909 * with this same handle. If journal_extend fails, then it will
4910 * only result in a minor loss of functionality for that inode.
4911 * If this is felt to be critical, then e2fsck should be run to
4912 * force a large enough s_min_extra_isize.
4914 if ((jbd2_journal_extend(handle,
4915 EXT4_DATA_TRANS_BLOCKS(inode->i_sb))) == 0) {
4916 ret = ext4_expand_extra_isize(inode,
4917 sbi->s_want_extra_isize,
4920 ext4_set_inode_state(inode,
4921 EXT4_STATE_NO_EXPAND);
4923 le16_to_cpu(sbi->s_es->s_mnt_count)) {
4924 ext4_warning(inode->i_sb,
4925 "Unable to expand inode %lu. Delete"
4926 " some EAs or run e2fsck.",
4929 le16_to_cpu(sbi->s_es->s_mnt_count);
4935 err = ext4_mark_iloc_dirty(handle, inode, &iloc);
4940 * ext4_dirty_inode() is called from __mark_inode_dirty()
4942 * We're really interested in the case where a file is being extended.
4943 * i_size has been changed by generic_commit_write() and we thus need
4944 * to include the updated inode in the current transaction.
4946 * Also, dquot_alloc_block() will always dirty the inode when blocks
4947 * are allocated to the file.
4949 * If the inode is marked synchronous, we don't honour that here - doing
4950 * so would cause a commit on atime updates, which we don't bother doing.
4951 * We handle synchronous inodes at the highest possible level.
4953 void ext4_dirty_inode(struct inode *inode, int flags)
4957 handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
4961 ext4_mark_inode_dirty(handle, inode);
4963 ext4_journal_stop(handle);
4970 * Bind an inode's backing buffer_head into this transaction, to prevent
4971 * it from being flushed to disk early. Unlike
4972 * ext4_reserve_inode_write, this leaves behind no bh reference and
4973 * returns no iloc structure, so the caller needs to repeat the iloc
4974 * lookup to mark the inode dirty later.
4976 static int ext4_pin_inode(handle_t *handle, struct inode *inode)
4978 struct ext4_iloc iloc;
4982 err = ext4_get_inode_loc(inode, &iloc);
4984 BUFFER_TRACE(iloc.bh, "get_write_access");
4985 err = jbd2_journal_get_write_access(handle, iloc.bh);
4987 err = ext4_handle_dirty_metadata(handle,
4993 ext4_std_error(inode->i_sb, err);
4998 int ext4_change_inode_journal_flag(struct inode *inode, int val)
5005 * We have to be very careful here: changing a data block's
5006 * journaling status dynamically is dangerous. If we write a
5007 * data block to the journal, change the status and then delete
5008 * that block, we risk forgetting to revoke the old log record
5009 * from the journal and so a subsequent replay can corrupt data.
5010 * So, first we make sure that the journal is empty and that
5011 * nobody is changing anything.
5014 journal = EXT4_JOURNAL(inode);
5017 if (is_journal_aborted(journal))
5019 /* We have to allocate physical blocks for delalloc blocks
5020 * before flushing journal. otherwise delalloc blocks can not
5021 * be allocated any more. even more truncate on delalloc blocks
5022 * could trigger BUG by flushing delalloc blocks in journal.
5023 * There is no delalloc block in non-journal data mode.
5025 if (val && test_opt(inode->i_sb, DELALLOC)) {
5026 err = ext4_alloc_da_blocks(inode);
5031 /* Wait for all existing dio workers */
5032 ext4_inode_block_unlocked_dio(inode);
5033 inode_dio_wait(inode);
5035 jbd2_journal_lock_updates(journal);
5038 * OK, there are no updates running now, and all cached data is
5039 * synced to disk. We are now in a completely consistent state
5040 * which doesn't have anything in the journal, and we know that
5041 * no filesystem updates are running, so it is safe to modify
5042 * the inode's in-core data-journaling state flag now.
5046 ext4_set_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
5048 jbd2_journal_flush(journal);
5049 ext4_clear_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
5051 ext4_set_aops(inode);
5053 jbd2_journal_unlock_updates(journal);
5054 ext4_inode_resume_unlocked_dio(inode);
5056 /* Finally we can mark the inode as dirty. */
5058 handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
5060 return PTR_ERR(handle);
5062 err = ext4_mark_inode_dirty(handle, inode);
5063 ext4_handle_sync(handle);
5064 ext4_journal_stop(handle);
5065 ext4_std_error(inode->i_sb, err);
5070 static int ext4_bh_unmapped(handle_t *handle, struct buffer_head *bh)
5072 return !buffer_mapped(bh);
5075 int ext4_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
5077 struct page *page = vmf->page;
5081 struct file *file = vma->vm_file;
5082 struct inode *inode = file_inode(file);
5083 struct address_space *mapping = inode->i_mapping;
5085 get_block_t *get_block;
5088 sb_start_pagefault(inode->i_sb);
5089 file_update_time(vma->vm_file);
5090 /* Delalloc case is easy... */
5091 if (test_opt(inode->i_sb, DELALLOC) &&
5092 !ext4_should_journal_data(inode) &&
5093 !ext4_nonda_switch(inode->i_sb)) {
5095 ret = __block_page_mkwrite(vma, vmf,
5096 ext4_da_get_block_prep);
5097 } while (ret == -ENOSPC &&
5098 ext4_should_retry_alloc(inode->i_sb, &retries));
5103 size = i_size_read(inode);
5104 /* Page got truncated from under us? */
5105 if (page->mapping != mapping || page_offset(page) > size) {
5107 ret = VM_FAULT_NOPAGE;
5111 if (page->index == size >> PAGE_CACHE_SHIFT)
5112 len = size & ~PAGE_CACHE_MASK;
5114 len = PAGE_CACHE_SIZE;
5116 * Return if we have all the buffers mapped. This avoids the need to do
5117 * journal_start/journal_stop which can block and take a long time
5119 if (page_has_buffers(page)) {
5120 if (!ext4_walk_page_buffers(NULL, page_buffers(page),
5122 ext4_bh_unmapped)) {
5123 /* Wait so that we don't change page under IO */
5124 wait_for_stable_page(page);
5125 ret = VM_FAULT_LOCKED;
5130 /* OK, we need to fill the hole... */
5131 if (ext4_should_dioread_nolock(inode))
5132 get_block = ext4_get_block_write;
5134 get_block = ext4_get_block;
5136 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
5137 ext4_writepage_trans_blocks(inode));
5138 if (IS_ERR(handle)) {
5139 ret = VM_FAULT_SIGBUS;
5142 ret = __block_page_mkwrite(vma, vmf, get_block);
5143 if (!ret && ext4_should_journal_data(inode)) {
5144 if (ext4_walk_page_buffers(handle, page_buffers(page), 0,
5145 PAGE_CACHE_SIZE, NULL, do_journal_get_write_access)) {
5147 ret = VM_FAULT_SIGBUS;
5148 ext4_journal_stop(handle);
5151 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
5153 ext4_journal_stop(handle);
5154 if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
5157 ret = block_page_mkwrite_return(ret);
5159 sb_end_pagefault(inode->i_sb);