1 // SPDX-License-Identifier: GPL-2.0
3 * linux/fs/ext4/inode.c
5 * Copyright (C) 1992, 1993, 1994, 1995
6 * Remy Card (card@masi.ibp.fr)
7 * Laboratoire MASI - Institut Blaise Pascal
8 * Universite Pierre et Marie Curie (Paris VI)
12 * linux/fs/minix/inode.c
14 * Copyright (C) 1991, 1992 Linus Torvalds
16 * 64-bit file support on 64-bit platforms by Jakub Jelinek
17 * (jj@sunsite.ms.mff.cuni.cz)
19 * Assorted race fixes, rewrite of ext4_get_block() by Al Viro, 2000
23 #include <linux/time.h>
24 #include <linux/highuid.h>
25 #include <linux/pagemap.h>
26 #include <linux/dax.h>
27 #include <linux/quotaops.h>
28 #include <linux/string.h>
29 #include <linux/buffer_head.h>
30 #include <linux/writeback.h>
31 #include <linux/pagevec.h>
32 #include <linux/mpage.h>
33 #include <linux/namei.h>
34 #include <linux/uio.h>
35 #include <linux/bio.h>
36 #include <linux/workqueue.h>
37 #include <linux/kernel.h>
38 #include <linux/printk.h>
39 #include <linux/slab.h>
40 #include <linux/bitops.h>
41 #include <linux/iomap.h>
42 #include <linux/iversion.h>
44 #include "ext4_jbd2.h"
49 #include <trace/events/ext4.h>
51 static __u32 ext4_inode_csum(struct inode *inode, struct ext4_inode *raw,
52 struct ext4_inode_info *ei)
54 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
57 int offset = offsetof(struct ext4_inode, i_checksum_lo);
58 unsigned int csum_size = sizeof(dummy_csum);
60 csum = ext4_chksum(sbi, ei->i_csum_seed, (__u8 *)raw, offset);
61 csum = ext4_chksum(sbi, csum, (__u8 *)&dummy_csum, csum_size);
63 csum = ext4_chksum(sbi, csum, (__u8 *)raw + offset,
64 EXT4_GOOD_OLD_INODE_SIZE - offset);
66 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
67 offset = offsetof(struct ext4_inode, i_checksum_hi);
68 csum = ext4_chksum(sbi, csum, (__u8 *)raw +
69 EXT4_GOOD_OLD_INODE_SIZE,
70 offset - EXT4_GOOD_OLD_INODE_SIZE);
71 if (EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi)) {
72 csum = ext4_chksum(sbi, csum, (__u8 *)&dummy_csum,
76 csum = ext4_chksum(sbi, csum, (__u8 *)raw + offset,
77 EXT4_INODE_SIZE(inode->i_sb) - offset);
83 static int ext4_inode_csum_verify(struct inode *inode, struct ext4_inode *raw,
84 struct ext4_inode_info *ei)
86 __u32 provided, calculated;
88 if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
89 cpu_to_le32(EXT4_OS_LINUX) ||
90 !ext4_has_metadata_csum(inode->i_sb))
93 provided = le16_to_cpu(raw->i_checksum_lo);
94 calculated = ext4_inode_csum(inode, raw, ei);
95 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
96 EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi))
97 provided |= ((__u32)le16_to_cpu(raw->i_checksum_hi)) << 16;
101 return provided == calculated;
104 void ext4_inode_csum_set(struct inode *inode, struct ext4_inode *raw,
105 struct ext4_inode_info *ei)
109 if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
110 cpu_to_le32(EXT4_OS_LINUX) ||
111 !ext4_has_metadata_csum(inode->i_sb))
114 csum = ext4_inode_csum(inode, raw, ei);
115 raw->i_checksum_lo = cpu_to_le16(csum & 0xFFFF);
116 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
117 EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi))
118 raw->i_checksum_hi = cpu_to_le16(csum >> 16);
121 static inline int ext4_begin_ordered_truncate(struct inode *inode,
124 trace_ext4_begin_ordered_truncate(inode, new_size);
126 * If jinode is zero, then we never opened the file for
127 * writing, so there's no need to call
128 * jbd2_journal_begin_ordered_truncate() since there's no
129 * outstanding writes we need to flush.
131 if (!EXT4_I(inode)->jinode)
133 return jbd2_journal_begin_ordered_truncate(EXT4_JOURNAL(inode),
134 EXT4_I(inode)->jinode,
138 static void ext4_invalidatepage(struct page *page, unsigned int offset,
139 unsigned int length);
140 static int __ext4_journalled_writepage(struct page *page, unsigned int len);
141 static int ext4_bh_delay_or_unwritten(handle_t *handle, struct buffer_head *bh);
142 static int ext4_meta_trans_blocks(struct inode *inode, int lblocks,
146 * Test whether an inode is a fast symlink.
147 * A fast symlink has its symlink data stored in ext4_inode_info->i_data.
149 int ext4_inode_is_fast_symlink(struct inode *inode)
151 if (!(EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL)) {
152 int ea_blocks = EXT4_I(inode)->i_file_acl ?
153 EXT4_CLUSTER_SIZE(inode->i_sb) >> 9 : 0;
155 if (ext4_has_inline_data(inode))
158 return (S_ISLNK(inode->i_mode) && inode->i_blocks - ea_blocks == 0);
160 return S_ISLNK(inode->i_mode) && inode->i_size &&
161 (inode->i_size < EXT4_N_BLOCKS * 4);
165 * Called at the last iput() if i_nlink is zero.
167 void ext4_evict_inode(struct inode *inode)
172 * Credits for final inode cleanup and freeing:
173 * sb + inode (ext4_orphan_del()), block bitmap, group descriptor
174 * (xattr block freeing), bitmap, group descriptor (inode freeing)
176 int extra_credits = 6;
177 struct ext4_xattr_inode_array *ea_inode_array = NULL;
178 bool freeze_protected = false;
180 trace_ext4_evict_inode(inode);
182 if (inode->i_nlink) {
184 * When journalling data dirty buffers are tracked only in the
185 * journal. So although mm thinks everything is clean and
186 * ready for reaping the inode might still have some pages to
187 * write in the running transaction or waiting to be
188 * checkpointed. Thus calling jbd2_journal_invalidatepage()
189 * (via truncate_inode_pages()) to discard these buffers can
190 * cause data loss. Also even if we did not discard these
191 * buffers, we would have no way to find them after the inode
192 * is reaped and thus user could see stale data if he tries to
193 * read them before the transaction is checkpointed. So be
194 * careful and force everything to disk here... We use
195 * ei->i_datasync_tid to store the newest transaction
196 * containing inode's data.
198 * Note that directories do not have this problem because they
199 * don't use page cache.
201 if (inode->i_ino != EXT4_JOURNAL_INO &&
202 ext4_should_journal_data(inode) &&
203 (S_ISLNK(inode->i_mode) || S_ISREG(inode->i_mode)) &&
204 inode->i_data.nrpages) {
205 journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
206 tid_t commit_tid = EXT4_I(inode)->i_datasync_tid;
208 jbd2_complete_transaction(journal, commit_tid);
209 filemap_write_and_wait(&inode->i_data);
211 truncate_inode_pages_final(&inode->i_data);
216 if (is_bad_inode(inode))
218 dquot_initialize(inode);
220 if (ext4_should_order_data(inode))
221 ext4_begin_ordered_truncate(inode, 0);
222 truncate_inode_pages_final(&inode->i_data);
225 * For inodes with journalled data, transaction commit could have
226 * dirtied the inode. Flush worker is ignoring it because of I_FREEING
227 * flag but we still need to remove the inode from the writeback lists.
229 if (!list_empty_careful(&inode->i_io_list)) {
230 WARN_ON_ONCE(!ext4_should_journal_data(inode));
231 inode_io_list_del(inode);
235 * Protect us against freezing - iput() caller didn't have to have any
236 * protection against it. When we are in a running transaction though,
237 * we are already protected against freezing and we cannot grab further
238 * protection due to lock ordering constraints.
240 if (!ext4_journal_current_handle()) {
241 sb_start_intwrite(inode->i_sb);
242 freeze_protected = true;
245 if (!IS_NOQUOTA(inode))
246 extra_credits += EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb);
249 * Block bitmap, group descriptor, and inode are accounted in both
250 * ext4_blocks_for_truncate() and extra_credits. So subtract 3.
252 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE,
253 ext4_blocks_for_truncate(inode) + extra_credits - 3);
254 if (IS_ERR(handle)) {
255 ext4_std_error(inode->i_sb, PTR_ERR(handle));
257 * If we're going to skip the normal cleanup, we still need to
258 * make sure that the in-core orphan linked list is properly
261 ext4_orphan_del(NULL, inode);
262 if (freeze_protected)
263 sb_end_intwrite(inode->i_sb);
268 ext4_handle_sync(handle);
271 * Set inode->i_size to 0 before calling ext4_truncate(). We need
272 * special handling of symlinks here because i_size is used to
273 * determine whether ext4_inode_info->i_data contains symlink data or
274 * block mappings. Setting i_size to 0 will remove its fast symlink
275 * status. Erase i_data so that it becomes a valid empty block map.
277 if (ext4_inode_is_fast_symlink(inode))
278 memset(EXT4_I(inode)->i_data, 0, sizeof(EXT4_I(inode)->i_data));
280 err = ext4_mark_inode_dirty(handle, inode);
282 ext4_warning(inode->i_sb,
283 "couldn't mark inode dirty (err %d)", err);
286 if (inode->i_blocks) {
287 err = ext4_truncate(inode);
289 ext4_error_err(inode->i_sb, -err,
290 "couldn't truncate inode %lu (err %d)",
296 /* Remove xattr references. */
297 err = ext4_xattr_delete_inode(handle, inode, &ea_inode_array,
300 ext4_warning(inode->i_sb, "xattr delete (err %d)", err);
302 ext4_journal_stop(handle);
303 ext4_orphan_del(NULL, inode);
304 if (freeze_protected)
305 sb_end_intwrite(inode->i_sb);
306 ext4_xattr_inode_array_free(ea_inode_array);
311 * Kill off the orphan record which ext4_truncate created.
312 * AKPM: I think this can be inside the above `if'.
313 * Note that ext4_orphan_del() has to be able to cope with the
314 * deletion of a non-existent orphan - this is because we don't
315 * know if ext4_truncate() actually created an orphan record.
316 * (Well, we could do this if we need to, but heck - it works)
318 ext4_orphan_del(handle, inode);
319 EXT4_I(inode)->i_dtime = (__u32)ktime_get_real_seconds();
322 * One subtle ordering requirement: if anything has gone wrong
323 * (transaction abort, IO errors, whatever), then we can still
324 * do these next steps (the fs will already have been marked as
325 * having errors), but we can't free the inode if the mark_dirty
328 if (ext4_mark_inode_dirty(handle, inode))
329 /* If that failed, just do the required in-core inode clear. */
330 ext4_clear_inode(inode);
332 ext4_free_inode(handle, inode);
333 ext4_journal_stop(handle);
334 if (freeze_protected)
335 sb_end_intwrite(inode->i_sb);
336 ext4_xattr_inode_array_free(ea_inode_array);
339 if (!list_empty(&EXT4_I(inode)->i_fc_list))
340 ext4_fc_mark_ineligible(inode->i_sb, EXT4_FC_REASON_NOMEM);
341 ext4_clear_inode(inode); /* We must guarantee clearing of inode... */
345 qsize_t *ext4_get_reserved_space(struct inode *inode)
347 return &EXT4_I(inode)->i_reserved_quota;
352 * Called with i_data_sem down, which is important since we can call
353 * ext4_discard_preallocations() from here.
355 void ext4_da_update_reserve_space(struct inode *inode,
356 int used, int quota_claim)
358 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
359 struct ext4_inode_info *ei = EXT4_I(inode);
361 spin_lock(&ei->i_block_reservation_lock);
362 trace_ext4_da_update_reserve_space(inode, used, quota_claim);
363 if (unlikely(used > ei->i_reserved_data_blocks)) {
364 ext4_warning(inode->i_sb, "%s: ino %lu, used %d "
365 "with only %d reserved data blocks",
366 __func__, inode->i_ino, used,
367 ei->i_reserved_data_blocks);
369 used = ei->i_reserved_data_blocks;
372 /* Update per-inode reservations */
373 ei->i_reserved_data_blocks -= used;
374 percpu_counter_sub(&sbi->s_dirtyclusters_counter, used);
376 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
378 /* Update quota subsystem for data blocks */
380 dquot_claim_block(inode, EXT4_C2B(sbi, used));
383 * We did fallocate with an offset that is already delayed
384 * allocated. So on delayed allocated writeback we should
385 * not re-claim the quota for fallocated blocks.
387 dquot_release_reservation_block(inode, EXT4_C2B(sbi, used));
391 * If we have done all the pending block allocations and if
392 * there aren't any writers on the inode, we can discard the
393 * inode's preallocations.
395 if ((ei->i_reserved_data_blocks == 0) &&
396 !inode_is_open_for_write(inode))
397 ext4_discard_preallocations(inode, 0);
400 static int __check_block_validity(struct inode *inode, const char *func,
402 struct ext4_map_blocks *map)
404 if (ext4_has_feature_journal(inode->i_sb) &&
406 le32_to_cpu(EXT4_SB(inode->i_sb)->s_es->s_journal_inum)))
408 if (!ext4_inode_block_valid(inode, map->m_pblk, map->m_len)) {
409 ext4_error_inode(inode, func, line, map->m_pblk,
410 "lblock %lu mapped to illegal pblock %llu "
411 "(length %d)", (unsigned long) map->m_lblk,
412 map->m_pblk, map->m_len);
413 return -EFSCORRUPTED;
418 int ext4_issue_zeroout(struct inode *inode, ext4_lblk_t lblk, ext4_fsblk_t pblk,
423 if (IS_ENCRYPTED(inode) && S_ISREG(inode->i_mode))
424 return fscrypt_zeroout_range(inode, lblk, pblk, len);
426 ret = sb_issue_zeroout(inode->i_sb, pblk, len, GFP_NOFS);
433 #define check_block_validity(inode, map) \
434 __check_block_validity((inode), __func__, __LINE__, (map))
436 #ifdef ES_AGGRESSIVE_TEST
437 static void ext4_map_blocks_es_recheck(handle_t *handle,
439 struct ext4_map_blocks *es_map,
440 struct ext4_map_blocks *map,
447 * There is a race window that the result is not the same.
448 * e.g. xfstests #223 when dioread_nolock enables. The reason
449 * is that we lookup a block mapping in extent status tree with
450 * out taking i_data_sem. So at the time the unwritten extent
451 * could be converted.
453 down_read(&EXT4_I(inode)->i_data_sem);
454 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
455 retval = ext4_ext_map_blocks(handle, inode, map, 0);
457 retval = ext4_ind_map_blocks(handle, inode, map, 0);
459 up_read((&EXT4_I(inode)->i_data_sem));
462 * We don't check m_len because extent will be collpased in status
463 * tree. So the m_len might not equal.
465 if (es_map->m_lblk != map->m_lblk ||
466 es_map->m_flags != map->m_flags ||
467 es_map->m_pblk != map->m_pblk) {
468 printk("ES cache assertion failed for inode: %lu "
469 "es_cached ex [%d/%d/%llu/%x] != "
470 "found ex [%d/%d/%llu/%x] retval %d flags %x\n",
471 inode->i_ino, es_map->m_lblk, es_map->m_len,
472 es_map->m_pblk, es_map->m_flags, map->m_lblk,
473 map->m_len, map->m_pblk, map->m_flags,
477 #endif /* ES_AGGRESSIVE_TEST */
480 * The ext4_map_blocks() function tries to look up the requested blocks,
481 * and returns if the blocks are already mapped.
483 * Otherwise it takes the write lock of the i_data_sem and allocate blocks
484 * and store the allocated blocks in the result buffer head and mark it
487 * If file type is extents based, it will call ext4_ext_map_blocks(),
488 * Otherwise, call with ext4_ind_map_blocks() to handle indirect mapping
491 * On success, it returns the number of blocks being mapped or allocated. if
492 * create==0 and the blocks are pre-allocated and unwritten, the resulting @map
493 * is marked as unwritten. If the create == 1, it will mark @map as mapped.
495 * It returns 0 if plain look up failed (blocks have not been allocated), in
496 * that case, @map is returned as unmapped but we still do fill map->m_len to
497 * indicate the length of a hole starting at map->m_lblk.
499 * It returns the error in case of allocation failure.
501 int ext4_map_blocks(handle_t *handle, struct inode *inode,
502 struct ext4_map_blocks *map, int flags)
504 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(inode, "flag 0x%x, max_blocks %u, logical block %lu\n",
515 flags, map->m_len, (unsigned long) map->m_lblk);
518 * ext4_map_blocks returns an int, and m_len is an unsigned int
520 if (unlikely(map->m_len > INT_MAX))
521 map->m_len = INT_MAX;
523 /* We can handle the block number less than EXT_MAX_BLOCKS */
524 if (unlikely(map->m_lblk >= EXT_MAX_BLOCKS))
525 return -EFSCORRUPTED;
527 /* Lookup extent status tree firstly */
528 if (!(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_FC_REPLAY) &&
529 ext4_es_lookup_extent(inode, map->m_lblk, NULL, &es)) {
530 if (ext4_es_is_written(&es) || ext4_es_is_unwritten(&es)) {
531 map->m_pblk = ext4_es_pblock(&es) +
532 map->m_lblk - es.es_lblk;
533 map->m_flags |= ext4_es_is_written(&es) ?
534 EXT4_MAP_MAPPED : EXT4_MAP_UNWRITTEN;
535 retval = es.es_len - (map->m_lblk - es.es_lblk);
536 if (retval > map->m_len)
539 } else if (ext4_es_is_delayed(&es) || ext4_es_is_hole(&es)) {
541 retval = es.es_len - (map->m_lblk - es.es_lblk);
542 if (retval > map->m_len)
549 #ifdef ES_AGGRESSIVE_TEST
550 ext4_map_blocks_es_recheck(handle, inode, map,
557 * Try to see if we can get the block without requesting a new
560 down_read(&EXT4_I(inode)->i_data_sem);
561 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
562 retval = ext4_ext_map_blocks(handle, inode, map, 0);
564 retval = ext4_ind_map_blocks(handle, inode, map, 0);
569 if (unlikely(retval != map->m_len)) {
570 ext4_warning(inode->i_sb,
571 "ES len assertion failed for inode "
572 "%lu: retval %d != map->m_len %d",
573 inode->i_ino, retval, map->m_len);
577 status = map->m_flags & EXT4_MAP_UNWRITTEN ?
578 EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
579 if (!(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) &&
580 !(status & EXTENT_STATUS_WRITTEN) &&
581 ext4_es_scan_range(inode, &ext4_es_is_delayed, map->m_lblk,
582 map->m_lblk + map->m_len - 1))
583 status |= EXTENT_STATUS_DELAYED;
584 ret = ext4_es_insert_extent(inode, map->m_lblk,
585 map->m_len, map->m_pblk, status);
589 up_read((&EXT4_I(inode)->i_data_sem));
592 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
593 ret = check_block_validity(inode, map);
598 /* If it is only a block(s) look up */
599 if ((flags & EXT4_GET_BLOCKS_CREATE) == 0)
603 * Returns if the blocks have already allocated
605 * Note that if blocks have been preallocated
606 * ext4_ext_get_block() returns the create = 0
607 * with buffer head unmapped.
609 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED)
611 * If we need to convert extent to unwritten
612 * we continue and do the actual work in
613 * ext4_ext_map_blocks()
615 if (!(flags & EXT4_GET_BLOCKS_CONVERT_UNWRITTEN))
619 * Here we clear m_flags because after allocating an new extent,
620 * it will be set again.
622 map->m_flags &= ~EXT4_MAP_FLAGS;
625 * New blocks allocate and/or writing to unwritten extent
626 * will possibly result in updating i_data, so we take
627 * the write lock of i_data_sem, and call get_block()
628 * with create == 1 flag.
630 down_write(&EXT4_I(inode)->i_data_sem);
633 * We need to check for EXT4 here because migrate
634 * could have changed the inode type in between
636 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
637 retval = ext4_ext_map_blocks(handle, inode, map, flags);
639 retval = ext4_ind_map_blocks(handle, inode, map, flags);
641 if (retval > 0 && map->m_flags & EXT4_MAP_NEW) {
643 * We allocated new blocks which will result in
644 * i_data's format changing. Force the migrate
645 * to fail by clearing migrate flags
647 ext4_clear_inode_state(inode, EXT4_STATE_EXT_MIGRATE);
651 * Update reserved blocks/metadata blocks after successful
652 * block allocation which had been deferred till now. We don't
653 * support fallocate for non extent files. So we can update
654 * reserve space here.
657 (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE))
658 ext4_da_update_reserve_space(inode, retval, 1);
664 if (unlikely(retval != map->m_len)) {
665 ext4_warning(inode->i_sb,
666 "ES len assertion failed for inode "
667 "%lu: retval %d != map->m_len %d",
668 inode->i_ino, retval, map->m_len);
673 * We have to zeroout blocks before inserting them into extent
674 * status tree. Otherwise someone could look them up there and
675 * use them before they are really zeroed. We also have to
676 * unmap metadata before zeroing as otherwise writeback can
677 * overwrite zeros with stale data from block device.
679 if (flags & EXT4_GET_BLOCKS_ZERO &&
680 map->m_flags & EXT4_MAP_MAPPED &&
681 map->m_flags & EXT4_MAP_NEW) {
682 ret = ext4_issue_zeroout(inode, map->m_lblk,
683 map->m_pblk, map->m_len);
691 * If the extent has been zeroed out, we don't need to update
692 * extent status tree.
694 if ((flags & EXT4_GET_BLOCKS_PRE_IO) &&
695 ext4_es_lookup_extent(inode, map->m_lblk, NULL, &es)) {
696 if (ext4_es_is_written(&es))
699 status = map->m_flags & EXT4_MAP_UNWRITTEN ?
700 EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
701 if (!(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) &&
702 !(status & EXTENT_STATUS_WRITTEN) &&
703 ext4_es_scan_range(inode, &ext4_es_is_delayed, map->m_lblk,
704 map->m_lblk + map->m_len - 1))
705 status |= EXTENT_STATUS_DELAYED;
706 ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
707 map->m_pblk, status);
715 up_write((&EXT4_I(inode)->i_data_sem));
716 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
717 ret = check_block_validity(inode, map);
722 * Inodes with freshly allocated blocks where contents will be
723 * visible after transaction commit must be on transaction's
726 if (map->m_flags & EXT4_MAP_NEW &&
727 !(map->m_flags & EXT4_MAP_UNWRITTEN) &&
728 !(flags & EXT4_GET_BLOCKS_ZERO) &&
729 !ext4_is_quota_file(inode) &&
730 ext4_should_order_data(inode)) {
732 (loff_t)map->m_lblk << inode->i_blkbits;
733 loff_t length = (loff_t)map->m_len << inode->i_blkbits;
735 if (flags & EXT4_GET_BLOCKS_IO_SUBMIT)
736 ret = ext4_jbd2_inode_add_wait(handle, inode,
739 ret = ext4_jbd2_inode_add_write(handle, inode,
745 if (retval > 0 && (map->m_flags & EXT4_MAP_UNWRITTEN ||
746 map->m_flags & EXT4_MAP_MAPPED))
747 ext4_fc_track_range(handle, inode, map->m_lblk,
748 map->m_lblk + map->m_len - 1);
750 ext_debug(inode, "failed with err %d\n", retval);
755 * Update EXT4_MAP_FLAGS in bh->b_state. For buffer heads attached to pages
756 * we have to be careful as someone else may be manipulating b_state as well.
758 static void ext4_update_bh_state(struct buffer_head *bh, unsigned long flags)
760 unsigned long old_state;
761 unsigned long new_state;
763 flags &= EXT4_MAP_FLAGS;
765 /* Dummy buffer_head? Set non-atomically. */
767 bh->b_state = (bh->b_state & ~EXT4_MAP_FLAGS) | flags;
771 * Someone else may be modifying b_state. Be careful! This is ugly but
772 * once we get rid of using bh as a container for mapping information
773 * to pass to / from get_block functions, this can go away.
776 old_state = READ_ONCE(bh->b_state);
777 new_state = (old_state & ~EXT4_MAP_FLAGS) | flags;
779 cmpxchg(&bh->b_state, old_state, new_state) != old_state));
782 static int _ext4_get_block(struct inode *inode, sector_t iblock,
783 struct buffer_head *bh, int flags)
785 struct ext4_map_blocks map;
788 if (ext4_has_inline_data(inode))
792 map.m_len = bh->b_size >> inode->i_blkbits;
794 ret = ext4_map_blocks(ext4_journal_current_handle(), inode, &map,
797 map_bh(bh, inode->i_sb, map.m_pblk);
798 ext4_update_bh_state(bh, map.m_flags);
799 bh->b_size = inode->i_sb->s_blocksize * map.m_len;
801 } else if (ret == 0) {
802 /* hole case, need to fill in bh->b_size */
803 bh->b_size = inode->i_sb->s_blocksize * map.m_len;
808 int ext4_get_block(struct inode *inode, sector_t iblock,
809 struct buffer_head *bh, int create)
811 return _ext4_get_block(inode, iblock, bh,
812 create ? EXT4_GET_BLOCKS_CREATE : 0);
816 * Get block function used when preparing for buffered write if we require
817 * creating an unwritten extent if blocks haven't been allocated. The extent
818 * will be converted to written after the IO is complete.
820 int ext4_get_block_unwritten(struct inode *inode, sector_t iblock,
821 struct buffer_head *bh_result, int create)
823 ext4_debug("ext4_get_block_unwritten: inode %lu, create flag %d\n",
824 inode->i_ino, create);
825 return _ext4_get_block(inode, iblock, bh_result,
826 EXT4_GET_BLOCKS_IO_CREATE_EXT);
829 /* Maximum number of blocks we map for direct IO at once. */
830 #define DIO_MAX_BLOCKS 4096
833 * `handle' can be NULL if create is zero
835 struct buffer_head *ext4_getblk(handle_t *handle, struct inode *inode,
836 ext4_lblk_t block, int map_flags)
838 struct ext4_map_blocks map;
839 struct buffer_head *bh;
840 int create = map_flags & EXT4_GET_BLOCKS_CREATE;
843 J_ASSERT((EXT4_SB(inode->i_sb)->s_mount_state & EXT4_FC_REPLAY)
844 || handle != NULL || create == 0);
848 err = ext4_map_blocks(handle, inode, &map, map_flags);
851 return create ? ERR_PTR(-ENOSPC) : NULL;
855 bh = sb_getblk(inode->i_sb, map.m_pblk);
857 return ERR_PTR(-ENOMEM);
858 if (map.m_flags & EXT4_MAP_NEW) {
859 J_ASSERT(create != 0);
860 J_ASSERT((EXT4_SB(inode->i_sb)->s_mount_state & EXT4_FC_REPLAY)
861 || (handle != NULL));
864 * Now that we do not always journal data, we should
865 * keep in mind whether this should always journal the
866 * new buffer as metadata. For now, regular file
867 * writes use ext4_get_block instead, so it's not a
871 BUFFER_TRACE(bh, "call get_create_access");
872 err = ext4_journal_get_create_access(handle, bh);
877 if (!buffer_uptodate(bh)) {
878 memset(bh->b_data, 0, inode->i_sb->s_blocksize);
879 set_buffer_uptodate(bh);
882 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
883 err = ext4_handle_dirty_metadata(handle, inode, bh);
887 BUFFER_TRACE(bh, "not a new buffer");
894 struct buffer_head *ext4_bread(handle_t *handle, struct inode *inode,
895 ext4_lblk_t block, int map_flags)
897 struct buffer_head *bh;
900 bh = ext4_getblk(handle, inode, block, map_flags);
903 if (!bh || ext4_buffer_uptodate(bh))
906 ret = ext4_read_bh_lock(bh, REQ_META | REQ_PRIO, true);
914 /* Read a contiguous batch of blocks. */
915 int ext4_bread_batch(struct inode *inode, ext4_lblk_t block, int bh_count,
916 bool wait, struct buffer_head **bhs)
920 for (i = 0; i < bh_count; i++) {
921 bhs[i] = ext4_getblk(NULL, inode, block + i, 0 /* map_flags */);
922 if (IS_ERR(bhs[i])) {
923 err = PTR_ERR(bhs[i]);
929 for (i = 0; i < bh_count; i++)
930 /* Note that NULL bhs[i] is valid because of holes. */
931 if (bhs[i] && !ext4_buffer_uptodate(bhs[i]))
932 ext4_read_bh_lock(bhs[i], REQ_META | REQ_PRIO, false);
937 for (i = 0; i < bh_count; i++)
939 wait_on_buffer(bhs[i]);
941 for (i = 0; i < bh_count; i++) {
942 if (bhs[i] && !buffer_uptodate(bhs[i])) {
950 for (i = 0; i < bh_count; i++) {
957 int ext4_walk_page_buffers(handle_t *handle,
958 struct buffer_head *head,
962 int (*fn)(handle_t *handle,
963 struct buffer_head *bh))
965 struct buffer_head *bh;
966 unsigned block_start, block_end;
967 unsigned blocksize = head->b_size;
969 struct buffer_head *next;
971 for (bh = head, block_start = 0;
972 ret == 0 && (bh != head || !block_start);
973 block_start = block_end, bh = next) {
974 next = bh->b_this_page;
975 block_end = block_start + blocksize;
976 if (block_end <= from || block_start >= to) {
977 if (partial && !buffer_uptodate(bh))
981 err = (*fn)(handle, bh);
989 * To preserve ordering, it is essential that the hole instantiation and
990 * the data write be encapsulated in a single transaction. We cannot
991 * close off a transaction and start a new one between the ext4_get_block()
992 * and the commit_write(). So doing the jbd2_journal_start at the start of
993 * prepare_write() is the right place.
995 * Also, this function can nest inside ext4_writepage(). In that case, we
996 * *know* that ext4_writepage() has generated enough buffer credits to do the
997 * whole page. So we won't block on the journal in that case, which is good,
998 * because the caller may be PF_MEMALLOC.
1000 * By accident, ext4 can be reentered when a transaction is open via
1001 * quota file writes. If we were to commit the transaction while thus
1002 * reentered, there can be a deadlock - we would be holding a quota
1003 * lock, and the commit would never complete if another thread had a
1004 * transaction open and was blocking on the quota lock - a ranking
1007 * So what we do is to rely on the fact that jbd2_journal_stop/journal_start
1008 * will _not_ run commit under these circumstances because handle->h_ref
1009 * is elevated. We'll still have enough credits for the tiny quotafile
1012 int do_journal_get_write_access(handle_t *handle,
1013 struct buffer_head *bh)
1015 int dirty = buffer_dirty(bh);
1018 if (!buffer_mapped(bh) || buffer_freed(bh))
1021 * __block_write_begin() could have dirtied some buffers. Clean
1022 * the dirty bit as jbd2_journal_get_write_access() could complain
1023 * otherwise about fs integrity issues. Setting of the dirty bit
1024 * by __block_write_begin() isn't a real problem here as we clear
1025 * the bit before releasing a page lock and thus writeback cannot
1026 * ever write the buffer.
1029 clear_buffer_dirty(bh);
1030 BUFFER_TRACE(bh, "get write access");
1031 ret = ext4_journal_get_write_access(handle, bh);
1033 ret = ext4_handle_dirty_metadata(handle, NULL, bh);
1037 #ifdef CONFIG_FS_ENCRYPTION
1038 static int ext4_block_write_begin(struct page *page, loff_t pos, unsigned len,
1039 get_block_t *get_block)
1041 unsigned from = pos & (PAGE_SIZE - 1);
1042 unsigned to = from + len;
1043 struct inode *inode = page->mapping->host;
1044 unsigned block_start, block_end;
1047 unsigned blocksize = inode->i_sb->s_blocksize;
1049 struct buffer_head *bh, *head, *wait[2];
1053 BUG_ON(!PageLocked(page));
1054 BUG_ON(from > PAGE_SIZE);
1055 BUG_ON(to > PAGE_SIZE);
1058 if (!page_has_buffers(page))
1059 create_empty_buffers(page, blocksize, 0);
1060 head = page_buffers(page);
1061 bbits = ilog2(blocksize);
1062 block = (sector_t)page->index << (PAGE_SHIFT - bbits);
1064 for (bh = head, block_start = 0; bh != head || !block_start;
1065 block++, block_start = block_end, bh = bh->b_this_page) {
1066 block_end = block_start + blocksize;
1067 if (block_end <= from || block_start >= to) {
1068 if (PageUptodate(page)) {
1069 if (!buffer_uptodate(bh))
1070 set_buffer_uptodate(bh);
1075 clear_buffer_new(bh);
1076 if (!buffer_mapped(bh)) {
1077 WARN_ON(bh->b_size != blocksize);
1078 err = get_block(inode, block, bh, 1);
1081 if (buffer_new(bh)) {
1082 if (PageUptodate(page)) {
1083 clear_buffer_new(bh);
1084 set_buffer_uptodate(bh);
1085 mark_buffer_dirty(bh);
1088 if (block_end > to || block_start < from)
1089 zero_user_segments(page, to, block_end,
1094 if (PageUptodate(page)) {
1095 if (!buffer_uptodate(bh))
1096 set_buffer_uptodate(bh);
1099 if (!buffer_uptodate(bh) && !buffer_delay(bh) &&
1100 !buffer_unwritten(bh) &&
1101 (block_start < from || block_end > to)) {
1102 ext4_read_bh_lock(bh, 0, false);
1103 wait[nr_wait++] = bh;
1107 * If we issued read requests, let them complete.
1109 for (i = 0; i < nr_wait; i++) {
1110 wait_on_buffer(wait[i]);
1111 if (!buffer_uptodate(wait[i]))
1114 if (unlikely(err)) {
1115 page_zero_new_buffers(page, from, to);
1116 } else if (fscrypt_inode_uses_fs_layer_crypto(inode)) {
1117 for (i = 0; i < nr_wait; i++) {
1120 err2 = fscrypt_decrypt_pagecache_blocks(page, blocksize,
1121 bh_offset(wait[i]));
1123 clear_buffer_uptodate(wait[i]);
1133 static int ext4_write_begin(struct file *file, struct address_space *mapping,
1134 loff_t pos, unsigned len, unsigned flags,
1135 struct page **pagep, void **fsdata)
1137 struct inode *inode = mapping->host;
1138 int ret, needed_blocks;
1145 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
1148 trace_ext4_write_begin(inode, pos, len, flags);
1150 * Reserve one block more for addition to orphan list in case
1151 * we allocate blocks but write fails for some reason
1153 needed_blocks = ext4_writepage_trans_blocks(inode) + 1;
1154 index = pos >> PAGE_SHIFT;
1155 from = pos & (PAGE_SIZE - 1);
1158 if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
1159 ret = ext4_try_to_write_inline_data(mapping, inode, pos, len,
1168 * grab_cache_page_write_begin() can take a long time if the
1169 * system is thrashing due to memory pressure, or if the page
1170 * is being written back. So grab it first before we start
1171 * the transaction handle. This also allows us to allocate
1172 * the page (if needed) without using GFP_NOFS.
1175 page = grab_cache_page_write_begin(mapping, index, flags);
1179 * The same as page allocation, we prealloc buffer heads before
1180 * starting the handle.
1182 if (!page_has_buffers(page))
1183 create_empty_buffers(page, inode->i_sb->s_blocksize, 0);
1188 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE, needed_blocks);
1189 if (IS_ERR(handle)) {
1191 return PTR_ERR(handle);
1195 if (page->mapping != mapping) {
1196 /* The page got truncated from under us */
1199 ext4_journal_stop(handle);
1202 /* In case writeback began while the page was unlocked */
1203 wait_for_stable_page(page);
1205 #ifdef CONFIG_FS_ENCRYPTION
1206 if (ext4_should_dioread_nolock(inode))
1207 ret = ext4_block_write_begin(page, pos, len,
1208 ext4_get_block_unwritten);
1210 ret = ext4_block_write_begin(page, pos, len,
1213 if (ext4_should_dioread_nolock(inode))
1214 ret = __block_write_begin(page, pos, len,
1215 ext4_get_block_unwritten);
1217 ret = __block_write_begin(page, pos, len, ext4_get_block);
1219 if (!ret && ext4_should_journal_data(inode)) {
1220 ret = ext4_walk_page_buffers(handle, page_buffers(page),
1222 do_journal_get_write_access);
1226 bool extended = (pos + len > inode->i_size) &&
1227 !ext4_verity_in_progress(inode);
1231 * __block_write_begin may have instantiated a few blocks
1232 * outside i_size. Trim these off again. Don't need
1233 * i_size_read because we hold i_mutex.
1235 * Add inode to orphan list in case we crash before
1238 if (extended && ext4_can_truncate(inode))
1239 ext4_orphan_add(handle, inode);
1241 ext4_journal_stop(handle);
1243 ext4_truncate_failed_write(inode);
1245 * If truncate failed early the inode might
1246 * still be on the orphan list; we need to
1247 * make sure the inode is removed from the
1248 * orphan list in that case.
1251 ext4_orphan_del(NULL, inode);
1254 if (ret == -ENOSPC &&
1255 ext4_should_retry_alloc(inode->i_sb, &retries))
1264 /* For write_end() in data=journal mode */
1265 static int write_end_fn(handle_t *handle, struct buffer_head *bh)
1268 if (!buffer_mapped(bh) || buffer_freed(bh))
1270 set_buffer_uptodate(bh);
1271 ret = ext4_handle_dirty_metadata(handle, NULL, bh);
1272 clear_buffer_meta(bh);
1273 clear_buffer_prio(bh);
1278 * We need to pick up the new inode size which generic_commit_write gave us
1279 * `file' can be NULL - eg, when called from page_symlink().
1281 * ext4 never places buffers on inode->i_mapping->private_list. metadata
1282 * buffers are managed internally.
1284 static int ext4_write_end(struct file *file,
1285 struct address_space *mapping,
1286 loff_t pos, unsigned len, unsigned copied,
1287 struct page *page, void *fsdata)
1289 handle_t *handle = ext4_journal_current_handle();
1290 struct inode *inode = mapping->host;
1291 loff_t old_size = inode->i_size;
1293 int i_size_changed = 0;
1294 int inline_data = ext4_has_inline_data(inode);
1295 bool verity = ext4_verity_in_progress(inode);
1297 trace_ext4_write_end(inode, pos, len, copied);
1299 ret = ext4_write_inline_data_end(inode, pos, len,
1309 copied = block_write_end(file, mapping, pos,
1310 len, copied, page, fsdata);
1312 * it's important to update i_size while still holding page lock:
1313 * page writeout could otherwise come in and zero beyond i_size.
1315 * If FS_IOC_ENABLE_VERITY is running on this inode, then Merkle tree
1316 * blocks are being written past EOF, so skip the i_size update.
1319 i_size_changed = ext4_update_inode_size(inode, pos + copied);
1323 if (old_size < pos && !verity)
1324 pagecache_isize_extended(inode, old_size, pos);
1326 * Don't mark the inode dirty under page lock. First, it unnecessarily
1327 * makes the holding time of page lock longer. Second, it forces lock
1328 * ordering of page lock and transaction start for journaling
1331 if (i_size_changed || inline_data)
1332 ret = ext4_mark_inode_dirty(handle, inode);
1335 if (pos + len > inode->i_size && !verity && ext4_can_truncate(inode))
1336 /* if we have allocated more blocks and copied
1337 * less. We will have blocks allocated outside
1338 * inode->i_size. So truncate them
1340 ext4_orphan_add(handle, inode);
1342 ret2 = ext4_journal_stop(handle);
1346 if (pos + len > inode->i_size && !verity) {
1347 ext4_truncate_failed_write(inode);
1349 * If truncate failed early the inode might still be
1350 * on the orphan list; we need to make sure the inode
1351 * is removed from the orphan list in that case.
1354 ext4_orphan_del(NULL, inode);
1357 return ret ? ret : copied;
1361 * This is a private version of page_zero_new_buffers() which doesn't
1362 * set the buffer to be dirty, since in data=journalled mode we need
1363 * to call ext4_handle_dirty_metadata() instead.
1365 static void ext4_journalled_zero_new_buffers(handle_t *handle,
1367 unsigned from, unsigned to)
1369 unsigned int block_start = 0, block_end;
1370 struct buffer_head *head, *bh;
1372 bh = head = page_buffers(page);
1374 block_end = block_start + bh->b_size;
1375 if (buffer_new(bh)) {
1376 if (block_end > from && block_start < to) {
1377 if (!PageUptodate(page)) {
1378 unsigned start, size;
1380 start = max(from, block_start);
1381 size = min(to, block_end) - start;
1383 zero_user(page, start, size);
1384 write_end_fn(handle, bh);
1386 clear_buffer_new(bh);
1389 block_start = block_end;
1390 bh = bh->b_this_page;
1391 } while (bh != head);
1394 static int ext4_journalled_write_end(struct file *file,
1395 struct address_space *mapping,
1396 loff_t pos, unsigned len, unsigned copied,
1397 struct page *page, void *fsdata)
1399 handle_t *handle = ext4_journal_current_handle();
1400 struct inode *inode = mapping->host;
1401 loff_t old_size = inode->i_size;
1405 int size_changed = 0;
1406 int inline_data = ext4_has_inline_data(inode);
1407 bool verity = ext4_verity_in_progress(inode);
1409 trace_ext4_journalled_write_end(inode, pos, len, copied);
1410 from = pos & (PAGE_SIZE - 1);
1413 BUG_ON(!ext4_handle_valid(handle));
1416 ret = ext4_write_inline_data_end(inode, pos, len,
1425 } else if (unlikely(copied < len) && !PageUptodate(page)) {
1427 ext4_journalled_zero_new_buffers(handle, page, from, to);
1429 if (unlikely(copied < len))
1430 ext4_journalled_zero_new_buffers(handle, page,
1432 ret = ext4_walk_page_buffers(handle, page_buffers(page), from,
1433 from + copied, &partial,
1436 SetPageUptodate(page);
1439 size_changed = ext4_update_inode_size(inode, pos + copied);
1440 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
1441 EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
1445 if (old_size < pos && !verity)
1446 pagecache_isize_extended(inode, old_size, pos);
1448 if (size_changed || inline_data) {
1449 ret2 = ext4_mark_inode_dirty(handle, inode);
1455 if (pos + len > inode->i_size && !verity && ext4_can_truncate(inode))
1456 /* if we have allocated more blocks and copied
1457 * less. We will have blocks allocated outside
1458 * inode->i_size. So truncate them
1460 ext4_orphan_add(handle, inode);
1462 ret2 = ext4_journal_stop(handle);
1465 if (pos + len > inode->i_size && !verity) {
1466 ext4_truncate_failed_write(inode);
1468 * If truncate failed early the inode might still be
1469 * on the orphan list; we need to make sure the inode
1470 * is removed from the orphan list in that case.
1473 ext4_orphan_del(NULL, inode);
1476 return ret ? ret : copied;
1480 * Reserve space for a single cluster
1482 static int ext4_da_reserve_space(struct inode *inode)
1484 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1485 struct ext4_inode_info *ei = EXT4_I(inode);
1489 * We will charge metadata quota at writeout time; this saves
1490 * us from metadata over-estimation, though we may go over by
1491 * a small amount in the end. Here we just reserve for data.
1493 ret = dquot_reserve_block(inode, EXT4_C2B(sbi, 1));
1497 spin_lock(&ei->i_block_reservation_lock);
1498 if (ext4_claim_free_clusters(sbi, 1, 0)) {
1499 spin_unlock(&ei->i_block_reservation_lock);
1500 dquot_release_reservation_block(inode, EXT4_C2B(sbi, 1));
1503 ei->i_reserved_data_blocks++;
1504 trace_ext4_da_reserve_space(inode);
1505 spin_unlock(&ei->i_block_reservation_lock);
1507 return 0; /* success */
1510 void ext4_da_release_space(struct inode *inode, int to_free)
1512 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1513 struct ext4_inode_info *ei = EXT4_I(inode);
1516 return; /* Nothing to release, exit */
1518 spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
1520 trace_ext4_da_release_space(inode, to_free);
1521 if (unlikely(to_free > ei->i_reserved_data_blocks)) {
1523 * if there aren't enough reserved blocks, then the
1524 * counter is messed up somewhere. Since this
1525 * function is called from invalidate page, it's
1526 * harmless to return without any action.
1528 ext4_warning(inode->i_sb, "ext4_da_release_space: "
1529 "ino %lu, to_free %d with only %d reserved "
1530 "data blocks", inode->i_ino, to_free,
1531 ei->i_reserved_data_blocks);
1533 to_free = ei->i_reserved_data_blocks;
1535 ei->i_reserved_data_blocks -= to_free;
1537 /* update fs dirty data blocks counter */
1538 percpu_counter_sub(&sbi->s_dirtyclusters_counter, to_free);
1540 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
1542 dquot_release_reservation_block(inode, EXT4_C2B(sbi, to_free));
1546 * Delayed allocation stuff
1549 struct mpage_da_data {
1550 struct inode *inode;
1551 struct writeback_control *wbc;
1553 pgoff_t first_page; /* The first page to write */
1554 pgoff_t next_page; /* Current page to examine */
1555 pgoff_t last_page; /* Last page to examine */
1557 * Extent to map - this can be after first_page because that can be
1558 * fully mapped. We somewhat abuse m_flags to store whether the extent
1559 * is delalloc or unwritten.
1561 struct ext4_map_blocks map;
1562 struct ext4_io_submit io_submit; /* IO submission data */
1563 unsigned int do_map:1;
1564 unsigned int scanned_until_end:1;
1567 static void mpage_release_unused_pages(struct mpage_da_data *mpd,
1572 struct pagevec pvec;
1573 struct inode *inode = mpd->inode;
1574 struct address_space *mapping = inode->i_mapping;
1576 /* This is necessary when next_page == 0. */
1577 if (mpd->first_page >= mpd->next_page)
1580 mpd->scanned_until_end = 0;
1581 index = mpd->first_page;
1582 end = mpd->next_page - 1;
1584 ext4_lblk_t start, last;
1585 start = index << (PAGE_SHIFT - inode->i_blkbits);
1586 last = end << (PAGE_SHIFT - inode->i_blkbits);
1589 * avoid racing with extent status tree scans made by
1590 * ext4_insert_delayed_block()
1592 down_write(&EXT4_I(inode)->i_data_sem);
1593 ext4_es_remove_extent(inode, start, last - start + 1);
1594 up_write(&EXT4_I(inode)->i_data_sem);
1597 pagevec_init(&pvec);
1598 while (index <= end) {
1599 nr_pages = pagevec_lookup_range(&pvec, mapping, &index, end);
1602 for (i = 0; i < nr_pages; i++) {
1603 struct page *page = pvec.pages[i];
1605 BUG_ON(!PageLocked(page));
1606 BUG_ON(PageWriteback(page));
1608 if (page_mapped(page))
1609 clear_page_dirty_for_io(page);
1610 block_invalidatepage(page, 0, PAGE_SIZE);
1611 ClearPageUptodate(page);
1615 pagevec_release(&pvec);
1619 static void ext4_print_free_blocks(struct inode *inode)
1621 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1622 struct super_block *sb = inode->i_sb;
1623 struct ext4_inode_info *ei = EXT4_I(inode);
1625 ext4_msg(sb, KERN_CRIT, "Total free blocks count %lld",
1626 EXT4_C2B(EXT4_SB(inode->i_sb),
1627 ext4_count_free_clusters(sb)));
1628 ext4_msg(sb, KERN_CRIT, "Free/Dirty block details");
1629 ext4_msg(sb, KERN_CRIT, "free_blocks=%lld",
1630 (long long) EXT4_C2B(EXT4_SB(sb),
1631 percpu_counter_sum(&sbi->s_freeclusters_counter)));
1632 ext4_msg(sb, KERN_CRIT, "dirty_blocks=%lld",
1633 (long long) EXT4_C2B(EXT4_SB(sb),
1634 percpu_counter_sum(&sbi->s_dirtyclusters_counter)));
1635 ext4_msg(sb, KERN_CRIT, "Block reservation details");
1636 ext4_msg(sb, KERN_CRIT, "i_reserved_data_blocks=%u",
1637 ei->i_reserved_data_blocks);
1641 static int ext4_bh_delay_or_unwritten(handle_t *handle, struct buffer_head *bh)
1643 return (buffer_delay(bh) || buffer_unwritten(bh)) && buffer_dirty(bh);
1647 * ext4_insert_delayed_block - adds a delayed block to the extents status
1648 * tree, incrementing the reserved cluster/block
1649 * count or making a pending reservation
1652 * @inode - file containing the newly added block
1653 * @lblk - logical block to be added
1655 * Returns 0 on success, negative error code on failure.
1657 static int ext4_insert_delayed_block(struct inode *inode, ext4_lblk_t lblk)
1659 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1661 bool allocated = false;
1662 bool reserved = false;
1665 * If the cluster containing lblk is shared with a delayed,
1666 * written, or unwritten extent in a bigalloc file system, it's
1667 * already been accounted for and does not need to be reserved.
1668 * A pending reservation must be made for the cluster if it's
1669 * shared with a written or unwritten extent and doesn't already
1670 * have one. Written and unwritten extents can be purged from the
1671 * extents status tree if the system is under memory pressure, so
1672 * it's necessary to examine the extent tree if a search of the
1673 * extents status tree doesn't get a match.
1675 if (sbi->s_cluster_ratio == 1) {
1676 ret = ext4_da_reserve_space(inode);
1677 if (ret != 0) /* ENOSPC */
1680 } else { /* bigalloc */
1681 if (!ext4_es_scan_clu(inode, &ext4_es_is_delonly, lblk)) {
1682 if (!ext4_es_scan_clu(inode,
1683 &ext4_es_is_mapped, lblk)) {
1684 ret = ext4_clu_mapped(inode,
1685 EXT4_B2C(sbi, lblk));
1689 ret = ext4_da_reserve_space(inode);
1690 if (ret != 0) /* ENOSPC */
1702 ret = ext4_es_insert_delayed_block(inode, lblk, allocated);
1703 if (ret && reserved)
1704 ext4_da_release_space(inode, 1);
1711 * This function is grabs code from the very beginning of
1712 * ext4_map_blocks, but assumes that the caller is from delayed write
1713 * time. This function looks up the requested blocks and sets the
1714 * buffer delay bit under the protection of i_data_sem.
1716 static int ext4_da_map_blocks(struct inode *inode, sector_t iblock,
1717 struct ext4_map_blocks *map,
1718 struct buffer_head *bh)
1720 struct extent_status es;
1722 sector_t invalid_block = ~((sector_t) 0xffff);
1723 #ifdef ES_AGGRESSIVE_TEST
1724 struct ext4_map_blocks orig_map;
1726 memcpy(&orig_map, map, sizeof(*map));
1729 if (invalid_block < ext4_blocks_count(EXT4_SB(inode->i_sb)->s_es))
1733 ext_debug(inode, "max_blocks %u, logical block %lu\n", map->m_len,
1734 (unsigned long) map->m_lblk);
1736 /* Lookup extent status tree firstly */
1737 if (ext4_es_lookup_extent(inode, iblock, NULL, &es)) {
1738 if (ext4_es_is_hole(&es)) {
1740 down_read(&EXT4_I(inode)->i_data_sem);
1745 * Delayed extent could be allocated by fallocate.
1746 * So we need to check it.
1748 if (ext4_es_is_delayed(&es) && !ext4_es_is_unwritten(&es)) {
1749 map_bh(bh, inode->i_sb, invalid_block);
1751 set_buffer_delay(bh);
1755 map->m_pblk = ext4_es_pblock(&es) + iblock - es.es_lblk;
1756 retval = es.es_len - (iblock - es.es_lblk);
1757 if (retval > map->m_len)
1758 retval = map->m_len;
1759 map->m_len = retval;
1760 if (ext4_es_is_written(&es))
1761 map->m_flags |= EXT4_MAP_MAPPED;
1762 else if (ext4_es_is_unwritten(&es))
1763 map->m_flags |= EXT4_MAP_UNWRITTEN;
1767 #ifdef ES_AGGRESSIVE_TEST
1768 ext4_map_blocks_es_recheck(NULL, inode, map, &orig_map, 0);
1774 * Try to see if we can get the block without requesting a new
1775 * file system block.
1777 down_read(&EXT4_I(inode)->i_data_sem);
1778 if (ext4_has_inline_data(inode))
1780 else if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
1781 retval = ext4_ext_map_blocks(NULL, inode, map, 0);
1783 retval = ext4_ind_map_blocks(NULL, inode, map, 0);
1790 * XXX: __block_prepare_write() unmaps passed block,
1794 ret = ext4_insert_delayed_block(inode, map->m_lblk);
1800 map_bh(bh, inode->i_sb, invalid_block);
1802 set_buffer_delay(bh);
1803 } else if (retval > 0) {
1805 unsigned int status;
1807 if (unlikely(retval != map->m_len)) {
1808 ext4_warning(inode->i_sb,
1809 "ES len assertion failed for inode "
1810 "%lu: retval %d != map->m_len %d",
1811 inode->i_ino, retval, map->m_len);
1815 status = map->m_flags & EXT4_MAP_UNWRITTEN ?
1816 EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
1817 ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
1818 map->m_pblk, status);
1824 up_read((&EXT4_I(inode)->i_data_sem));
1830 * This is a special get_block_t callback which is used by
1831 * ext4_da_write_begin(). It will either return mapped block or
1832 * reserve space for a single block.
1834 * For delayed buffer_head we have BH_Mapped, BH_New, BH_Delay set.
1835 * We also have b_blocknr = -1 and b_bdev initialized properly
1837 * For unwritten buffer_head we have BH_Mapped, BH_New, BH_Unwritten set.
1838 * We also have b_blocknr = physicalblock mapping unwritten extent and b_bdev
1839 * initialized properly.
1841 int ext4_da_get_block_prep(struct inode *inode, sector_t iblock,
1842 struct buffer_head *bh, int create)
1844 struct ext4_map_blocks map;
1847 BUG_ON(create == 0);
1848 BUG_ON(bh->b_size != inode->i_sb->s_blocksize);
1850 map.m_lblk = iblock;
1854 * first, we need to know whether the block is allocated already
1855 * preallocated blocks are unmapped but should treated
1856 * the same as allocated blocks.
1858 ret = ext4_da_map_blocks(inode, iblock, &map, bh);
1862 map_bh(bh, inode->i_sb, map.m_pblk);
1863 ext4_update_bh_state(bh, map.m_flags);
1865 if (buffer_unwritten(bh)) {
1866 /* A delayed write to unwritten bh should be marked
1867 * new and mapped. Mapped ensures that we don't do
1868 * get_block multiple times when we write to the same
1869 * offset and new ensures that we do proper zero out
1870 * for partial write.
1873 set_buffer_mapped(bh);
1878 static int bget_one(handle_t *handle, struct buffer_head *bh)
1884 static int bput_one(handle_t *handle, struct buffer_head *bh)
1890 static int __ext4_journalled_writepage(struct page *page,
1893 struct address_space *mapping = page->mapping;
1894 struct inode *inode = mapping->host;
1895 struct buffer_head *page_bufs = NULL;
1896 handle_t *handle = NULL;
1897 int ret = 0, err = 0;
1898 int inline_data = ext4_has_inline_data(inode);
1899 struct buffer_head *inode_bh = NULL;
1901 ClearPageChecked(page);
1904 BUG_ON(page->index != 0);
1905 BUG_ON(len > ext4_get_max_inline_size(inode));
1906 inode_bh = ext4_journalled_write_inline_data(inode, len, page);
1907 if (inode_bh == NULL)
1910 page_bufs = page_buffers(page);
1915 ext4_walk_page_buffers(handle, page_bufs, 0, len,
1919 * We need to release the page lock before we start the
1920 * journal, so grab a reference so the page won't disappear
1921 * out from under us.
1926 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
1927 ext4_writepage_trans_blocks(inode));
1928 if (IS_ERR(handle)) {
1929 ret = PTR_ERR(handle);
1931 goto out_no_pagelock;
1933 BUG_ON(!ext4_handle_valid(handle));
1937 if (page->mapping != mapping) {
1938 /* The page got truncated from under us */
1939 ext4_journal_stop(handle);
1945 ret = ext4_mark_inode_dirty(handle, inode);
1947 ret = ext4_walk_page_buffers(handle, page_bufs, 0, len, NULL,
1948 do_journal_get_write_access);
1950 err = ext4_walk_page_buffers(handle, page_bufs, 0, len, NULL,
1955 err = ext4_jbd2_inode_add_write(handle, inode, page_offset(page), len);
1958 EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
1959 err = ext4_journal_stop(handle);
1963 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
1967 if (!inline_data && page_bufs)
1968 ext4_walk_page_buffers(NULL, page_bufs, 0, len,
1975 * Note that we don't need to start a transaction unless we're journaling data
1976 * because we should have holes filled from ext4_page_mkwrite(). We even don't
1977 * need to file the inode to the transaction's list in ordered mode because if
1978 * we are writing back data added by write(), the inode is already there and if
1979 * we are writing back data modified via mmap(), no one guarantees in which
1980 * transaction the data will hit the disk. In case we are journaling data, we
1981 * cannot start transaction directly because transaction start ranks above page
1982 * lock so we have to do some magic.
1984 * This function can get called via...
1985 * - ext4_writepages after taking page lock (have journal handle)
1986 * - journal_submit_inode_data_buffers (no journal handle)
1987 * - shrink_page_list via the kswapd/direct reclaim (no journal handle)
1988 * - grab_page_cache when doing write_begin (have journal handle)
1990 * We don't do any block allocation in this function. If we have page with
1991 * multiple blocks we need to write those buffer_heads that are mapped. This
1992 * is important for mmaped based write. So if we do with blocksize 1K
1993 * truncate(f, 1024);
1994 * a = mmap(f, 0, 4096);
1996 * truncate(f, 4096);
1997 * we have in the page first buffer_head mapped via page_mkwrite call back
1998 * but other buffer_heads would be unmapped but dirty (dirty done via the
1999 * do_wp_page). So writepage should write the first block. If we modify
2000 * the mmap area beyond 1024 we will again get a page_fault and the
2001 * page_mkwrite callback will do the block allocation and mark the
2002 * buffer_heads mapped.
2004 * We redirty the page if we have any buffer_heads that is either delay or
2005 * unwritten in the page.
2007 * We can get recursively called as show below.
2009 * ext4_writepage() -> kmalloc() -> __alloc_pages() -> page_launder() ->
2012 * But since we don't do any block allocation we should not deadlock.
2013 * Page also have the dirty flag cleared so we don't get recurive page_lock.
2015 static int ext4_writepage(struct page *page,
2016 struct writeback_control *wbc)
2021 struct buffer_head *page_bufs = NULL;
2022 struct inode *inode = page->mapping->host;
2023 struct ext4_io_submit io_submit;
2024 bool keep_towrite = false;
2026 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb)))) {
2027 inode->i_mapping->a_ops->invalidatepage(page, 0, PAGE_SIZE);
2032 trace_ext4_writepage(page);
2033 size = i_size_read(inode);
2034 if (page->index == size >> PAGE_SHIFT &&
2035 !ext4_verity_in_progress(inode))
2036 len = size & ~PAGE_MASK;
2040 /* Should never happen but for bugs in other kernel subsystems */
2041 if (!page_has_buffers(page)) {
2042 ext4_warning_inode(inode,
2043 "page %lu does not have buffers attached", page->index);
2044 ClearPageDirty(page);
2049 page_bufs = page_buffers(page);
2051 * We cannot do block allocation or other extent handling in this
2052 * function. If there are buffers needing that, we have to redirty
2053 * the page. But we may reach here when we do a journal commit via
2054 * journal_submit_inode_data_buffers() and in that case we must write
2055 * allocated buffers to achieve data=ordered mode guarantees.
2057 * Also, if there is only one buffer per page (the fs block
2058 * size == the page size), if one buffer needs block
2059 * allocation or needs to modify the extent tree to clear the
2060 * unwritten flag, we know that the page can't be written at
2061 * all, so we might as well refuse the write immediately.
2062 * Unfortunately if the block size != page size, we can't as
2063 * easily detect this case using ext4_walk_page_buffers(), but
2064 * for the extremely common case, this is an optimization that
2065 * skips a useless round trip through ext4_bio_write_page().
2067 if (ext4_walk_page_buffers(NULL, page_bufs, 0, len, NULL,
2068 ext4_bh_delay_or_unwritten)) {
2069 redirty_page_for_writepage(wbc, page);
2070 if ((current->flags & PF_MEMALLOC) ||
2071 (inode->i_sb->s_blocksize == PAGE_SIZE)) {
2073 * For memory cleaning there's no point in writing only
2074 * some buffers. So just bail out. Warn if we came here
2075 * from direct reclaim.
2077 WARN_ON_ONCE((current->flags & (PF_MEMALLOC|PF_KSWAPD))
2082 keep_towrite = true;
2085 if (PageChecked(page) && ext4_should_journal_data(inode))
2087 * It's mmapped pagecache. Add buffers and journal it. There
2088 * doesn't seem much point in redirtying the page here.
2090 return __ext4_journalled_writepage(page, len);
2092 ext4_io_submit_init(&io_submit, wbc);
2093 io_submit.io_end = ext4_init_io_end(inode, GFP_NOFS);
2094 if (!io_submit.io_end) {
2095 redirty_page_for_writepage(wbc, page);
2099 ret = ext4_bio_write_page(&io_submit, page, len, wbc, keep_towrite);
2100 ext4_io_submit(&io_submit);
2101 /* Drop io_end reference we got from init */
2102 ext4_put_io_end_defer(io_submit.io_end);
2106 static int mpage_submit_page(struct mpage_da_data *mpd, struct page *page)
2112 BUG_ON(page->index != mpd->first_page);
2113 clear_page_dirty_for_io(page);
2115 * We have to be very careful here! Nothing protects writeback path
2116 * against i_size changes and the page can be writeably mapped into
2117 * page tables. So an application can be growing i_size and writing
2118 * data through mmap while writeback runs. clear_page_dirty_for_io()
2119 * write-protects our page in page tables and the page cannot get
2120 * written to again until we release page lock. So only after
2121 * clear_page_dirty_for_io() we are safe to sample i_size for
2122 * ext4_bio_write_page() to zero-out tail of the written page. We rely
2123 * on the barrier provided by TestClearPageDirty in
2124 * clear_page_dirty_for_io() to make sure i_size is really sampled only
2125 * after page tables are updated.
2127 size = i_size_read(mpd->inode);
2128 if (page->index == size >> PAGE_SHIFT &&
2129 !ext4_verity_in_progress(mpd->inode))
2130 len = size & ~PAGE_MASK;
2133 err = ext4_bio_write_page(&mpd->io_submit, page, len, mpd->wbc, false);
2135 mpd->wbc->nr_to_write--;
2141 #define BH_FLAGS (BIT(BH_Unwritten) | BIT(BH_Delay))
2144 * mballoc gives us at most this number of blocks...
2145 * XXX: That seems to be only a limitation of ext4_mb_normalize_request().
2146 * The rest of mballoc seems to handle chunks up to full group size.
2148 #define MAX_WRITEPAGES_EXTENT_LEN 2048
2151 * mpage_add_bh_to_extent - try to add bh to extent of blocks to map
2153 * @mpd - extent of blocks
2154 * @lblk - logical number of the block in the file
2155 * @bh - buffer head we want to add to the extent
2157 * The function is used to collect contig. blocks in the same state. If the
2158 * buffer doesn't require mapping for writeback and we haven't started the
2159 * extent of buffers to map yet, the function returns 'true' immediately - the
2160 * caller can write the buffer right away. Otherwise the function returns true
2161 * if the block has been added to the extent, false if the block couldn't be
2164 static bool mpage_add_bh_to_extent(struct mpage_da_data *mpd, ext4_lblk_t lblk,
2165 struct buffer_head *bh)
2167 struct ext4_map_blocks *map = &mpd->map;
2169 /* Buffer that doesn't need mapping for writeback? */
2170 if (!buffer_dirty(bh) || !buffer_mapped(bh) ||
2171 (!buffer_delay(bh) && !buffer_unwritten(bh))) {
2172 /* So far no extent to map => we write the buffer right away */
2173 if (map->m_len == 0)
2178 /* First block in the extent? */
2179 if (map->m_len == 0) {
2180 /* We cannot map unless handle is started... */
2185 map->m_flags = bh->b_state & BH_FLAGS;
2189 /* Don't go larger than mballoc is willing to allocate */
2190 if (map->m_len >= MAX_WRITEPAGES_EXTENT_LEN)
2193 /* Can we merge the block to our big extent? */
2194 if (lblk == map->m_lblk + map->m_len &&
2195 (bh->b_state & BH_FLAGS) == map->m_flags) {
2203 * mpage_process_page_bufs - submit page buffers for IO or add them to extent
2205 * @mpd - extent of blocks for mapping
2206 * @head - the first buffer in the page
2207 * @bh - buffer we should start processing from
2208 * @lblk - logical number of the block in the file corresponding to @bh
2210 * Walk through page buffers from @bh upto @head (exclusive) and either submit
2211 * the page for IO if all buffers in this page were mapped and there's no
2212 * accumulated extent of buffers to map or add buffers in the page to the
2213 * extent of buffers to map. The function returns 1 if the caller can continue
2214 * by processing the next page, 0 if it should stop adding buffers to the
2215 * extent to map because we cannot extend it anymore. It can also return value
2216 * < 0 in case of error during IO submission.
2218 static int mpage_process_page_bufs(struct mpage_da_data *mpd,
2219 struct buffer_head *head,
2220 struct buffer_head *bh,
2223 struct inode *inode = mpd->inode;
2225 ext4_lblk_t blocks = (i_size_read(inode) + i_blocksize(inode) - 1)
2226 >> inode->i_blkbits;
2228 if (ext4_verity_in_progress(inode))
2229 blocks = EXT_MAX_BLOCKS;
2232 BUG_ON(buffer_locked(bh));
2234 if (lblk >= blocks || !mpage_add_bh_to_extent(mpd, lblk, bh)) {
2235 /* Found extent to map? */
2238 /* Buffer needs mapping and handle is not started? */
2241 /* Everything mapped so far and we hit EOF */
2244 } while (lblk++, (bh = bh->b_this_page) != head);
2245 /* So far everything mapped? Submit the page for IO. */
2246 if (mpd->map.m_len == 0) {
2247 err = mpage_submit_page(mpd, head->b_page);
2251 if (lblk >= blocks) {
2252 mpd->scanned_until_end = 1;
2259 * mpage_process_page - update page buffers corresponding to changed extent and
2260 * may submit fully mapped page for IO
2262 * @mpd - description of extent to map, on return next extent to map
2263 * @m_lblk - logical block mapping.
2264 * @m_pblk - corresponding physical mapping.
2265 * @map_bh - determines on return whether this page requires any further
2267 * Scan given page buffers corresponding to changed extent and update buffer
2268 * state according to new extent state.
2269 * We map delalloc buffers to their physical location, clear unwritten bits.
2270 * If the given page is not fully mapped, we update @map to the next extent in
2271 * the given page that needs mapping & return @map_bh as true.
2273 static int mpage_process_page(struct mpage_da_data *mpd, struct page *page,
2274 ext4_lblk_t *m_lblk, ext4_fsblk_t *m_pblk,
2277 struct buffer_head *head, *bh;
2278 ext4_io_end_t *io_end = mpd->io_submit.io_end;
2279 ext4_lblk_t lblk = *m_lblk;
2280 ext4_fsblk_t pblock = *m_pblk;
2282 int blkbits = mpd->inode->i_blkbits;
2283 ssize_t io_end_size = 0;
2284 struct ext4_io_end_vec *io_end_vec = ext4_last_io_end_vec(io_end);
2286 bh = head = page_buffers(page);
2288 if (lblk < mpd->map.m_lblk)
2290 if (lblk >= mpd->map.m_lblk + mpd->map.m_len) {
2292 * Buffer after end of mapped extent.
2293 * Find next buffer in the page to map.
2296 mpd->map.m_flags = 0;
2297 io_end_vec->size += io_end_size;
2300 err = mpage_process_page_bufs(mpd, head, bh, lblk);
2303 if (!err && mpd->map.m_len && mpd->map.m_lblk > lblk) {
2304 io_end_vec = ext4_alloc_io_end_vec(io_end);
2305 if (IS_ERR(io_end_vec)) {
2306 err = PTR_ERR(io_end_vec);
2309 io_end_vec->offset = (loff_t)mpd->map.m_lblk << blkbits;
2314 if (buffer_delay(bh)) {
2315 clear_buffer_delay(bh);
2316 bh->b_blocknr = pblock++;
2318 clear_buffer_unwritten(bh);
2319 io_end_size += (1 << blkbits);
2320 } while (lblk++, (bh = bh->b_this_page) != head);
2322 io_end_vec->size += io_end_size;
2332 * mpage_map_buffers - update buffers corresponding to changed extent and
2333 * submit fully mapped pages for IO
2335 * @mpd - description of extent to map, on return next extent to map
2337 * Scan buffers corresponding to changed extent (we expect corresponding pages
2338 * to be already locked) and update buffer state according to new extent state.
2339 * We map delalloc buffers to their physical location, clear unwritten bits,
2340 * and mark buffers as uninit when we perform writes to unwritten extents
2341 * and do extent conversion after IO is finished. If the last page is not fully
2342 * mapped, we update @map to the next extent in the last page that needs
2343 * mapping. Otherwise we submit the page for IO.
2345 static int mpage_map_and_submit_buffers(struct mpage_da_data *mpd)
2347 struct pagevec pvec;
2349 struct inode *inode = mpd->inode;
2350 int bpp_bits = PAGE_SHIFT - inode->i_blkbits;
2353 ext4_fsblk_t pblock;
2355 bool map_bh = false;
2357 start = mpd->map.m_lblk >> bpp_bits;
2358 end = (mpd->map.m_lblk + mpd->map.m_len - 1) >> bpp_bits;
2359 lblk = start << bpp_bits;
2360 pblock = mpd->map.m_pblk;
2362 pagevec_init(&pvec);
2363 while (start <= end) {
2364 nr_pages = pagevec_lookup_range(&pvec, inode->i_mapping,
2368 for (i = 0; i < nr_pages; i++) {
2369 struct page *page = pvec.pages[i];
2371 err = mpage_process_page(mpd, page, &lblk, &pblock,
2374 * If map_bh is true, means page may require further bh
2375 * mapping, or maybe the page was submitted for IO.
2376 * So we return to call further extent mapping.
2378 if (err < 0 || map_bh)
2380 /* Page fully mapped - let IO run! */
2381 err = mpage_submit_page(mpd, page);
2385 pagevec_release(&pvec);
2387 /* Extent fully mapped and matches with page boundary. We are done. */
2389 mpd->map.m_flags = 0;
2392 pagevec_release(&pvec);
2396 static int mpage_map_one_extent(handle_t *handle, struct mpage_da_data *mpd)
2398 struct inode *inode = mpd->inode;
2399 struct ext4_map_blocks *map = &mpd->map;
2400 int get_blocks_flags;
2401 int err, dioread_nolock;
2403 trace_ext4_da_write_pages_extent(inode, map);
2405 * Call ext4_map_blocks() to allocate any delayed allocation blocks, or
2406 * to convert an unwritten extent to be initialized (in the case
2407 * where we have written into one or more preallocated blocks). It is
2408 * possible that we're going to need more metadata blocks than
2409 * previously reserved. However we must not fail because we're in
2410 * writeback and there is nothing we can do about it so it might result
2411 * in data loss. So use reserved blocks to allocate metadata if
2414 * We pass in the magic EXT4_GET_BLOCKS_DELALLOC_RESERVE if
2415 * the blocks in question are delalloc blocks. This indicates
2416 * that the blocks and quotas has already been checked when
2417 * the data was copied into the page cache.
2419 get_blocks_flags = EXT4_GET_BLOCKS_CREATE |
2420 EXT4_GET_BLOCKS_METADATA_NOFAIL |
2421 EXT4_GET_BLOCKS_IO_SUBMIT;
2422 dioread_nolock = ext4_should_dioread_nolock(inode);
2424 get_blocks_flags |= EXT4_GET_BLOCKS_IO_CREATE_EXT;
2425 if (map->m_flags & BIT(BH_Delay))
2426 get_blocks_flags |= EXT4_GET_BLOCKS_DELALLOC_RESERVE;
2428 err = ext4_map_blocks(handle, inode, map, get_blocks_flags);
2431 if (dioread_nolock && (map->m_flags & EXT4_MAP_UNWRITTEN)) {
2432 if (!mpd->io_submit.io_end->handle &&
2433 ext4_handle_valid(handle)) {
2434 mpd->io_submit.io_end->handle = handle->h_rsv_handle;
2435 handle->h_rsv_handle = NULL;
2437 ext4_set_io_unwritten_flag(inode, mpd->io_submit.io_end);
2440 BUG_ON(map->m_len == 0);
2445 * mpage_map_and_submit_extent - map extent starting at mpd->lblk of length
2446 * mpd->len and submit pages underlying it for IO
2448 * @handle - handle for journal operations
2449 * @mpd - extent to map
2450 * @give_up_on_write - we set this to true iff there is a fatal error and there
2451 * is no hope of writing the data. The caller should discard
2452 * dirty pages to avoid infinite loops.
2454 * The function maps extent starting at mpd->lblk of length mpd->len. If it is
2455 * delayed, blocks are allocated, if it is unwritten, we may need to convert
2456 * them to initialized or split the described range from larger unwritten
2457 * extent. Note that we need not map all the described range since allocation
2458 * can return less blocks or the range is covered by more unwritten extents. We
2459 * cannot map more because we are limited by reserved transaction credits. On
2460 * the other hand we always make sure that the last touched page is fully
2461 * mapped so that it can be written out (and thus forward progress is
2462 * guaranteed). After mapping we submit all mapped pages for IO.
2464 static int mpage_map_and_submit_extent(handle_t *handle,
2465 struct mpage_da_data *mpd,
2466 bool *give_up_on_write)
2468 struct inode *inode = mpd->inode;
2469 struct ext4_map_blocks *map = &mpd->map;
2473 ext4_io_end_t *io_end = mpd->io_submit.io_end;
2474 struct ext4_io_end_vec *io_end_vec;
2476 io_end_vec = ext4_alloc_io_end_vec(io_end);
2477 if (IS_ERR(io_end_vec))
2478 return PTR_ERR(io_end_vec);
2479 io_end_vec->offset = ((loff_t)map->m_lblk) << inode->i_blkbits;
2481 err = mpage_map_one_extent(handle, mpd);
2483 struct super_block *sb = inode->i_sb;
2485 if (ext4_forced_shutdown(EXT4_SB(sb)) ||
2486 ext4_test_mount_flag(sb, EXT4_MF_FS_ABORTED))
2487 goto invalidate_dirty_pages;
2489 * Let the uper layers retry transient errors.
2490 * In the case of ENOSPC, if ext4_count_free_blocks()
2491 * is non-zero, a commit should free up blocks.
2493 if ((err == -ENOMEM) ||
2494 (err == -ENOSPC && ext4_count_free_clusters(sb))) {
2496 goto update_disksize;
2499 ext4_msg(sb, KERN_CRIT,
2500 "Delayed block allocation failed for "
2501 "inode %lu at logical offset %llu with"
2502 " max blocks %u with error %d",
2504 (unsigned long long)map->m_lblk,
2505 (unsigned)map->m_len, -err);
2506 ext4_msg(sb, KERN_CRIT,
2507 "This should not happen!! Data will "
2510 ext4_print_free_blocks(inode);
2511 invalidate_dirty_pages:
2512 *give_up_on_write = true;
2517 * Update buffer state, submit mapped pages, and get us new
2520 err = mpage_map_and_submit_buffers(mpd);
2522 goto update_disksize;
2523 } while (map->m_len);
2527 * Update on-disk size after IO is submitted. Races with
2528 * truncate are avoided by checking i_size under i_data_sem.
2530 disksize = ((loff_t)mpd->first_page) << PAGE_SHIFT;
2531 if (disksize > READ_ONCE(EXT4_I(inode)->i_disksize)) {
2535 down_write(&EXT4_I(inode)->i_data_sem);
2536 i_size = i_size_read(inode);
2537 if (disksize > i_size)
2539 if (disksize > EXT4_I(inode)->i_disksize)
2540 EXT4_I(inode)->i_disksize = disksize;
2541 up_write(&EXT4_I(inode)->i_data_sem);
2542 err2 = ext4_mark_inode_dirty(handle, inode);
2544 ext4_error_err(inode->i_sb, -err2,
2545 "Failed to mark inode %lu dirty",
2555 * Calculate the total number of credits to reserve for one writepages
2556 * iteration. This is called from ext4_writepages(). We map an extent of
2557 * up to MAX_WRITEPAGES_EXTENT_LEN blocks and then we go on and finish mapping
2558 * the last partial page. So in total we can map MAX_WRITEPAGES_EXTENT_LEN +
2559 * bpp - 1 blocks in bpp different extents.
2561 static int ext4_da_writepages_trans_blocks(struct inode *inode)
2563 int bpp = ext4_journal_blocks_per_page(inode);
2565 return ext4_meta_trans_blocks(inode,
2566 MAX_WRITEPAGES_EXTENT_LEN + bpp - 1, bpp);
2570 * mpage_prepare_extent_to_map - find & lock contiguous range of dirty pages
2571 * and underlying extent to map
2573 * @mpd - where to look for pages
2575 * Walk dirty pages in the mapping. If they are fully mapped, submit them for
2576 * IO immediately. When we find a page which isn't mapped we start accumulating
2577 * extent of buffers underlying these pages that needs mapping (formed by
2578 * either delayed or unwritten buffers). We also lock the pages containing
2579 * these buffers. The extent found is returned in @mpd structure (starting at
2580 * mpd->lblk with length mpd->len blocks).
2582 * Note that this function can attach bios to one io_end structure which are
2583 * neither logically nor physically contiguous. Although it may seem as an
2584 * unnecessary complication, it is actually inevitable in blocksize < pagesize
2585 * case as we need to track IO to all buffers underlying a page in one io_end.
2587 static int mpage_prepare_extent_to_map(struct mpage_da_data *mpd)
2589 struct address_space *mapping = mpd->inode->i_mapping;
2590 struct pagevec pvec;
2591 unsigned int nr_pages;
2592 long left = mpd->wbc->nr_to_write;
2593 pgoff_t index = mpd->first_page;
2594 pgoff_t end = mpd->last_page;
2597 int blkbits = mpd->inode->i_blkbits;
2599 struct buffer_head *head;
2601 if (mpd->wbc->sync_mode == WB_SYNC_ALL || mpd->wbc->tagged_writepages)
2602 tag = PAGECACHE_TAG_TOWRITE;
2604 tag = PAGECACHE_TAG_DIRTY;
2606 pagevec_init(&pvec);
2608 mpd->next_page = index;
2609 while (index <= end) {
2610 nr_pages = pagevec_lookup_range_tag(&pvec, mapping, &index, end,
2615 for (i = 0; i < nr_pages; i++) {
2616 struct page *page = pvec.pages[i];
2619 * Accumulated enough dirty pages? This doesn't apply
2620 * to WB_SYNC_ALL mode. For integrity sync we have to
2621 * keep going because someone may be concurrently
2622 * dirtying pages, and we might have synced a lot of
2623 * newly appeared dirty pages, but have not synced all
2624 * of the old dirty pages.
2626 if (mpd->wbc->sync_mode == WB_SYNC_NONE && left <= 0)
2629 /* If we can't merge this page, we are done. */
2630 if (mpd->map.m_len > 0 && mpd->next_page != page->index)
2635 * If the page is no longer dirty, or its mapping no
2636 * longer corresponds to inode we are writing (which
2637 * means it has been truncated or invalidated), or the
2638 * page is already under writeback and we are not doing
2639 * a data integrity writeback, skip the page
2641 if (!PageDirty(page) ||
2642 (PageWriteback(page) &&
2643 (mpd->wbc->sync_mode == WB_SYNC_NONE)) ||
2644 unlikely(page->mapping != mapping)) {
2649 wait_on_page_writeback(page);
2650 BUG_ON(PageWriteback(page));
2653 * Should never happen but for buggy code in
2654 * other subsystems that call
2655 * set_page_dirty() without properly warning
2656 * the file system first. See [1] for more
2659 * [1] https://lore.kernel.org/linux-mm/20180103100430.GE4911@quack2.suse.cz
2661 if (!page_has_buffers(page)) {
2662 ext4_warning_inode(mpd->inode, "page %lu does not have buffers attached", page->index);
2663 ClearPageDirty(page);
2668 if (mpd->map.m_len == 0)
2669 mpd->first_page = page->index;
2670 mpd->next_page = page->index + 1;
2671 /* Add all dirty buffers to mpd */
2672 lblk = ((ext4_lblk_t)page->index) <<
2673 (PAGE_SHIFT - blkbits);
2674 head = page_buffers(page);
2675 err = mpage_process_page_bufs(mpd, head, head, lblk);
2681 pagevec_release(&pvec);
2684 mpd->scanned_until_end = 1;
2687 pagevec_release(&pvec);
2691 static int ext4_writepages(struct address_space *mapping,
2692 struct writeback_control *wbc)
2694 pgoff_t writeback_index = 0;
2695 long nr_to_write = wbc->nr_to_write;
2696 int range_whole = 0;
2698 handle_t *handle = NULL;
2699 struct mpage_da_data mpd;
2700 struct inode *inode = mapping->host;
2701 int needed_blocks, rsv_blocks = 0, ret = 0;
2702 struct ext4_sb_info *sbi = EXT4_SB(mapping->host->i_sb);
2703 struct blk_plug plug;
2704 bool give_up_on_write = false;
2706 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
2709 percpu_down_read(&sbi->s_writepages_rwsem);
2710 trace_ext4_writepages(inode, wbc);
2713 * No pages to write? This is mainly a kludge to avoid starting
2714 * a transaction for special inodes like journal inode on last iput()
2715 * because that could violate lock ordering on umount
2717 if (!mapping->nrpages || !mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
2718 goto out_writepages;
2720 if (ext4_should_journal_data(inode)) {
2721 ret = generic_writepages(mapping, wbc);
2722 goto out_writepages;
2726 * If the filesystem has aborted, it is read-only, so return
2727 * right away instead of dumping stack traces later on that
2728 * will obscure the real source of the problem. We test
2729 * EXT4_MF_FS_ABORTED instead of sb->s_flag's SB_RDONLY because
2730 * the latter could be true if the filesystem is mounted
2731 * read-only, and in that case, ext4_writepages should
2732 * *never* be called, so if that ever happens, we would want
2735 if (unlikely(ext4_forced_shutdown(EXT4_SB(mapping->host->i_sb)) ||
2736 ext4_test_mount_flag(inode->i_sb, EXT4_MF_FS_ABORTED))) {
2738 goto out_writepages;
2742 * If we have inline data and arrive here, it means that
2743 * we will soon create the block for the 1st page, so
2744 * we'd better clear the inline data here.
2746 if (ext4_has_inline_data(inode)) {
2747 /* Just inode will be modified... */
2748 handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
2749 if (IS_ERR(handle)) {
2750 ret = PTR_ERR(handle);
2751 goto out_writepages;
2753 BUG_ON(ext4_test_inode_state(inode,
2754 EXT4_STATE_MAY_INLINE_DATA));
2755 ext4_destroy_inline_data(handle, inode);
2756 ext4_journal_stop(handle);
2759 if (ext4_should_dioread_nolock(inode)) {
2761 * We may need to convert up to one extent per block in
2762 * the page and we may dirty the inode.
2764 rsv_blocks = 1 + ext4_chunk_trans_blocks(inode,
2765 PAGE_SIZE >> inode->i_blkbits);
2768 if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
2771 if (wbc->range_cyclic) {
2772 writeback_index = mapping->writeback_index;
2773 if (writeback_index)
2775 mpd.first_page = writeback_index;
2778 mpd.first_page = wbc->range_start >> PAGE_SHIFT;
2779 mpd.last_page = wbc->range_end >> PAGE_SHIFT;
2784 ext4_io_submit_init(&mpd.io_submit, wbc);
2786 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
2787 tag_pages_for_writeback(mapping, mpd.first_page, mpd.last_page);
2788 blk_start_plug(&plug);
2791 * First writeback pages that don't need mapping - we can avoid
2792 * starting a transaction unnecessarily and also avoid being blocked
2793 * in the block layer on device congestion while having transaction
2797 mpd.scanned_until_end = 0;
2798 mpd.io_submit.io_end = ext4_init_io_end(inode, GFP_KERNEL);
2799 if (!mpd.io_submit.io_end) {
2803 ret = mpage_prepare_extent_to_map(&mpd);
2804 /* Unlock pages we didn't use */
2805 mpage_release_unused_pages(&mpd, false);
2806 /* Submit prepared bio */
2807 ext4_io_submit(&mpd.io_submit);
2808 ext4_put_io_end_defer(mpd.io_submit.io_end);
2809 mpd.io_submit.io_end = NULL;
2813 while (!mpd.scanned_until_end && wbc->nr_to_write > 0) {
2814 /* For each extent of pages we use new io_end */
2815 mpd.io_submit.io_end = ext4_init_io_end(inode, GFP_KERNEL);
2816 if (!mpd.io_submit.io_end) {
2822 * We have two constraints: We find one extent to map and we
2823 * must always write out whole page (makes a difference when
2824 * blocksize < pagesize) so that we don't block on IO when we
2825 * try to write out the rest of the page. Journalled mode is
2826 * not supported by delalloc.
2828 BUG_ON(ext4_should_journal_data(inode));
2829 needed_blocks = ext4_da_writepages_trans_blocks(inode);
2831 /* start a new transaction */
2832 handle = ext4_journal_start_with_reserve(inode,
2833 EXT4_HT_WRITE_PAGE, needed_blocks, rsv_blocks);
2834 if (IS_ERR(handle)) {
2835 ret = PTR_ERR(handle);
2836 ext4_msg(inode->i_sb, KERN_CRIT, "%s: jbd2_start: "
2837 "%ld pages, ino %lu; err %d", __func__,
2838 wbc->nr_to_write, inode->i_ino, ret);
2839 /* Release allocated io_end */
2840 ext4_put_io_end(mpd.io_submit.io_end);
2841 mpd.io_submit.io_end = NULL;
2846 trace_ext4_da_write_pages(inode, mpd.first_page, mpd.wbc);
2847 ret = mpage_prepare_extent_to_map(&mpd);
2848 if (!ret && mpd.map.m_len)
2849 ret = mpage_map_and_submit_extent(handle, &mpd,
2852 * Caution: If the handle is synchronous,
2853 * ext4_journal_stop() can wait for transaction commit
2854 * to finish which may depend on writeback of pages to
2855 * complete or on page lock to be released. In that
2856 * case, we have to wait until after we have
2857 * submitted all the IO, released page locks we hold,
2858 * and dropped io_end reference (for extent conversion
2859 * to be able to complete) before stopping the handle.
2861 if (!ext4_handle_valid(handle) || handle->h_sync == 0) {
2862 ext4_journal_stop(handle);
2866 /* Unlock pages we didn't use */
2867 mpage_release_unused_pages(&mpd, give_up_on_write);
2868 /* Submit prepared bio */
2869 ext4_io_submit(&mpd.io_submit);
2872 * Drop our io_end reference we got from init. We have
2873 * to be careful and use deferred io_end finishing if
2874 * we are still holding the transaction as we can
2875 * release the last reference to io_end which may end
2876 * up doing unwritten extent conversion.
2879 ext4_put_io_end_defer(mpd.io_submit.io_end);
2880 ext4_journal_stop(handle);
2882 ext4_put_io_end(mpd.io_submit.io_end);
2883 mpd.io_submit.io_end = NULL;
2885 if (ret == -ENOSPC && sbi->s_journal) {
2887 * Commit the transaction which would
2888 * free blocks released in the transaction
2891 jbd2_journal_force_commit_nested(sbi->s_journal);
2895 /* Fatal error - ENOMEM, EIO... */
2900 blk_finish_plug(&plug);
2901 if (!ret && !cycled && wbc->nr_to_write > 0) {
2903 mpd.last_page = writeback_index - 1;
2909 if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
2911 * Set the writeback_index so that range_cyclic
2912 * mode will write it back later
2914 mapping->writeback_index = mpd.first_page;
2917 trace_ext4_writepages_result(inode, wbc, ret,
2918 nr_to_write - wbc->nr_to_write);
2919 percpu_up_read(&sbi->s_writepages_rwsem);
2923 static int ext4_dax_writepages(struct address_space *mapping,
2924 struct writeback_control *wbc)
2927 long nr_to_write = wbc->nr_to_write;
2928 struct inode *inode = mapping->host;
2929 struct ext4_sb_info *sbi = EXT4_SB(mapping->host->i_sb);
2931 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
2934 percpu_down_read(&sbi->s_writepages_rwsem);
2935 trace_ext4_writepages(inode, wbc);
2937 ret = dax_writeback_mapping_range(mapping, sbi->s_daxdev, wbc);
2938 trace_ext4_writepages_result(inode, wbc, ret,
2939 nr_to_write - wbc->nr_to_write);
2940 percpu_up_read(&sbi->s_writepages_rwsem);
2944 static int ext4_nonda_switch(struct super_block *sb)
2946 s64 free_clusters, dirty_clusters;
2947 struct ext4_sb_info *sbi = EXT4_SB(sb);
2950 * switch to non delalloc mode if we are running low
2951 * on free block. The free block accounting via percpu
2952 * counters can get slightly wrong with percpu_counter_batch getting
2953 * accumulated on each CPU without updating global counters
2954 * Delalloc need an accurate free block accounting. So switch
2955 * to non delalloc when we are near to error range.
2958 percpu_counter_read_positive(&sbi->s_freeclusters_counter);
2960 percpu_counter_read_positive(&sbi->s_dirtyclusters_counter);
2962 * Start pushing delalloc when 1/2 of free blocks are dirty.
2964 if (dirty_clusters && (free_clusters < 2 * dirty_clusters))
2965 try_to_writeback_inodes_sb(sb, WB_REASON_FS_FREE_SPACE);
2967 if (2 * free_clusters < 3 * dirty_clusters ||
2968 free_clusters < (dirty_clusters + EXT4_FREECLUSTERS_WATERMARK)) {
2970 * free block count is less than 150% of dirty blocks
2971 * or free blocks is less than watermark
2978 /* We always reserve for an inode update; the superblock could be there too */
2979 static int ext4_da_write_credits(struct inode *inode, loff_t pos, unsigned len)
2981 if (likely(ext4_has_feature_large_file(inode->i_sb)))
2984 if (pos + len <= 0x7fffffffULL)
2987 /* We might need to update the superblock to set LARGE_FILE */
2991 static int ext4_da_write_begin(struct file *file, struct address_space *mapping,
2992 loff_t pos, unsigned len, unsigned flags,
2993 struct page **pagep, void **fsdata)
2995 int ret, retries = 0;
2998 struct inode *inode = mapping->host;
3001 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
3004 index = pos >> PAGE_SHIFT;
3006 if (ext4_nonda_switch(inode->i_sb) || S_ISLNK(inode->i_mode) ||
3007 ext4_verity_in_progress(inode)) {
3008 *fsdata = (void *)FALL_BACK_TO_NONDELALLOC;
3009 return ext4_write_begin(file, mapping, pos,
3010 len, flags, pagep, fsdata);
3012 *fsdata = (void *)0;
3013 trace_ext4_da_write_begin(inode, pos, len, flags);
3015 if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
3016 ret = ext4_da_write_inline_data_begin(mapping, inode,
3026 * grab_cache_page_write_begin() can take a long time if the
3027 * system is thrashing due to memory pressure, or if the page
3028 * is being written back. So grab it first before we start
3029 * the transaction handle. This also allows us to allocate
3030 * the page (if needed) without using GFP_NOFS.
3033 page = grab_cache_page_write_begin(mapping, index, flags);
3039 * With delayed allocation, we don't log the i_disksize update
3040 * if there is delayed block allocation. But we still need
3041 * to journalling the i_disksize update if writes to the end
3042 * of file which has an already mapped buffer.
3045 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
3046 ext4_da_write_credits(inode, pos, len));
3047 if (IS_ERR(handle)) {
3049 return PTR_ERR(handle);
3053 if (page->mapping != mapping) {
3054 /* The page got truncated from under us */
3057 ext4_journal_stop(handle);
3060 /* In case writeback began while the page was unlocked */
3061 wait_for_stable_page(page);
3063 #ifdef CONFIG_FS_ENCRYPTION
3064 ret = ext4_block_write_begin(page, pos, len,
3065 ext4_da_get_block_prep);
3067 ret = __block_write_begin(page, pos, len, ext4_da_get_block_prep);
3071 ext4_journal_stop(handle);
3073 * block_write_begin may have instantiated a few blocks
3074 * outside i_size. Trim these off again. Don't need
3075 * i_size_read because we hold i_mutex.
3077 if (pos + len > inode->i_size)
3078 ext4_truncate_failed_write(inode);
3080 if (ret == -ENOSPC &&
3081 ext4_should_retry_alloc(inode->i_sb, &retries))
3093 * Check if we should update i_disksize
3094 * when write to the end of file but not require block allocation
3096 static int ext4_da_should_update_i_disksize(struct page *page,
3097 unsigned long offset)
3099 struct buffer_head *bh;
3100 struct inode *inode = page->mapping->host;
3104 bh = page_buffers(page);
3105 idx = offset >> inode->i_blkbits;
3107 for (i = 0; i < idx; i++)
3108 bh = bh->b_this_page;
3110 if (!buffer_mapped(bh) || (buffer_delay(bh)) || buffer_unwritten(bh))
3115 static int ext4_da_write_end(struct file *file,
3116 struct address_space *mapping,
3117 loff_t pos, unsigned len, unsigned copied,
3118 struct page *page, void *fsdata)
3120 struct inode *inode = mapping->host;
3122 handle_t *handle = ext4_journal_current_handle();
3124 unsigned long start, end;
3125 int write_mode = (int)(unsigned long)fsdata;
3127 if (write_mode == FALL_BACK_TO_NONDELALLOC)
3128 return ext4_write_end(file, mapping, pos,
3129 len, copied, page, fsdata);
3131 trace_ext4_da_write_end(inode, pos, len, copied);
3132 start = pos & (PAGE_SIZE - 1);
3133 end = start + copied - 1;
3136 * Since we are holding inode lock, we are sure i_disksize <=
3137 * i_size. We also know that if i_disksize < i_size, there are
3138 * delalloc writes pending in the range upto i_size. If the end of
3139 * the current write is <= i_size, there's no need to touch
3140 * i_disksize since writeback will push i_disksize upto i_size
3141 * eventually. If the end of the current write is > i_size and
3142 * inside an allocated block (ext4_da_should_update_i_disksize()
3143 * check), we need to update i_disksize here as neither
3144 * ext4_writepage() nor certain ext4_writepages() paths not
3145 * allocating blocks update i_disksize.
3147 * Note that we defer inode dirtying to generic_write_end() /
3148 * ext4_da_write_inline_data_end().
3150 new_i_size = pos + copied;
3151 if (copied && new_i_size > inode->i_size) {
3152 if (ext4_has_inline_data(inode) ||
3153 ext4_da_should_update_i_disksize(page, end))
3154 ext4_update_i_disksize(inode, new_i_size);
3157 if (write_mode != CONVERT_INLINE_DATA &&
3158 ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA) &&
3159 ext4_has_inline_data(inode))
3160 ret = ext4_da_write_inline_data_end(inode, pos, len, copied,
3163 ret = generic_write_end(file, mapping, pos, len, copied,
3167 ret2 = ext4_journal_stop(handle);
3168 if (unlikely(ret2 && !ret))
3171 return ret ? ret : copied;
3175 * Force all delayed allocation blocks to be allocated for a given inode.
3177 int ext4_alloc_da_blocks(struct inode *inode)
3179 trace_ext4_alloc_da_blocks(inode);
3181 if (!EXT4_I(inode)->i_reserved_data_blocks)
3185 * We do something simple for now. The filemap_flush() will
3186 * also start triggering a write of the data blocks, which is
3187 * not strictly speaking necessary (and for users of
3188 * laptop_mode, not even desirable). However, to do otherwise
3189 * would require replicating code paths in:
3191 * ext4_writepages() ->
3192 * write_cache_pages() ---> (via passed in callback function)
3193 * __mpage_da_writepage() -->
3194 * mpage_add_bh_to_extent()
3195 * mpage_da_map_blocks()
3197 * The problem is that write_cache_pages(), located in
3198 * mm/page-writeback.c, marks pages clean in preparation for
3199 * doing I/O, which is not desirable if we're not planning on
3202 * We could call write_cache_pages(), and then redirty all of
3203 * the pages by calling redirty_page_for_writepage() but that
3204 * would be ugly in the extreme. So instead we would need to
3205 * replicate parts of the code in the above functions,
3206 * simplifying them because we wouldn't actually intend to
3207 * write out the pages, but rather only collect contiguous
3208 * logical block extents, call the multi-block allocator, and
3209 * then update the buffer heads with the block allocations.
3211 * For now, though, we'll cheat by calling filemap_flush(),
3212 * which will map the blocks, and start the I/O, but not
3213 * actually wait for the I/O to complete.
3215 return filemap_flush(inode->i_mapping);
3219 * bmap() is special. It gets used by applications such as lilo and by
3220 * the swapper to find the on-disk block of a specific piece of data.
3222 * Naturally, this is dangerous if the block concerned is still in the
3223 * journal. If somebody makes a swapfile on an ext4 data-journaling
3224 * filesystem and enables swap, then they may get a nasty shock when the
3225 * data getting swapped to that swapfile suddenly gets overwritten by
3226 * the original zero's written out previously to the journal and
3227 * awaiting writeback in the kernel's buffer cache.
3229 * So, if we see any bmap calls here on a modified, data-journaled file,
3230 * take extra steps to flush any blocks which might be in the cache.
3232 static sector_t ext4_bmap(struct address_space *mapping, sector_t block)
3234 struct inode *inode = mapping->host;
3239 inode_lock_shared(inode);
3241 * We can get here for an inline file via the FIBMAP ioctl
3243 if (ext4_has_inline_data(inode))
3246 if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY) &&
3247 test_opt(inode->i_sb, DELALLOC)) {
3249 * With delalloc we want to sync the file
3250 * so that we can make sure we allocate
3253 filemap_write_and_wait(mapping);
3256 if (EXT4_JOURNAL(inode) &&
3257 ext4_test_inode_state(inode, EXT4_STATE_JDATA)) {
3259 * This is a REALLY heavyweight approach, but the use of
3260 * bmap on dirty files is expected to be extremely rare:
3261 * only if we run lilo or swapon on a freshly made file
3262 * do we expect this to happen.
3264 * (bmap requires CAP_SYS_RAWIO so this does not
3265 * represent an unprivileged user DOS attack --- we'd be
3266 * in trouble if mortal users could trigger this path at
3269 * NB. EXT4_STATE_JDATA is not set on files other than
3270 * regular files. If somebody wants to bmap a directory
3271 * or symlink and gets confused because the buffer
3272 * hasn't yet been flushed to disk, they deserve
3273 * everything they get.
3276 ext4_clear_inode_state(inode, EXT4_STATE_JDATA);
3277 journal = EXT4_JOURNAL(inode);
3278 jbd2_journal_lock_updates(journal);
3279 err = jbd2_journal_flush(journal);
3280 jbd2_journal_unlock_updates(journal);
3286 ret = iomap_bmap(mapping, block, &ext4_iomap_ops);
3289 inode_unlock_shared(inode);
3293 static int ext4_readpage(struct file *file, struct page *page)
3296 struct inode *inode = page->mapping->host;
3298 trace_ext4_readpage(page);
3300 if (ext4_has_inline_data(inode))
3301 ret = ext4_readpage_inline(inode, page);
3304 return ext4_mpage_readpages(inode, NULL, page);
3309 static void ext4_readahead(struct readahead_control *rac)
3311 struct inode *inode = rac->mapping->host;
3313 /* If the file has inline data, no need to do readahead. */
3314 if (ext4_has_inline_data(inode))
3317 ext4_mpage_readpages(inode, rac, NULL);
3320 static void ext4_invalidatepage(struct page *page, unsigned int offset,
3321 unsigned int length)
3323 trace_ext4_invalidatepage(page, offset, length);
3325 /* No journalling happens on data buffers when this function is used */
3326 WARN_ON(page_has_buffers(page) && buffer_jbd(page_buffers(page)));
3328 block_invalidatepage(page, offset, length);
3331 static int __ext4_journalled_invalidatepage(struct page *page,
3332 unsigned int offset,
3333 unsigned int length)
3335 journal_t *journal = EXT4_JOURNAL(page->mapping->host);
3337 trace_ext4_journalled_invalidatepage(page, offset, length);
3340 * If it's a full truncate we just forget about the pending dirtying
3342 if (offset == 0 && length == PAGE_SIZE)
3343 ClearPageChecked(page);
3345 return jbd2_journal_invalidatepage(journal, page, offset, length);
3348 /* Wrapper for aops... */
3349 static void ext4_journalled_invalidatepage(struct page *page,
3350 unsigned int offset,
3351 unsigned int length)
3353 WARN_ON(__ext4_journalled_invalidatepage(page, offset, length) < 0);
3356 static int ext4_releasepage(struct page *page, gfp_t wait)
3358 journal_t *journal = EXT4_JOURNAL(page->mapping->host);
3360 trace_ext4_releasepage(page);
3362 /* Page has dirty journalled data -> cannot release */
3363 if (PageChecked(page))
3366 return jbd2_journal_try_to_free_buffers(journal, page);
3368 return try_to_free_buffers(page);
3371 static bool ext4_inode_datasync_dirty(struct inode *inode)
3373 journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
3376 if (jbd2_transaction_committed(journal,
3377 EXT4_I(inode)->i_datasync_tid))
3379 if (test_opt2(inode->i_sb, JOURNAL_FAST_COMMIT))
3380 return !list_empty(&EXT4_I(inode)->i_fc_list);
3384 /* Any metadata buffers to write? */
3385 if (!list_empty(&inode->i_mapping->private_list))
3387 return inode->i_state & I_DIRTY_DATASYNC;
3390 static void ext4_set_iomap(struct inode *inode, struct iomap *iomap,
3391 struct ext4_map_blocks *map, loff_t offset,
3394 u8 blkbits = inode->i_blkbits;
3397 * Writes that span EOF might trigger an I/O size update on completion,
3398 * so consider them to be dirty for the purpose of O_DSYNC, even if
3399 * there is no other metadata changes being made or are pending.
3402 if (ext4_inode_datasync_dirty(inode) ||
3403 offset + length > i_size_read(inode))
3404 iomap->flags |= IOMAP_F_DIRTY;
3406 if (map->m_flags & EXT4_MAP_NEW)
3407 iomap->flags |= IOMAP_F_NEW;
3409 iomap->bdev = inode->i_sb->s_bdev;
3410 iomap->dax_dev = EXT4_SB(inode->i_sb)->s_daxdev;
3411 iomap->offset = (u64) map->m_lblk << blkbits;
3412 iomap->length = (u64) map->m_len << blkbits;
3414 if ((map->m_flags & EXT4_MAP_MAPPED) &&
3415 !ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3416 iomap->flags |= IOMAP_F_MERGED;
3419 * Flags passed to ext4_map_blocks() for direct I/O writes can result
3420 * in m_flags having both EXT4_MAP_MAPPED and EXT4_MAP_UNWRITTEN bits
3421 * set. In order for any allocated unwritten extents to be converted
3422 * into written extents correctly within the ->end_io() handler, we
3423 * need to ensure that the iomap->type is set appropriately. Hence, the
3424 * reason why we need to check whether the EXT4_MAP_UNWRITTEN bit has
3427 if (map->m_flags & EXT4_MAP_UNWRITTEN) {
3428 iomap->type = IOMAP_UNWRITTEN;
3429 iomap->addr = (u64) map->m_pblk << blkbits;
3430 } else if (map->m_flags & EXT4_MAP_MAPPED) {
3431 iomap->type = IOMAP_MAPPED;
3432 iomap->addr = (u64) map->m_pblk << blkbits;
3434 iomap->type = IOMAP_HOLE;
3435 iomap->addr = IOMAP_NULL_ADDR;
3439 static int ext4_iomap_alloc(struct inode *inode, struct ext4_map_blocks *map,
3443 u8 blkbits = inode->i_blkbits;
3444 int ret, dio_credits, m_flags = 0, retries = 0;
3447 * Trim the mapping request to the maximum value that we can map at
3448 * once for direct I/O.
3450 if (map->m_len > DIO_MAX_BLOCKS)
3451 map->m_len = DIO_MAX_BLOCKS;
3452 dio_credits = ext4_chunk_trans_blocks(inode, map->m_len);
3456 * Either we allocate blocks and then don't get an unwritten extent, so
3457 * in that case we have reserved enough credits. Or, the blocks are
3458 * already allocated and unwritten. In that case, the extent conversion
3459 * fits into the credits as well.
3461 handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS, dio_credits);
3463 return PTR_ERR(handle);
3466 * DAX and direct I/O are the only two operations that are currently
3467 * supported with IOMAP_WRITE.
3469 WARN_ON(!IS_DAX(inode) && !(flags & IOMAP_DIRECT));
3471 m_flags = EXT4_GET_BLOCKS_CREATE_ZERO;
3473 * We use i_size instead of i_disksize here because delalloc writeback
3474 * can complete at any point during the I/O and subsequently push the
3475 * i_disksize out to i_size. This could be beyond where direct I/O is
3476 * happening and thus expose allocated blocks to direct I/O reads.
3478 else if (((loff_t)map->m_lblk << blkbits) >= i_size_read(inode))
3479 m_flags = EXT4_GET_BLOCKS_CREATE;
3480 else if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3481 m_flags = EXT4_GET_BLOCKS_IO_CREATE_EXT;
3483 ret = ext4_map_blocks(handle, inode, map, m_flags);
3486 * We cannot fill holes in indirect tree based inodes as that could
3487 * expose stale data in the case of a crash. Use the magic error code
3488 * to fallback to buffered I/O.
3490 if (!m_flags && !ret)
3493 ext4_journal_stop(handle);
3494 if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
3501 static int ext4_iomap_begin(struct inode *inode, loff_t offset, loff_t length,
3502 unsigned flags, struct iomap *iomap, struct iomap *srcmap)
3505 struct ext4_map_blocks map;
3506 u8 blkbits = inode->i_blkbits;
3508 if ((offset >> blkbits) > EXT4_MAX_LOGICAL_BLOCK)
3511 if (WARN_ON_ONCE(ext4_has_inline_data(inode)))
3515 * Calculate the first and last logical blocks respectively.
3517 map.m_lblk = offset >> blkbits;
3518 map.m_len = min_t(loff_t, (offset + length - 1) >> blkbits,
3519 EXT4_MAX_LOGICAL_BLOCK) - map.m_lblk + 1;
3521 if (flags & IOMAP_WRITE) {
3523 * We check here if the blocks are already allocated, then we
3524 * don't need to start a journal txn and we can directly return
3525 * the mapping information. This could boost performance
3526 * especially in multi-threaded overwrite requests.
3528 if (offset + length <= i_size_read(inode)) {
3529 ret = ext4_map_blocks(NULL, inode, &map, 0);
3530 if (ret > 0 && (map.m_flags & EXT4_MAP_MAPPED))
3533 ret = ext4_iomap_alloc(inode, &map, flags);
3535 ret = ext4_map_blocks(NULL, inode, &map, 0);
3541 ext4_set_iomap(inode, iomap, &map, offset, length);
3546 static int ext4_iomap_overwrite_begin(struct inode *inode, loff_t offset,
3547 loff_t length, unsigned flags, struct iomap *iomap,
3548 struct iomap *srcmap)
3553 * Even for writes we don't need to allocate blocks, so just pretend
3554 * we are reading to save overhead of starting a transaction.
3556 flags &= ~IOMAP_WRITE;
3557 ret = ext4_iomap_begin(inode, offset, length, flags, iomap, srcmap);
3558 WARN_ON_ONCE(iomap->type != IOMAP_MAPPED);
3562 static int ext4_iomap_end(struct inode *inode, loff_t offset, loff_t length,
3563 ssize_t written, unsigned flags, struct iomap *iomap)
3566 * Check to see whether an error occurred while writing out the data to
3567 * the allocated blocks. If so, return the magic error code so that we
3568 * fallback to buffered I/O and attempt to complete the remainder of
3569 * the I/O. Any blocks that may have been allocated in preparation for
3570 * the direct I/O will be reused during buffered I/O.
3572 if (flags & (IOMAP_WRITE | IOMAP_DIRECT) && written == 0)
3578 const struct iomap_ops ext4_iomap_ops = {
3579 .iomap_begin = ext4_iomap_begin,
3580 .iomap_end = ext4_iomap_end,
3583 const struct iomap_ops ext4_iomap_overwrite_ops = {
3584 .iomap_begin = ext4_iomap_overwrite_begin,
3585 .iomap_end = ext4_iomap_end,
3588 static bool ext4_iomap_is_delalloc(struct inode *inode,
3589 struct ext4_map_blocks *map)
3591 struct extent_status es;
3592 ext4_lblk_t offset = 0, end = map->m_lblk + map->m_len - 1;
3594 ext4_es_find_extent_range(inode, &ext4_es_is_delayed,
3595 map->m_lblk, end, &es);
3597 if (!es.es_len || es.es_lblk > end)
3600 if (es.es_lblk > map->m_lblk) {
3601 map->m_len = es.es_lblk - map->m_lblk;
3605 offset = map->m_lblk - es.es_lblk;
3606 map->m_len = es.es_len - offset;
3611 static int ext4_iomap_begin_report(struct inode *inode, loff_t offset,
3612 loff_t length, unsigned int flags,
3613 struct iomap *iomap, struct iomap *srcmap)
3616 bool delalloc = false;
3617 struct ext4_map_blocks map;
3618 u8 blkbits = inode->i_blkbits;
3620 if ((offset >> blkbits) > EXT4_MAX_LOGICAL_BLOCK)
3623 if (ext4_has_inline_data(inode)) {
3624 ret = ext4_inline_data_iomap(inode, iomap);
3625 if (ret != -EAGAIN) {
3626 if (ret == 0 && offset >= iomap->length)
3633 * Calculate the first and last logical block respectively.
3635 map.m_lblk = offset >> blkbits;
3636 map.m_len = min_t(loff_t, (offset + length - 1) >> blkbits,
3637 EXT4_MAX_LOGICAL_BLOCK) - map.m_lblk + 1;
3640 * Fiemap callers may call for offset beyond s_bitmap_maxbytes.
3641 * So handle it here itself instead of querying ext4_map_blocks().
3642 * Since ext4_map_blocks() will warn about it and will return
3645 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
3646 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
3648 if (offset >= sbi->s_bitmap_maxbytes) {
3654 ret = ext4_map_blocks(NULL, inode, &map, 0);
3658 delalloc = ext4_iomap_is_delalloc(inode, &map);
3661 ext4_set_iomap(inode, iomap, &map, offset, length);
3662 if (delalloc && iomap->type == IOMAP_HOLE)
3663 iomap->type = IOMAP_DELALLOC;
3668 const struct iomap_ops ext4_iomap_report_ops = {
3669 .iomap_begin = ext4_iomap_begin_report,
3673 * Pages can be marked dirty completely asynchronously from ext4's journalling
3674 * activity. By filemap_sync_pte(), try_to_unmap_one(), etc. We cannot do
3675 * much here because ->set_page_dirty is called under VFS locks. The page is
3676 * not necessarily locked.
3678 * We cannot just dirty the page and leave attached buffers clean, because the
3679 * buffers' dirty state is "definitive". We cannot just set the buffers dirty
3680 * or jbddirty because all the journalling code will explode.
3682 * So what we do is to mark the page "pending dirty" and next time writepage
3683 * is called, propagate that into the buffers appropriately.
3685 static int ext4_journalled_set_page_dirty(struct page *page)
3687 SetPageChecked(page);
3688 return __set_page_dirty_nobuffers(page);
3691 static int ext4_set_page_dirty(struct page *page)
3693 WARN_ON_ONCE(!PageLocked(page) && !PageDirty(page));
3694 WARN_ON_ONCE(!page_has_buffers(page));
3695 return __set_page_dirty_buffers(page);
3698 static int ext4_iomap_swap_activate(struct swap_info_struct *sis,
3699 struct file *file, sector_t *span)
3701 return iomap_swapfile_activate(sis, file, span,
3702 &ext4_iomap_report_ops);
3705 static const struct address_space_operations ext4_aops = {
3706 .readpage = ext4_readpage,
3707 .readahead = ext4_readahead,
3708 .writepage = ext4_writepage,
3709 .writepages = ext4_writepages,
3710 .write_begin = ext4_write_begin,
3711 .write_end = ext4_write_end,
3712 .set_page_dirty = ext4_set_page_dirty,
3714 .invalidatepage = ext4_invalidatepage,
3715 .releasepage = ext4_releasepage,
3716 .direct_IO = noop_direct_IO,
3717 .migratepage = buffer_migrate_page,
3718 .is_partially_uptodate = block_is_partially_uptodate,
3719 .error_remove_page = generic_error_remove_page,
3720 .swap_activate = ext4_iomap_swap_activate,
3723 static const struct address_space_operations ext4_journalled_aops = {
3724 .readpage = ext4_readpage,
3725 .readahead = ext4_readahead,
3726 .writepage = ext4_writepage,
3727 .writepages = ext4_writepages,
3728 .write_begin = ext4_write_begin,
3729 .write_end = ext4_journalled_write_end,
3730 .set_page_dirty = ext4_journalled_set_page_dirty,
3732 .invalidatepage = ext4_journalled_invalidatepage,
3733 .releasepage = ext4_releasepage,
3734 .direct_IO = noop_direct_IO,
3735 .is_partially_uptodate = block_is_partially_uptodate,
3736 .error_remove_page = generic_error_remove_page,
3737 .swap_activate = ext4_iomap_swap_activate,
3740 static const struct address_space_operations ext4_da_aops = {
3741 .readpage = ext4_readpage,
3742 .readahead = ext4_readahead,
3743 .writepage = ext4_writepage,
3744 .writepages = ext4_writepages,
3745 .write_begin = ext4_da_write_begin,
3746 .write_end = ext4_da_write_end,
3747 .set_page_dirty = ext4_set_page_dirty,
3749 .invalidatepage = ext4_invalidatepage,
3750 .releasepage = ext4_releasepage,
3751 .direct_IO = noop_direct_IO,
3752 .migratepage = buffer_migrate_page,
3753 .is_partially_uptodate = block_is_partially_uptodate,
3754 .error_remove_page = generic_error_remove_page,
3755 .swap_activate = ext4_iomap_swap_activate,
3758 static const struct address_space_operations ext4_dax_aops = {
3759 .writepages = ext4_dax_writepages,
3760 .direct_IO = noop_direct_IO,
3761 .set_page_dirty = noop_set_page_dirty,
3763 .invalidatepage = noop_invalidatepage,
3764 .swap_activate = ext4_iomap_swap_activate,
3767 void ext4_set_aops(struct inode *inode)
3769 switch (ext4_inode_journal_mode(inode)) {
3770 case EXT4_INODE_ORDERED_DATA_MODE:
3771 case EXT4_INODE_WRITEBACK_DATA_MODE:
3773 case EXT4_INODE_JOURNAL_DATA_MODE:
3774 inode->i_mapping->a_ops = &ext4_journalled_aops;
3780 inode->i_mapping->a_ops = &ext4_dax_aops;
3781 else if (test_opt(inode->i_sb, DELALLOC))
3782 inode->i_mapping->a_ops = &ext4_da_aops;
3784 inode->i_mapping->a_ops = &ext4_aops;
3787 static int __ext4_block_zero_page_range(handle_t *handle,
3788 struct address_space *mapping, loff_t from, loff_t length)
3790 ext4_fsblk_t index = from >> PAGE_SHIFT;
3791 unsigned offset = from & (PAGE_SIZE-1);
3792 unsigned blocksize, pos;
3794 struct inode *inode = mapping->host;
3795 struct buffer_head *bh;
3799 page = find_or_create_page(mapping, from >> PAGE_SHIFT,
3800 mapping_gfp_constraint(mapping, ~__GFP_FS));
3804 blocksize = inode->i_sb->s_blocksize;
3806 iblock = index << (PAGE_SHIFT - inode->i_sb->s_blocksize_bits);
3808 if (!page_has_buffers(page))
3809 create_empty_buffers(page, blocksize, 0);
3811 /* Find the buffer that contains "offset" */
3812 bh = page_buffers(page);
3814 while (offset >= pos) {
3815 bh = bh->b_this_page;
3819 if (buffer_freed(bh)) {
3820 BUFFER_TRACE(bh, "freed: skip");
3823 if (!buffer_mapped(bh)) {
3824 BUFFER_TRACE(bh, "unmapped");
3825 ext4_get_block(inode, iblock, bh, 0);
3826 /* unmapped? It's a hole - nothing to do */
3827 if (!buffer_mapped(bh)) {
3828 BUFFER_TRACE(bh, "still unmapped");
3833 /* Ok, it's mapped. Make sure it's up-to-date */
3834 if (PageUptodate(page))
3835 set_buffer_uptodate(bh);
3837 if (!buffer_uptodate(bh)) {
3838 err = ext4_read_bh_lock(bh, 0, true);
3841 if (fscrypt_inode_uses_fs_layer_crypto(inode)) {
3842 /* We expect the key to be set. */
3843 BUG_ON(!fscrypt_has_encryption_key(inode));
3844 err = fscrypt_decrypt_pagecache_blocks(page, blocksize,
3847 clear_buffer_uptodate(bh);
3852 if (ext4_should_journal_data(inode)) {
3853 BUFFER_TRACE(bh, "get write access");
3854 err = ext4_journal_get_write_access(handle, bh);
3858 zero_user(page, offset, length);
3859 BUFFER_TRACE(bh, "zeroed end of block");
3861 if (ext4_should_journal_data(inode)) {
3862 err = ext4_handle_dirty_metadata(handle, inode, bh);
3865 mark_buffer_dirty(bh);
3866 if (ext4_should_order_data(inode))
3867 err = ext4_jbd2_inode_add_write(handle, inode, from,
3878 * ext4_block_zero_page_range() zeros out a mapping of length 'length'
3879 * starting from file offset 'from'. The range to be zero'd must
3880 * be contained with in one block. If the specified range exceeds
3881 * the end of the block it will be shortened to end of the block
3882 * that cooresponds to 'from'
3884 static int ext4_block_zero_page_range(handle_t *handle,
3885 struct address_space *mapping, loff_t from, loff_t length)
3887 struct inode *inode = mapping->host;
3888 unsigned offset = from & (PAGE_SIZE-1);
3889 unsigned blocksize = inode->i_sb->s_blocksize;
3890 unsigned max = blocksize - (offset & (blocksize - 1));
3893 * correct length if it does not fall between
3894 * 'from' and the end of the block
3896 if (length > max || length < 0)
3899 if (IS_DAX(inode)) {
3900 return iomap_zero_range(inode, from, length, NULL,
3903 return __ext4_block_zero_page_range(handle, mapping, from, length);
3907 * ext4_block_truncate_page() zeroes out a mapping from file offset `from'
3908 * up to the end of the block which corresponds to `from'.
3909 * This required during truncate. We need to physically zero the tail end
3910 * of that block so it doesn't yield old data if the file is later grown.
3912 static int ext4_block_truncate_page(handle_t *handle,
3913 struct address_space *mapping, loff_t from)
3915 unsigned offset = from & (PAGE_SIZE-1);
3918 struct inode *inode = mapping->host;
3920 /* If we are processing an encrypted inode during orphan list handling */
3921 if (IS_ENCRYPTED(inode) && !fscrypt_has_encryption_key(inode))
3924 blocksize = inode->i_sb->s_blocksize;
3925 length = blocksize - (offset & (blocksize - 1));
3927 return ext4_block_zero_page_range(handle, mapping, from, length);
3930 int ext4_zero_partial_blocks(handle_t *handle, struct inode *inode,
3931 loff_t lstart, loff_t length)
3933 struct super_block *sb = inode->i_sb;
3934 struct address_space *mapping = inode->i_mapping;
3935 unsigned partial_start, partial_end;
3936 ext4_fsblk_t start, end;
3937 loff_t byte_end = (lstart + length - 1);
3940 partial_start = lstart & (sb->s_blocksize - 1);
3941 partial_end = byte_end & (sb->s_blocksize - 1);
3943 start = lstart >> sb->s_blocksize_bits;
3944 end = byte_end >> sb->s_blocksize_bits;
3946 /* Handle partial zero within the single block */
3948 (partial_start || (partial_end != sb->s_blocksize - 1))) {
3949 err = ext4_block_zero_page_range(handle, mapping,
3953 /* Handle partial zero out on the start of the range */
3954 if (partial_start) {
3955 err = ext4_block_zero_page_range(handle, mapping,
3956 lstart, sb->s_blocksize);
3960 /* Handle partial zero out on the end of the range */
3961 if (partial_end != sb->s_blocksize - 1)
3962 err = ext4_block_zero_page_range(handle, mapping,
3963 byte_end - partial_end,
3968 int ext4_can_truncate(struct inode *inode)
3970 if (S_ISREG(inode->i_mode))
3972 if (S_ISDIR(inode->i_mode))
3974 if (S_ISLNK(inode->i_mode))
3975 return !ext4_inode_is_fast_symlink(inode);
3980 * We have to make sure i_disksize gets properly updated before we truncate
3981 * page cache due to hole punching or zero range. Otherwise i_disksize update
3982 * can get lost as it may have been postponed to submission of writeback but
3983 * that will never happen after we truncate page cache.
3985 int ext4_update_disksize_before_punch(struct inode *inode, loff_t offset,
3991 loff_t size = i_size_read(inode);
3993 WARN_ON(!inode_is_locked(inode));
3994 if (offset > size || offset + len < size)
3997 if (EXT4_I(inode)->i_disksize >= size)
4000 handle = ext4_journal_start(inode, EXT4_HT_MISC, 1);
4002 return PTR_ERR(handle);
4003 ext4_update_i_disksize(inode, size);
4004 ret = ext4_mark_inode_dirty(handle, inode);
4005 ext4_journal_stop(handle);
4010 static void ext4_wait_dax_page(struct ext4_inode_info *ei)
4012 up_write(&ei->i_mmap_sem);
4014 down_write(&ei->i_mmap_sem);
4017 int ext4_break_layouts(struct inode *inode)
4019 struct ext4_inode_info *ei = EXT4_I(inode);
4023 if (WARN_ON_ONCE(!rwsem_is_locked(&ei->i_mmap_sem)))
4027 page = dax_layout_busy_page(inode->i_mapping);
4031 error = ___wait_var_event(&page->_refcount,
4032 atomic_read(&page->_refcount) == 1,
4033 TASK_INTERRUPTIBLE, 0, 0,
4034 ext4_wait_dax_page(ei));
4035 } while (error == 0);
4041 * ext4_punch_hole: punches a hole in a file by releasing the blocks
4042 * associated with the given offset and length
4044 * @inode: File inode
4045 * @offset: The offset where the hole will begin
4046 * @len: The length of the hole
4048 * Returns: 0 on success or negative on failure
4051 int ext4_punch_hole(struct file *file, loff_t offset, loff_t length)
4053 struct inode *inode = file_inode(file);
4054 struct super_block *sb = inode->i_sb;
4055 ext4_lblk_t first_block, stop_block;
4056 struct address_space *mapping = inode->i_mapping;
4057 loff_t first_block_offset, last_block_offset, max_length;
4058 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4060 unsigned int credits;
4061 int ret = 0, ret2 = 0;
4063 trace_ext4_punch_hole(inode, offset, length, 0);
4066 * Write out all dirty pages to avoid race conditions
4067 * Then release them.
4069 if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY)) {
4070 ret = filemap_write_and_wait_range(mapping, offset,
4071 offset + length - 1);
4078 /* No need to punch hole beyond i_size */
4079 if (offset >= inode->i_size)
4083 * If the hole extends beyond i_size, set the hole
4084 * to end after the page that contains i_size
4086 if (offset + length > inode->i_size) {
4087 length = inode->i_size +
4088 PAGE_SIZE - (inode->i_size & (PAGE_SIZE - 1)) -
4093 * For punch hole the length + offset needs to be within one block
4094 * before last range. Adjust the length if it goes beyond that limit.
4096 max_length = sbi->s_bitmap_maxbytes - inode->i_sb->s_blocksize;
4097 if (offset + length > max_length)
4098 length = max_length - offset;
4100 if (offset & (sb->s_blocksize - 1) ||
4101 (offset + length) & (sb->s_blocksize - 1)) {
4103 * Attach jinode to inode for jbd2 if we do any zeroing of
4106 ret = ext4_inode_attach_jinode(inode);
4112 /* Wait all existing dio workers, newcomers will block on i_mutex */
4113 inode_dio_wait(inode);
4115 ret = file_modified(file);
4120 * Prevent page faults from reinstantiating pages we have released from
4123 down_write(&EXT4_I(inode)->i_mmap_sem);
4125 ret = ext4_break_layouts(inode);
4129 first_block_offset = round_up(offset, sb->s_blocksize);
4130 last_block_offset = round_down((offset + length), sb->s_blocksize) - 1;
4132 /* Now release the pages and zero block aligned part of pages*/
4133 if (last_block_offset > first_block_offset) {
4134 ret = ext4_update_disksize_before_punch(inode, offset, length);
4137 truncate_pagecache_range(inode, first_block_offset,
4141 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4142 credits = ext4_writepage_trans_blocks(inode);
4144 credits = ext4_blocks_for_truncate(inode);
4145 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
4146 if (IS_ERR(handle)) {
4147 ret = PTR_ERR(handle);
4148 ext4_std_error(sb, ret);
4152 ret = ext4_zero_partial_blocks(handle, inode, offset,
4157 first_block = (offset + sb->s_blocksize - 1) >>
4158 EXT4_BLOCK_SIZE_BITS(sb);
4159 stop_block = (offset + length) >> EXT4_BLOCK_SIZE_BITS(sb);
4161 /* If there are blocks to remove, do it */
4162 if (stop_block > first_block) {
4164 down_write(&EXT4_I(inode)->i_data_sem);
4165 ext4_discard_preallocations(inode, 0);
4167 ret = ext4_es_remove_extent(inode, first_block,
4168 stop_block - first_block);
4170 up_write(&EXT4_I(inode)->i_data_sem);
4174 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4175 ret = ext4_ext_remove_space(inode, first_block,
4178 ret = ext4_ind_remove_space(handle, inode, first_block,
4181 up_write(&EXT4_I(inode)->i_data_sem);
4183 ext4_fc_track_range(handle, inode, first_block, stop_block);
4185 ext4_handle_sync(handle);
4187 inode->i_mtime = inode->i_ctime = current_time(inode);
4188 ret2 = ext4_mark_inode_dirty(handle, inode);
4192 ext4_update_inode_fsync_trans(handle, inode, 1);
4194 ext4_journal_stop(handle);
4196 up_write(&EXT4_I(inode)->i_mmap_sem);
4198 inode_unlock(inode);
4202 int ext4_inode_attach_jinode(struct inode *inode)
4204 struct ext4_inode_info *ei = EXT4_I(inode);
4205 struct jbd2_inode *jinode;
4207 if (ei->jinode || !EXT4_SB(inode->i_sb)->s_journal)
4210 jinode = jbd2_alloc_inode(GFP_KERNEL);
4211 spin_lock(&inode->i_lock);
4214 spin_unlock(&inode->i_lock);
4217 ei->jinode = jinode;
4218 jbd2_journal_init_jbd_inode(ei->jinode, inode);
4221 spin_unlock(&inode->i_lock);
4222 if (unlikely(jinode != NULL))
4223 jbd2_free_inode(jinode);
4230 * We block out ext4_get_block() block instantiations across the entire
4231 * transaction, and VFS/VM ensures that ext4_truncate() cannot run
4232 * simultaneously on behalf of the same inode.
4234 * As we work through the truncate and commit bits of it to the journal there
4235 * is one core, guiding principle: the file's tree must always be consistent on
4236 * disk. We must be able to restart the truncate after a crash.
4238 * The file's tree may be transiently inconsistent in memory (although it
4239 * probably isn't), but whenever we close off and commit a journal transaction,
4240 * the contents of (the filesystem + the journal) must be consistent and
4241 * restartable. It's pretty simple, really: bottom up, right to left (although
4242 * left-to-right works OK too).
4244 * Note that at recovery time, journal replay occurs *before* the restart of
4245 * truncate against the orphan inode list.
4247 * The committed inode has the new, desired i_size (which is the same as
4248 * i_disksize in this case). After a crash, ext4_orphan_cleanup() will see
4249 * that this inode's truncate did not complete and it will again call
4250 * ext4_truncate() to have another go. So there will be instantiated blocks
4251 * to the right of the truncation point in a crashed ext4 filesystem. But
4252 * that's fine - as long as they are linked from the inode, the post-crash
4253 * ext4_truncate() run will find them and release them.
4255 int ext4_truncate(struct inode *inode)
4257 struct ext4_inode_info *ei = EXT4_I(inode);
4258 unsigned int credits;
4261 struct address_space *mapping = inode->i_mapping;
4264 * There is a possibility that we're either freeing the inode
4265 * or it's a completely new inode. In those cases we might not
4266 * have i_mutex locked because it's not necessary.
4268 if (!(inode->i_state & (I_NEW|I_FREEING)))
4269 WARN_ON(!inode_is_locked(inode));
4270 trace_ext4_truncate_enter(inode);
4272 if (!ext4_can_truncate(inode))
4275 if (inode->i_size == 0 && !test_opt(inode->i_sb, NO_AUTO_DA_ALLOC))
4276 ext4_set_inode_state(inode, EXT4_STATE_DA_ALLOC_CLOSE);
4278 if (ext4_has_inline_data(inode)) {
4281 err = ext4_inline_data_truncate(inode, &has_inline);
4282 if (err || has_inline)
4286 /* If we zero-out tail of the page, we have to create jinode for jbd2 */
4287 if (inode->i_size & (inode->i_sb->s_blocksize - 1)) {
4288 if (ext4_inode_attach_jinode(inode) < 0)
4292 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4293 credits = ext4_writepage_trans_blocks(inode);
4295 credits = ext4_blocks_for_truncate(inode);
4297 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
4298 if (IS_ERR(handle)) {
4299 err = PTR_ERR(handle);
4303 if (inode->i_size & (inode->i_sb->s_blocksize - 1))
4304 ext4_block_truncate_page(handle, mapping, inode->i_size);
4307 * We add the inode to the orphan list, so that if this
4308 * truncate spans multiple transactions, and we crash, we will
4309 * resume the truncate when the filesystem recovers. It also
4310 * marks the inode dirty, to catch the new size.
4312 * Implication: the file must always be in a sane, consistent
4313 * truncatable state while each transaction commits.
4315 err = ext4_orphan_add(handle, inode);
4319 down_write(&EXT4_I(inode)->i_data_sem);
4321 ext4_discard_preallocations(inode, 0);
4323 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4324 err = ext4_ext_truncate(handle, inode);
4326 ext4_ind_truncate(handle, inode);
4328 up_write(&ei->i_data_sem);
4333 ext4_handle_sync(handle);
4337 * If this was a simple ftruncate() and the file will remain alive,
4338 * then we need to clear up the orphan record which we created above.
4339 * However, if this was a real unlink then we were called by
4340 * ext4_evict_inode(), and we allow that function to clean up the
4341 * orphan info for us.
4344 ext4_orphan_del(handle, inode);
4346 inode->i_mtime = inode->i_ctime = current_time(inode);
4347 err2 = ext4_mark_inode_dirty(handle, inode);
4348 if (unlikely(err2 && !err))
4350 ext4_journal_stop(handle);
4353 trace_ext4_truncate_exit(inode);
4358 * ext4_get_inode_loc returns with an extra refcount against the inode's
4359 * underlying buffer_head on success. If 'in_mem' is true, we have all
4360 * data in memory that is needed to recreate the on-disk version of this
4363 static int __ext4_get_inode_loc(struct super_block *sb, unsigned long ino,
4364 struct ext4_iloc *iloc, int in_mem,
4365 ext4_fsblk_t *ret_block)
4367 struct ext4_group_desc *gdp;
4368 struct buffer_head *bh;
4370 struct blk_plug plug;
4371 int inodes_per_block, inode_offset;
4374 if (ino < EXT4_ROOT_INO ||
4375 ino > le32_to_cpu(EXT4_SB(sb)->s_es->s_inodes_count))
4376 return -EFSCORRUPTED;
4378 iloc->block_group = (ino - 1) / EXT4_INODES_PER_GROUP(sb);
4379 gdp = ext4_get_group_desc(sb, iloc->block_group, NULL);
4384 * Figure out the offset within the block group inode table
4386 inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
4387 inode_offset = ((ino - 1) %
4388 EXT4_INODES_PER_GROUP(sb));
4389 block = ext4_inode_table(sb, gdp) + (inode_offset / inodes_per_block);
4390 iloc->offset = (inode_offset % inodes_per_block) * EXT4_INODE_SIZE(sb);
4392 bh = sb_getblk(sb, block);
4395 if (ext4_simulate_fail(sb, EXT4_SIM_INODE_EIO))
4397 if (!buffer_uptodate(bh)) {
4400 if (ext4_buffer_uptodate(bh)) {
4401 /* someone brought it uptodate while we waited */
4407 * If we have all information of the inode in memory and this
4408 * is the only valid inode in the block, we need not read the
4412 struct buffer_head *bitmap_bh;
4415 start = inode_offset & ~(inodes_per_block - 1);
4417 /* Is the inode bitmap in cache? */
4418 bitmap_bh = sb_getblk(sb, ext4_inode_bitmap(sb, gdp));
4419 if (unlikely(!bitmap_bh))
4423 * If the inode bitmap isn't in cache then the
4424 * optimisation may end up performing two reads instead
4425 * of one, so skip it.
4427 if (!buffer_uptodate(bitmap_bh)) {
4431 for (i = start; i < start + inodes_per_block; i++) {
4432 if (i == inode_offset)
4434 if (ext4_test_bit(i, bitmap_bh->b_data))
4438 if (i == start + inodes_per_block) {
4439 /* all other inodes are free, so skip I/O */
4440 memset(bh->b_data, 0, bh->b_size);
4441 set_buffer_uptodate(bh);
4449 * If we need to do any I/O, try to pre-readahead extra
4450 * blocks from the inode table.
4452 blk_start_plug(&plug);
4453 if (EXT4_SB(sb)->s_inode_readahead_blks) {
4454 ext4_fsblk_t b, end, table;
4456 __u32 ra_blks = EXT4_SB(sb)->s_inode_readahead_blks;
4458 table = ext4_inode_table(sb, gdp);
4459 /* s_inode_readahead_blks is always a power of 2 */
4460 b = block & ~((ext4_fsblk_t) ra_blks - 1);
4464 num = EXT4_INODES_PER_GROUP(sb);
4465 if (ext4_has_group_desc_csum(sb))
4466 num -= ext4_itable_unused_count(sb, gdp);
4467 table += num / inodes_per_block;
4471 ext4_sb_breadahead_unmovable(sb, b++);
4475 * There are other valid inodes in the buffer, this inode
4476 * has in-inode xattrs, or we don't have this inode in memory.
4477 * Read the block from disk.
4479 trace_ext4_load_inode(sb, ino);
4480 ext4_read_bh_nowait(bh, REQ_META | REQ_PRIO, NULL);
4481 blk_finish_plug(&plug);
4483 if (!buffer_uptodate(bh)) {
4496 static int __ext4_get_inode_loc_noinmem(struct inode *inode,
4497 struct ext4_iloc *iloc)
4499 ext4_fsblk_t err_blk = 0;
4502 ret = __ext4_get_inode_loc(inode->i_sb, inode->i_ino, iloc, 0,
4506 ext4_error_inode_block(inode, err_blk, EIO,
4507 "unable to read itable block");
4512 int ext4_get_inode_loc(struct inode *inode, struct ext4_iloc *iloc)
4514 ext4_fsblk_t err_blk = 0;
4517 /* We have all inode data except xattrs in memory here. */
4518 ret = __ext4_get_inode_loc(inode->i_sb, inode->i_ino, iloc,
4519 !ext4_test_inode_state(inode, EXT4_STATE_XATTR), &err_blk);
4522 ext4_error_inode_block(inode, err_blk, EIO,
4523 "unable to read itable block");
4529 int ext4_get_fc_inode_loc(struct super_block *sb, unsigned long ino,
4530 struct ext4_iloc *iloc)
4532 return __ext4_get_inode_loc(sb, ino, iloc, 0, NULL);
4535 static bool ext4_should_enable_dax(struct inode *inode)
4537 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4539 if (test_opt2(inode->i_sb, DAX_NEVER))
4541 if (!S_ISREG(inode->i_mode))
4543 if (ext4_should_journal_data(inode))
4545 if (ext4_has_inline_data(inode))
4547 if (ext4_test_inode_flag(inode, EXT4_INODE_ENCRYPT))
4549 if (ext4_test_inode_flag(inode, EXT4_INODE_VERITY))
4551 if (!test_bit(EXT4_FLAGS_BDEV_IS_DAX, &sbi->s_ext4_flags))
4553 if (test_opt(inode->i_sb, DAX_ALWAYS))
4556 return ext4_test_inode_flag(inode, EXT4_INODE_DAX);
4559 void ext4_set_inode_flags(struct inode *inode, bool init)
4561 unsigned int flags = EXT4_I(inode)->i_flags;
4562 unsigned int new_fl = 0;
4564 WARN_ON_ONCE(IS_DAX(inode) && init);
4566 if (flags & EXT4_SYNC_FL)
4568 if (flags & EXT4_APPEND_FL)
4570 if (flags & EXT4_IMMUTABLE_FL)
4571 new_fl |= S_IMMUTABLE;
4572 if (flags & EXT4_NOATIME_FL)
4573 new_fl |= S_NOATIME;
4574 if (flags & EXT4_DIRSYNC_FL)
4575 new_fl |= S_DIRSYNC;
4577 /* Because of the way inode_set_flags() works we must preserve S_DAX
4578 * here if already set. */
4579 new_fl |= (inode->i_flags & S_DAX);
4580 if (init && ext4_should_enable_dax(inode))
4583 if (flags & EXT4_ENCRYPT_FL)
4584 new_fl |= S_ENCRYPTED;
4585 if (flags & EXT4_CASEFOLD_FL)
4586 new_fl |= S_CASEFOLD;
4587 if (flags & EXT4_VERITY_FL)
4589 inode_set_flags(inode, new_fl,
4590 S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME|S_DIRSYNC|S_DAX|
4591 S_ENCRYPTED|S_CASEFOLD|S_VERITY);
4594 static blkcnt_t ext4_inode_blocks(struct ext4_inode *raw_inode,
4595 struct ext4_inode_info *ei)
4598 struct inode *inode = &(ei->vfs_inode);
4599 struct super_block *sb = inode->i_sb;
4601 if (ext4_has_feature_huge_file(sb)) {
4602 /* we are using combined 48 bit field */
4603 i_blocks = ((u64)le16_to_cpu(raw_inode->i_blocks_high)) << 32 |
4604 le32_to_cpu(raw_inode->i_blocks_lo);
4605 if (ext4_test_inode_flag(inode, EXT4_INODE_HUGE_FILE)) {
4606 /* i_blocks represent file system block size */
4607 return i_blocks << (inode->i_blkbits - 9);
4612 return le32_to_cpu(raw_inode->i_blocks_lo);
4616 static inline int ext4_iget_extra_inode(struct inode *inode,
4617 struct ext4_inode *raw_inode,
4618 struct ext4_inode_info *ei)
4620 __le32 *magic = (void *)raw_inode +
4621 EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize;
4623 if (EXT4_INODE_HAS_XATTR_SPACE(inode) &&
4624 *magic == cpu_to_le32(EXT4_XATTR_MAGIC)) {
4625 ext4_set_inode_state(inode, EXT4_STATE_XATTR);
4626 return ext4_find_inline_data_nolock(inode);
4628 EXT4_I(inode)->i_inline_off = 0;
4632 int ext4_get_projid(struct inode *inode, kprojid_t *projid)
4634 if (!ext4_has_feature_project(inode->i_sb))
4636 *projid = EXT4_I(inode)->i_projid;
4641 * ext4 has self-managed i_version for ea inodes, it stores the lower 32bit of
4642 * refcount in i_version, so use raw values if inode has EXT4_EA_INODE_FL flag
4645 static inline void ext4_inode_set_iversion_queried(struct inode *inode, u64 val)
4647 if (unlikely(EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL))
4648 inode_set_iversion_raw(inode, val);
4650 inode_set_iversion_queried(inode, val);
4652 static inline u64 ext4_inode_peek_iversion(const struct inode *inode)
4654 if (unlikely(EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL))
4655 return inode_peek_iversion_raw(inode);
4657 return inode_peek_iversion(inode);
4660 struct inode *__ext4_iget(struct super_block *sb, unsigned long ino,
4661 ext4_iget_flags flags, const char *function,
4664 struct ext4_iloc iloc;
4665 struct ext4_inode *raw_inode;
4666 struct ext4_inode_info *ei;
4667 struct inode *inode;
4668 journal_t *journal = EXT4_SB(sb)->s_journal;
4676 if ((!(flags & EXT4_IGET_SPECIAL) &&
4677 (ino < EXT4_FIRST_INO(sb) && ino != EXT4_ROOT_INO)) ||
4678 (ino < EXT4_ROOT_INO) ||
4679 (ino > le32_to_cpu(EXT4_SB(sb)->s_es->s_inodes_count))) {
4680 if (flags & EXT4_IGET_HANDLE)
4681 return ERR_PTR(-ESTALE);
4682 __ext4_error(sb, function, line, EFSCORRUPTED, 0,
4683 "inode #%lu: comm %s: iget: illegal inode #",
4684 ino, current->comm);
4685 return ERR_PTR(-EFSCORRUPTED);
4688 inode = iget_locked(sb, ino);
4690 return ERR_PTR(-ENOMEM);
4691 if (!(inode->i_state & I_NEW))
4697 ret = __ext4_get_inode_loc_noinmem(inode, &iloc);
4700 raw_inode = ext4_raw_inode(&iloc);
4702 if ((ino == EXT4_ROOT_INO) && (raw_inode->i_links_count == 0)) {
4703 ext4_error_inode(inode, function, line, 0,
4704 "iget: root inode unallocated");
4705 ret = -EFSCORRUPTED;
4709 if ((flags & EXT4_IGET_HANDLE) &&
4710 (raw_inode->i_links_count == 0) && (raw_inode->i_mode == 0)) {
4715 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4716 ei->i_extra_isize = le16_to_cpu(raw_inode->i_extra_isize);
4717 if (EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize >
4718 EXT4_INODE_SIZE(inode->i_sb) ||
4719 (ei->i_extra_isize & 3)) {
4720 ext4_error_inode(inode, function, line, 0,
4721 "iget: bad extra_isize %u "
4724 EXT4_INODE_SIZE(inode->i_sb));
4725 ret = -EFSCORRUPTED;
4729 ei->i_extra_isize = 0;
4731 /* Precompute checksum seed for inode metadata */
4732 if (ext4_has_metadata_csum(sb)) {
4733 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4735 __le32 inum = cpu_to_le32(inode->i_ino);
4736 __le32 gen = raw_inode->i_generation;
4737 csum = ext4_chksum(sbi, sbi->s_csum_seed, (__u8 *)&inum,
4739 ei->i_csum_seed = ext4_chksum(sbi, csum, (__u8 *)&gen,
4743 if ((!ext4_inode_csum_verify(inode, raw_inode, ei) ||
4744 ext4_simulate_fail(sb, EXT4_SIM_INODE_CRC)) &&
4745 (!(EXT4_SB(sb)->s_mount_state & EXT4_FC_REPLAY))) {
4746 ext4_error_inode_err(inode, function, line, 0,
4747 EFSBADCRC, "iget: checksum invalid");
4752 inode->i_mode = le16_to_cpu(raw_inode->i_mode);
4753 i_uid = (uid_t)le16_to_cpu(raw_inode->i_uid_low);
4754 i_gid = (gid_t)le16_to_cpu(raw_inode->i_gid_low);
4755 if (ext4_has_feature_project(sb) &&
4756 EXT4_INODE_SIZE(sb) > EXT4_GOOD_OLD_INODE_SIZE &&
4757 EXT4_FITS_IN_INODE(raw_inode, ei, i_projid))
4758 i_projid = (projid_t)le32_to_cpu(raw_inode->i_projid);
4760 i_projid = EXT4_DEF_PROJID;
4762 if (!(test_opt(inode->i_sb, NO_UID32))) {
4763 i_uid |= le16_to_cpu(raw_inode->i_uid_high) << 16;
4764 i_gid |= le16_to_cpu(raw_inode->i_gid_high) << 16;
4766 i_uid_write(inode, i_uid);
4767 i_gid_write(inode, i_gid);
4768 ei->i_projid = make_kprojid(&init_user_ns, i_projid);
4769 set_nlink(inode, le16_to_cpu(raw_inode->i_links_count));
4771 ext4_clear_state_flags(ei); /* Only relevant on 32-bit archs */
4772 ei->i_inline_off = 0;
4773 ei->i_dir_start_lookup = 0;
4774 ei->i_dtime = le32_to_cpu(raw_inode->i_dtime);
4775 /* We now have enough fields to check if the inode was active or not.
4776 * This is needed because nfsd might try to access dead inodes
4777 * the test is that same one that e2fsck uses
4778 * NeilBrown 1999oct15
4780 if (inode->i_nlink == 0) {
4781 if ((inode->i_mode == 0 ||
4782 !(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_ORPHAN_FS)) &&
4783 ino != EXT4_BOOT_LOADER_INO) {
4784 /* this inode is deleted */
4788 /* The only unlinked inodes we let through here have
4789 * valid i_mode and are being read by the orphan
4790 * recovery code: that's fine, we're about to complete
4791 * the process of deleting those.
4792 * OR it is the EXT4_BOOT_LOADER_INO which is
4793 * not initialized on a new filesystem. */
4795 ei->i_flags = le32_to_cpu(raw_inode->i_flags);
4796 ext4_set_inode_flags(inode, true);
4797 inode->i_blocks = ext4_inode_blocks(raw_inode, ei);
4798 ei->i_file_acl = le32_to_cpu(raw_inode->i_file_acl_lo);
4799 if (ext4_has_feature_64bit(sb))
4801 ((__u64)le16_to_cpu(raw_inode->i_file_acl_high)) << 32;
4802 inode->i_size = ext4_isize(sb, raw_inode);
4803 if ((size = i_size_read(inode)) < 0) {
4804 ext4_error_inode(inode, function, line, 0,
4805 "iget: bad i_size value: %lld", size);
4806 ret = -EFSCORRUPTED;
4810 * If dir_index is not enabled but there's dir with INDEX flag set,
4811 * we'd normally treat htree data as empty space. But with metadata
4812 * checksumming that corrupts checksums so forbid that.
4814 if (!ext4_has_feature_dir_index(sb) && ext4_has_metadata_csum(sb) &&
4815 ext4_test_inode_flag(inode, EXT4_INODE_INDEX)) {
4816 ext4_error_inode(inode, function, line, 0,
4817 "iget: Dir with htree data on filesystem without dir_index feature.");
4818 ret = -EFSCORRUPTED;
4821 ei->i_disksize = inode->i_size;
4823 ei->i_reserved_quota = 0;
4825 inode->i_generation = le32_to_cpu(raw_inode->i_generation);
4826 ei->i_block_group = iloc.block_group;
4827 ei->i_last_alloc_group = ~0;
4829 * NOTE! The in-memory inode i_data array is in little-endian order
4830 * even on big-endian machines: we do NOT byteswap the block numbers!
4832 for (block = 0; block < EXT4_N_BLOCKS; block++)
4833 ei->i_data[block] = raw_inode->i_block[block];
4834 INIT_LIST_HEAD(&ei->i_orphan);
4835 ext4_fc_init_inode(&ei->vfs_inode);
4838 * Set transaction id's of transactions that have to be committed
4839 * to finish f[data]sync. We set them to currently running transaction
4840 * as we cannot be sure that the inode or some of its metadata isn't
4841 * part of the transaction - the inode could have been reclaimed and
4842 * now it is reread from disk.
4845 transaction_t *transaction;
4848 read_lock(&journal->j_state_lock);
4849 if (journal->j_running_transaction)
4850 transaction = journal->j_running_transaction;
4852 transaction = journal->j_committing_transaction;
4854 tid = transaction->t_tid;
4856 tid = journal->j_commit_sequence;
4857 read_unlock(&journal->j_state_lock);
4858 ei->i_sync_tid = tid;
4859 ei->i_datasync_tid = tid;
4862 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4863 if (ei->i_extra_isize == 0) {
4864 /* The extra space is currently unused. Use it. */
4865 BUILD_BUG_ON(sizeof(struct ext4_inode) & 3);
4866 ei->i_extra_isize = sizeof(struct ext4_inode) -
4867 EXT4_GOOD_OLD_INODE_SIZE;
4869 ret = ext4_iget_extra_inode(inode, raw_inode, ei);
4875 EXT4_INODE_GET_XTIME(i_ctime, inode, raw_inode);
4876 EXT4_INODE_GET_XTIME(i_mtime, inode, raw_inode);
4877 EXT4_INODE_GET_XTIME(i_atime, inode, raw_inode);
4878 EXT4_EINODE_GET_XTIME(i_crtime, ei, raw_inode);
4880 if (likely(!test_opt2(inode->i_sb, HURD_COMPAT))) {
4881 u64 ivers = le32_to_cpu(raw_inode->i_disk_version);
4883 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4884 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
4886 (__u64)(le32_to_cpu(raw_inode->i_version_hi)) << 32;
4888 ext4_inode_set_iversion_queried(inode, ivers);
4892 if (ei->i_file_acl &&
4893 !ext4_inode_block_valid(inode, ei->i_file_acl, 1)) {
4894 ext4_error_inode(inode, function, line, 0,
4895 "iget: bad extended attribute block %llu",
4897 ret = -EFSCORRUPTED;
4899 } else if (!ext4_has_inline_data(inode)) {
4900 /* validate the block references in the inode */
4901 if (!(EXT4_SB(sb)->s_mount_state & EXT4_FC_REPLAY) &&
4902 (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
4903 (S_ISLNK(inode->i_mode) &&
4904 !ext4_inode_is_fast_symlink(inode)))) {
4905 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4906 ret = ext4_ext_check_inode(inode);
4908 ret = ext4_ind_check_inode(inode);
4914 if (S_ISREG(inode->i_mode)) {
4915 inode->i_op = &ext4_file_inode_operations;
4916 inode->i_fop = &ext4_file_operations;
4917 ext4_set_aops(inode);
4918 } else if (S_ISDIR(inode->i_mode)) {
4919 inode->i_op = &ext4_dir_inode_operations;
4920 inode->i_fop = &ext4_dir_operations;
4921 } else if (S_ISLNK(inode->i_mode)) {
4922 /* VFS does not allow setting these so must be corruption */
4923 if (IS_APPEND(inode) || IS_IMMUTABLE(inode)) {
4924 ext4_error_inode(inode, function, line, 0,
4925 "iget: immutable or append flags "
4926 "not allowed on symlinks");
4927 ret = -EFSCORRUPTED;
4930 if (IS_ENCRYPTED(inode)) {
4931 inode->i_op = &ext4_encrypted_symlink_inode_operations;
4932 ext4_set_aops(inode);
4933 } else if (ext4_inode_is_fast_symlink(inode)) {
4934 inode->i_link = (char *)ei->i_data;
4935 inode->i_op = &ext4_fast_symlink_inode_operations;
4936 nd_terminate_link(ei->i_data, inode->i_size,
4937 sizeof(ei->i_data) - 1);
4939 inode->i_op = &ext4_symlink_inode_operations;
4940 ext4_set_aops(inode);
4942 inode_nohighmem(inode);
4943 } else if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode) ||
4944 S_ISFIFO(inode->i_mode) || S_ISSOCK(inode->i_mode)) {
4945 inode->i_op = &ext4_special_inode_operations;
4946 if (raw_inode->i_block[0])
4947 init_special_inode(inode, inode->i_mode,
4948 old_decode_dev(le32_to_cpu(raw_inode->i_block[0])));
4950 init_special_inode(inode, inode->i_mode,
4951 new_decode_dev(le32_to_cpu(raw_inode->i_block[1])));
4952 } else if (ino == EXT4_BOOT_LOADER_INO) {
4953 make_bad_inode(inode);
4955 ret = -EFSCORRUPTED;
4956 ext4_error_inode(inode, function, line, 0,
4957 "iget: bogus i_mode (%o)", inode->i_mode);
4960 if (IS_CASEFOLDED(inode) && !ext4_has_feature_casefold(inode->i_sb))
4961 ext4_error_inode(inode, function, line, 0,
4962 "casefold flag without casefold feature");
4965 unlock_new_inode(inode);
4971 return ERR_PTR(ret);
4974 static int ext4_inode_blocks_set(handle_t *handle,
4975 struct ext4_inode *raw_inode,
4976 struct ext4_inode_info *ei)
4978 struct inode *inode = &(ei->vfs_inode);
4979 u64 i_blocks = READ_ONCE(inode->i_blocks);
4980 struct super_block *sb = inode->i_sb;
4982 if (i_blocks <= ~0U) {
4984 * i_blocks can be represented in a 32 bit variable
4985 * as multiple of 512 bytes
4987 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
4988 raw_inode->i_blocks_high = 0;
4989 ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
4992 if (!ext4_has_feature_huge_file(sb))
4995 if (i_blocks <= 0xffffffffffffULL) {
4997 * i_blocks can be represented in a 48 bit variable
4998 * as multiple of 512 bytes
5000 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
5001 raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
5002 ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
5004 ext4_set_inode_flag(inode, EXT4_INODE_HUGE_FILE);
5005 /* i_block is stored in file system block size */
5006 i_blocks = i_blocks >> (inode->i_blkbits - 9);
5007 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
5008 raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
5013 static void __ext4_update_other_inode_time(struct super_block *sb,
5014 unsigned long orig_ino,
5016 struct ext4_inode *raw_inode)
5018 struct inode *inode;
5020 inode = find_inode_by_ino_rcu(sb, ino);
5024 if ((inode->i_state & (I_FREEING | I_WILL_FREE | I_NEW |
5026 ((inode->i_state & I_DIRTY_TIME) == 0))
5029 spin_lock(&inode->i_lock);
5030 if (((inode->i_state & (I_FREEING | I_WILL_FREE | I_NEW |
5031 I_DIRTY_INODE)) == 0) &&
5032 (inode->i_state & I_DIRTY_TIME)) {
5033 struct ext4_inode_info *ei = EXT4_I(inode);
5035 inode->i_state &= ~I_DIRTY_TIME;
5036 spin_unlock(&inode->i_lock);
5038 spin_lock(&ei->i_raw_lock);
5039 EXT4_INODE_SET_XTIME(i_ctime, inode, raw_inode);
5040 EXT4_INODE_SET_XTIME(i_mtime, inode, raw_inode);
5041 EXT4_INODE_SET_XTIME(i_atime, inode, raw_inode);
5042 ext4_inode_csum_set(inode, raw_inode, ei);
5043 spin_unlock(&ei->i_raw_lock);
5044 trace_ext4_other_inode_update_time(inode, orig_ino);
5047 spin_unlock(&inode->i_lock);
5051 * Opportunistically update the other time fields for other inodes in
5052 * the same inode table block.
5054 static void ext4_update_other_inodes_time(struct super_block *sb,
5055 unsigned long orig_ino, char *buf)
5058 int i, inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
5059 int inode_size = EXT4_INODE_SIZE(sb);
5062 * Calculate the first inode in the inode table block. Inode
5063 * numbers are one-based. That is, the first inode in a block
5064 * (assuming 4k blocks and 256 byte inodes) is (n*16 + 1).
5066 ino = ((orig_ino - 1) & ~(inodes_per_block - 1)) + 1;
5068 for (i = 0; i < inodes_per_block; i++, ino++, buf += inode_size) {
5069 if (ino == orig_ino)
5071 __ext4_update_other_inode_time(sb, orig_ino, ino,
5072 (struct ext4_inode *)buf);
5078 * Post the struct inode info into an on-disk inode location in the
5079 * buffer-cache. This gobbles the caller's reference to the
5080 * buffer_head in the inode location struct.
5082 * The caller must have write access to iloc->bh.
5084 static int ext4_do_update_inode(handle_t *handle,
5085 struct inode *inode,
5086 struct ext4_iloc *iloc)
5088 struct ext4_inode *raw_inode = ext4_raw_inode(iloc);
5089 struct ext4_inode_info *ei = EXT4_I(inode);
5090 struct buffer_head *bh = iloc->bh;
5091 struct super_block *sb = inode->i_sb;
5093 int need_datasync = 0, set_large_file = 0;
5098 spin_lock(&ei->i_raw_lock);
5100 /* For fields not tracked in the in-memory inode,
5101 * initialise them to zero for new inodes. */
5102 if (ext4_test_inode_state(inode, EXT4_STATE_NEW))
5103 memset(raw_inode, 0, EXT4_SB(inode->i_sb)->s_inode_size);
5105 err = ext4_inode_blocks_set(handle, raw_inode, ei);
5107 spin_unlock(&ei->i_raw_lock);
5111 raw_inode->i_mode = cpu_to_le16(inode->i_mode);
5112 i_uid = i_uid_read(inode);
5113 i_gid = i_gid_read(inode);
5114 i_projid = from_kprojid(&init_user_ns, ei->i_projid);
5115 if (!(test_opt(inode->i_sb, NO_UID32))) {
5116 raw_inode->i_uid_low = cpu_to_le16(low_16_bits(i_uid));
5117 raw_inode->i_gid_low = cpu_to_le16(low_16_bits(i_gid));
5119 * Fix up interoperability with old kernels. Otherwise, old inodes get
5120 * re-used with the upper 16 bits of the uid/gid intact
5122 if (ei->i_dtime && list_empty(&ei->i_orphan)) {
5123 raw_inode->i_uid_high = 0;
5124 raw_inode->i_gid_high = 0;
5126 raw_inode->i_uid_high =
5127 cpu_to_le16(high_16_bits(i_uid));
5128 raw_inode->i_gid_high =
5129 cpu_to_le16(high_16_bits(i_gid));
5132 raw_inode->i_uid_low = cpu_to_le16(fs_high2lowuid(i_uid));
5133 raw_inode->i_gid_low = cpu_to_le16(fs_high2lowgid(i_gid));
5134 raw_inode->i_uid_high = 0;
5135 raw_inode->i_gid_high = 0;
5137 raw_inode->i_links_count = cpu_to_le16(inode->i_nlink);
5139 EXT4_INODE_SET_XTIME(i_ctime, inode, raw_inode);
5140 EXT4_INODE_SET_XTIME(i_mtime, inode, raw_inode);
5141 EXT4_INODE_SET_XTIME(i_atime, inode, raw_inode);
5142 EXT4_EINODE_SET_XTIME(i_crtime, ei, raw_inode);
5144 raw_inode->i_dtime = cpu_to_le32(ei->i_dtime);
5145 raw_inode->i_flags = cpu_to_le32(ei->i_flags & 0xFFFFFFFF);
5146 if (likely(!test_opt2(inode->i_sb, HURD_COMPAT)))
5147 raw_inode->i_file_acl_high =
5148 cpu_to_le16(ei->i_file_acl >> 32);
5149 raw_inode->i_file_acl_lo = cpu_to_le32(ei->i_file_acl);
5150 if (READ_ONCE(ei->i_disksize) != ext4_isize(inode->i_sb, raw_inode)) {
5151 ext4_isize_set(raw_inode, ei->i_disksize);
5154 if (ei->i_disksize > 0x7fffffffULL) {
5155 if (!ext4_has_feature_large_file(sb) ||
5156 EXT4_SB(sb)->s_es->s_rev_level ==
5157 cpu_to_le32(EXT4_GOOD_OLD_REV))
5160 raw_inode->i_generation = cpu_to_le32(inode->i_generation);
5161 if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) {
5162 if (old_valid_dev(inode->i_rdev)) {
5163 raw_inode->i_block[0] =
5164 cpu_to_le32(old_encode_dev(inode->i_rdev));
5165 raw_inode->i_block[1] = 0;
5167 raw_inode->i_block[0] = 0;
5168 raw_inode->i_block[1] =
5169 cpu_to_le32(new_encode_dev(inode->i_rdev));
5170 raw_inode->i_block[2] = 0;
5172 } else if (!ext4_has_inline_data(inode)) {
5173 for (block = 0; block < EXT4_N_BLOCKS; block++)
5174 raw_inode->i_block[block] = ei->i_data[block];
5177 if (likely(!test_opt2(inode->i_sb, HURD_COMPAT))) {
5178 u64 ivers = ext4_inode_peek_iversion(inode);
5180 raw_inode->i_disk_version = cpu_to_le32(ivers);
5181 if (ei->i_extra_isize) {
5182 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
5183 raw_inode->i_version_hi =
5184 cpu_to_le32(ivers >> 32);
5185 raw_inode->i_extra_isize =
5186 cpu_to_le16(ei->i_extra_isize);
5190 BUG_ON(!ext4_has_feature_project(inode->i_sb) &&
5191 i_projid != EXT4_DEF_PROJID);
5193 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
5194 EXT4_FITS_IN_INODE(raw_inode, ei, i_projid))
5195 raw_inode->i_projid = cpu_to_le32(i_projid);
5197 ext4_inode_csum_set(inode, raw_inode, ei);
5198 spin_unlock(&ei->i_raw_lock);
5199 if (inode->i_sb->s_flags & SB_LAZYTIME)
5200 ext4_update_other_inodes_time(inode->i_sb, inode->i_ino,
5203 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
5204 err = ext4_handle_dirty_metadata(handle, NULL, bh);
5207 ext4_clear_inode_state(inode, EXT4_STATE_NEW);
5208 if (set_large_file) {
5209 BUFFER_TRACE(EXT4_SB(sb)->s_sbh, "get write access");
5210 err = ext4_journal_get_write_access(handle, EXT4_SB(sb)->s_sbh);
5213 ext4_set_feature_large_file(sb);
5214 ext4_handle_sync(handle);
5215 err = ext4_handle_dirty_super(handle, sb);
5217 ext4_update_inode_fsync_trans(handle, inode, need_datasync);
5220 ext4_std_error(inode->i_sb, err);
5225 * ext4_write_inode()
5227 * We are called from a few places:
5229 * - Within generic_file_aio_write() -> generic_write_sync() for O_SYNC files.
5230 * Here, there will be no transaction running. We wait for any running
5231 * transaction to commit.
5233 * - Within flush work (sys_sync(), kupdate and such).
5234 * We wait on commit, if told to.
5236 * - Within iput_final() -> write_inode_now()
5237 * We wait on commit, if told to.
5239 * In all cases it is actually safe for us to return without doing anything,
5240 * because the inode has been copied into a raw inode buffer in
5241 * ext4_mark_inode_dirty(). This is a correctness thing for WB_SYNC_ALL
5244 * Note that we are absolutely dependent upon all inode dirtiers doing the
5245 * right thing: they *must* call mark_inode_dirty() after dirtying info in
5246 * which we are interested.
5248 * It would be a bug for them to not do this. The code:
5250 * mark_inode_dirty(inode)
5252 * inode->i_size = expr;
5254 * is in error because write_inode() could occur while `stuff()' is running,
5255 * and the new i_size will be lost. Plus the inode will no longer be on the
5256 * superblock's dirty inode list.
5258 int ext4_write_inode(struct inode *inode, struct writeback_control *wbc)
5262 if (WARN_ON_ONCE(current->flags & PF_MEMALLOC) ||
5263 sb_rdonly(inode->i_sb))
5266 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
5269 if (EXT4_SB(inode->i_sb)->s_journal) {
5270 if (ext4_journal_current_handle()) {
5271 jbd_debug(1, "called recursively, non-PF_MEMALLOC!\n");
5277 * No need to force transaction in WB_SYNC_NONE mode. Also
5278 * ext4_sync_fs() will force the commit after everything is
5281 if (wbc->sync_mode != WB_SYNC_ALL || wbc->for_sync)
5284 err = ext4_fc_commit(EXT4_SB(inode->i_sb)->s_journal,
5285 EXT4_I(inode)->i_sync_tid);
5287 struct ext4_iloc iloc;
5289 err = __ext4_get_inode_loc_noinmem(inode, &iloc);
5293 * sync(2) will flush the whole buffer cache. No need to do
5294 * it here separately for each inode.
5296 if (wbc->sync_mode == WB_SYNC_ALL && !wbc->for_sync)
5297 sync_dirty_buffer(iloc.bh);
5298 if (buffer_req(iloc.bh) && !buffer_uptodate(iloc.bh)) {
5299 ext4_error_inode_block(inode, iloc.bh->b_blocknr, EIO,
5300 "IO error syncing inode");
5309 * In data=journal mode ext4_journalled_invalidatepage() may fail to invalidate
5310 * buffers that are attached to a page stradding i_size and are undergoing
5311 * commit. In that case we have to wait for commit to finish and try again.
5313 static void ext4_wait_for_tail_page_commit(struct inode *inode)
5317 journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
5318 tid_t commit_tid = 0;
5321 offset = inode->i_size & (PAGE_SIZE - 1);
5323 * If the page is fully truncated, we don't need to wait for any commit
5324 * (and we even should not as __ext4_journalled_invalidatepage() may
5325 * strip all buffers from the page but keep the page dirty which can then
5326 * confuse e.g. concurrent ext4_writepage() seeing dirty page without
5327 * buffers). Also we don't need to wait for any commit if all buffers in
5328 * the page remain valid. This is most beneficial for the common case of
5329 * blocksize == PAGESIZE.
5331 if (!offset || offset > (PAGE_SIZE - i_blocksize(inode)))
5334 page = find_lock_page(inode->i_mapping,
5335 inode->i_size >> PAGE_SHIFT);
5338 ret = __ext4_journalled_invalidatepage(page, offset,
5339 PAGE_SIZE - offset);
5345 read_lock(&journal->j_state_lock);
5346 if (journal->j_committing_transaction)
5347 commit_tid = journal->j_committing_transaction->t_tid;
5348 read_unlock(&journal->j_state_lock);
5350 jbd2_log_wait_commit(journal, commit_tid);
5357 * Called from notify_change.
5359 * We want to trap VFS attempts to truncate the file as soon as
5360 * possible. In particular, we want to make sure that when the VFS
5361 * shrinks i_size, we put the inode on the orphan list and modify
5362 * i_disksize immediately, so that during the subsequent flushing of
5363 * dirty pages and freeing of disk blocks, we can guarantee that any
5364 * commit will leave the blocks being flushed in an unused state on
5365 * disk. (On recovery, the inode will get truncated and the blocks will
5366 * be freed, so we have a strong guarantee that no future commit will
5367 * leave these blocks visible to the user.)
5369 * Another thing we have to assure is that if we are in ordered mode
5370 * and inode is still attached to the committing transaction, we must
5371 * we start writeout of all the dirty pages which are being truncated.
5372 * This way we are sure that all the data written in the previous
5373 * transaction are already on disk (truncate waits for pages under
5376 * Called with inode->i_mutex down.
5378 int ext4_setattr(struct dentry *dentry, struct iattr *attr)
5380 struct inode *inode = d_inode(dentry);
5383 const unsigned int ia_valid = attr->ia_valid;
5385 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
5388 if (unlikely(IS_IMMUTABLE(inode)))
5391 if (unlikely(IS_APPEND(inode) &&
5392 (ia_valid & (ATTR_MODE | ATTR_UID |
5393 ATTR_GID | ATTR_TIMES_SET))))
5396 error = setattr_prepare(dentry, attr);
5400 error = fscrypt_prepare_setattr(dentry, attr);
5404 error = fsverity_prepare_setattr(dentry, attr);
5408 if (is_quota_modification(inode, attr)) {
5409 error = dquot_initialize(inode);
5413 ext4_fc_start_update(inode);
5414 if ((ia_valid & ATTR_UID && !uid_eq(attr->ia_uid, inode->i_uid)) ||
5415 (ia_valid & ATTR_GID && !gid_eq(attr->ia_gid, inode->i_gid))) {
5418 /* (user+group)*(old+new) structure, inode write (sb,
5419 * inode block, ? - but truncate inode update has it) */
5420 handle = ext4_journal_start(inode, EXT4_HT_QUOTA,
5421 (EXT4_MAXQUOTAS_INIT_BLOCKS(inode->i_sb) +
5422 EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb)) + 3);
5423 if (IS_ERR(handle)) {
5424 error = PTR_ERR(handle);
5428 /* dquot_transfer() calls back ext4_get_inode_usage() which
5429 * counts xattr inode references.
5431 down_read(&EXT4_I(inode)->xattr_sem);
5432 error = dquot_transfer(inode, attr);
5433 up_read(&EXT4_I(inode)->xattr_sem);
5436 ext4_journal_stop(handle);
5437 ext4_fc_stop_update(inode);
5440 /* Update corresponding info in inode so that everything is in
5441 * one transaction */
5442 if (attr->ia_valid & ATTR_UID)
5443 inode->i_uid = attr->ia_uid;
5444 if (attr->ia_valid & ATTR_GID)
5445 inode->i_gid = attr->ia_gid;
5446 error = ext4_mark_inode_dirty(handle, inode);
5447 ext4_journal_stop(handle);
5448 if (unlikely(error)) {
5449 ext4_fc_stop_update(inode);
5454 if (attr->ia_valid & ATTR_SIZE) {
5456 loff_t oldsize = inode->i_size;
5457 loff_t old_disksize;
5458 int shrink = (attr->ia_size < inode->i_size);
5460 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
5461 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
5463 if (attr->ia_size > sbi->s_bitmap_maxbytes) {
5464 ext4_fc_stop_update(inode);
5468 if (!S_ISREG(inode->i_mode)) {
5469 ext4_fc_stop_update(inode);
5473 if (IS_I_VERSION(inode) && attr->ia_size != inode->i_size)
5474 inode_inc_iversion(inode);
5477 if (ext4_should_order_data(inode)) {
5478 error = ext4_begin_ordered_truncate(inode,
5484 * Blocks are going to be removed from the inode. Wait
5485 * for dio in flight.
5487 inode_dio_wait(inode);
5490 down_write(&EXT4_I(inode)->i_mmap_sem);
5492 rc = ext4_break_layouts(inode);
5494 up_write(&EXT4_I(inode)->i_mmap_sem);
5498 if (attr->ia_size != inode->i_size) {
5499 handle = ext4_journal_start(inode, EXT4_HT_INODE, 3);
5500 if (IS_ERR(handle)) {
5501 error = PTR_ERR(handle);
5504 if (ext4_handle_valid(handle) && shrink) {
5505 error = ext4_orphan_add(handle, inode);
5509 * Update c/mtime on truncate up, ext4_truncate() will
5510 * update c/mtime in shrink case below
5513 inode->i_mtime = current_time(inode);
5514 inode->i_ctime = inode->i_mtime;
5518 ext4_fc_track_range(handle, inode,
5519 (attr->ia_size > 0 ? attr->ia_size - 1 : 0) >>
5520 inode->i_sb->s_blocksize_bits,
5521 EXT_MAX_BLOCKS - 1);
5523 ext4_fc_track_range(
5525 (oldsize > 0 ? oldsize - 1 : oldsize) >>
5526 inode->i_sb->s_blocksize_bits,
5527 (attr->ia_size > 0 ? attr->ia_size - 1 : 0) >>
5528 inode->i_sb->s_blocksize_bits);
5530 down_write(&EXT4_I(inode)->i_data_sem);
5531 old_disksize = EXT4_I(inode)->i_disksize;
5532 EXT4_I(inode)->i_disksize = attr->ia_size;
5533 rc = ext4_mark_inode_dirty(handle, inode);
5537 * We have to update i_size under i_data_sem together
5538 * with i_disksize to avoid races with writeback code
5539 * running ext4_wb_update_i_disksize().
5542 i_size_write(inode, attr->ia_size);
5544 EXT4_I(inode)->i_disksize = old_disksize;
5545 up_write(&EXT4_I(inode)->i_data_sem);
5546 ext4_journal_stop(handle);
5550 pagecache_isize_extended(inode, oldsize,
5552 } else if (ext4_should_journal_data(inode)) {
5553 ext4_wait_for_tail_page_commit(inode);
5558 * Truncate pagecache after we've waited for commit
5559 * in data=journal mode to make pages freeable.
5561 truncate_pagecache(inode, inode->i_size);
5563 * Call ext4_truncate() even if i_size didn't change to
5564 * truncate possible preallocated blocks.
5566 if (attr->ia_size <= oldsize) {
5567 rc = ext4_truncate(inode);
5572 up_write(&EXT4_I(inode)->i_mmap_sem);
5576 setattr_copy(inode, attr);
5577 mark_inode_dirty(inode);
5581 * If the call to ext4_truncate failed to get a transaction handle at
5582 * all, we need to clean up the in-core orphan list manually.
5584 if (orphan && inode->i_nlink)
5585 ext4_orphan_del(NULL, inode);
5587 if (!error && (ia_valid & ATTR_MODE))
5588 rc = posix_acl_chmod(inode, inode->i_mode);
5592 ext4_std_error(inode->i_sb, error);
5595 ext4_fc_stop_update(inode);
5599 int ext4_getattr(const struct path *path, struct kstat *stat,
5600 u32 request_mask, unsigned int query_flags)
5602 struct inode *inode = d_inode(path->dentry);
5603 struct ext4_inode *raw_inode;
5604 struct ext4_inode_info *ei = EXT4_I(inode);
5607 if ((request_mask & STATX_BTIME) &&
5608 EXT4_FITS_IN_INODE(raw_inode, ei, i_crtime)) {
5609 stat->result_mask |= STATX_BTIME;
5610 stat->btime.tv_sec = ei->i_crtime.tv_sec;
5611 stat->btime.tv_nsec = ei->i_crtime.tv_nsec;
5614 flags = ei->i_flags & EXT4_FL_USER_VISIBLE;
5615 if (flags & EXT4_APPEND_FL)
5616 stat->attributes |= STATX_ATTR_APPEND;
5617 if (flags & EXT4_COMPR_FL)
5618 stat->attributes |= STATX_ATTR_COMPRESSED;
5619 if (flags & EXT4_ENCRYPT_FL)
5620 stat->attributes |= STATX_ATTR_ENCRYPTED;
5621 if (flags & EXT4_IMMUTABLE_FL)
5622 stat->attributes |= STATX_ATTR_IMMUTABLE;
5623 if (flags & EXT4_NODUMP_FL)
5624 stat->attributes |= STATX_ATTR_NODUMP;
5625 if (flags & EXT4_VERITY_FL)
5626 stat->attributes |= STATX_ATTR_VERITY;
5628 stat->attributes_mask |= (STATX_ATTR_APPEND |
5629 STATX_ATTR_COMPRESSED |
5630 STATX_ATTR_ENCRYPTED |
5631 STATX_ATTR_IMMUTABLE |
5635 generic_fillattr(inode, stat);
5639 int ext4_file_getattr(const struct path *path, struct kstat *stat,
5640 u32 request_mask, unsigned int query_flags)
5642 struct inode *inode = d_inode(path->dentry);
5643 u64 delalloc_blocks;
5645 ext4_getattr(path, stat, request_mask, query_flags);
5648 * If there is inline data in the inode, the inode will normally not
5649 * have data blocks allocated (it may have an external xattr block).
5650 * Report at least one sector for such files, so tools like tar, rsync,
5651 * others don't incorrectly think the file is completely sparse.
5653 if (unlikely(ext4_has_inline_data(inode)))
5654 stat->blocks += (stat->size + 511) >> 9;
5657 * We can't update i_blocks if the block allocation is delayed
5658 * otherwise in the case of system crash before the real block
5659 * allocation is done, we will have i_blocks inconsistent with
5660 * on-disk file blocks.
5661 * We always keep i_blocks updated together with real
5662 * allocation. But to not confuse with user, stat
5663 * will return the blocks that include the delayed allocation
5664 * blocks for this file.
5666 delalloc_blocks = EXT4_C2B(EXT4_SB(inode->i_sb),
5667 EXT4_I(inode)->i_reserved_data_blocks);
5668 stat->blocks += delalloc_blocks << (inode->i_sb->s_blocksize_bits - 9);
5672 static int ext4_index_trans_blocks(struct inode *inode, int lblocks,
5675 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
5676 return ext4_ind_trans_blocks(inode, lblocks);
5677 return ext4_ext_index_trans_blocks(inode, pextents);
5681 * Account for index blocks, block groups bitmaps and block group
5682 * descriptor blocks if modify datablocks and index blocks
5683 * worse case, the indexs blocks spread over different block groups
5685 * If datablocks are discontiguous, they are possible to spread over
5686 * different block groups too. If they are contiguous, with flexbg,
5687 * they could still across block group boundary.
5689 * Also account for superblock, inode, quota and xattr blocks
5691 static int ext4_meta_trans_blocks(struct inode *inode, int lblocks,
5694 ext4_group_t groups, ngroups = ext4_get_groups_count(inode->i_sb);
5700 * How many index blocks need to touch to map @lblocks logical blocks
5701 * to @pextents physical extents?
5703 idxblocks = ext4_index_trans_blocks(inode, lblocks, pextents);
5708 * Now let's see how many group bitmaps and group descriptors need
5711 groups = idxblocks + pextents;
5713 if (groups > ngroups)
5715 if (groups > EXT4_SB(inode->i_sb)->s_gdb_count)
5716 gdpblocks = EXT4_SB(inode->i_sb)->s_gdb_count;
5718 /* bitmaps and block group descriptor blocks */
5719 ret += groups + gdpblocks;
5721 /* Blocks for super block, inode, quota and xattr blocks */
5722 ret += EXT4_META_TRANS_BLOCKS(inode->i_sb);
5728 * Calculate the total number of credits to reserve to fit
5729 * the modification of a single pages into a single transaction,
5730 * which may include multiple chunks of block allocations.
5732 * This could be called via ext4_write_begin()
5734 * We need to consider the worse case, when
5735 * one new block per extent.
5737 int ext4_writepage_trans_blocks(struct inode *inode)
5739 int bpp = ext4_journal_blocks_per_page(inode);
5742 ret = ext4_meta_trans_blocks(inode, bpp, bpp);
5744 /* Account for data blocks for journalled mode */
5745 if (ext4_should_journal_data(inode))
5751 * Calculate the journal credits for a chunk of data modification.
5753 * This is called from DIO, fallocate or whoever calling
5754 * ext4_map_blocks() to map/allocate a chunk of contiguous disk blocks.
5756 * journal buffers for data blocks are not included here, as DIO
5757 * and fallocate do no need to journal data buffers.
5759 int ext4_chunk_trans_blocks(struct inode *inode, int nrblocks)
5761 return ext4_meta_trans_blocks(inode, nrblocks, 1);
5765 * The caller must have previously called ext4_reserve_inode_write().
5766 * Give this, we know that the caller already has write access to iloc->bh.
5768 int ext4_mark_iloc_dirty(handle_t *handle,
5769 struct inode *inode, struct ext4_iloc *iloc)
5773 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb)))) {
5777 ext4_fc_track_inode(handle, inode);
5780 * ea_inodes are using i_version for storing reference count, don't
5783 if (IS_I_VERSION(inode) &&
5784 !(EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL))
5785 inode_inc_iversion(inode);
5787 /* the do_update_inode consumes one bh->b_count */
5790 /* ext4_do_update_inode() does jbd2_journal_dirty_metadata */
5791 err = ext4_do_update_inode(handle, inode, iloc);
5797 * On success, We end up with an outstanding reference count against
5798 * iloc->bh. This _must_ be cleaned up later.
5802 ext4_reserve_inode_write(handle_t *handle, struct inode *inode,
5803 struct ext4_iloc *iloc)
5807 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
5810 err = ext4_get_inode_loc(inode, iloc);
5812 BUFFER_TRACE(iloc->bh, "get_write_access");
5813 err = ext4_journal_get_write_access(handle, iloc->bh);
5819 ext4_std_error(inode->i_sb, err);
5823 static int __ext4_expand_extra_isize(struct inode *inode,
5824 unsigned int new_extra_isize,
5825 struct ext4_iloc *iloc,
5826 handle_t *handle, int *no_expand)
5828 struct ext4_inode *raw_inode;
5829 struct ext4_xattr_ibody_header *header;
5830 unsigned int inode_size = EXT4_INODE_SIZE(inode->i_sb);
5831 struct ext4_inode_info *ei = EXT4_I(inode);
5834 /* this was checked at iget time, but double check for good measure */
5835 if ((EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize > inode_size) ||
5836 (ei->i_extra_isize & 3)) {
5837 EXT4_ERROR_INODE(inode, "bad extra_isize %u (inode size %u)",
5839 EXT4_INODE_SIZE(inode->i_sb));
5840 return -EFSCORRUPTED;
5842 if ((new_extra_isize < ei->i_extra_isize) ||
5843 (new_extra_isize < 4) ||
5844 (new_extra_isize > inode_size - EXT4_GOOD_OLD_INODE_SIZE))
5845 return -EINVAL; /* Should never happen */
5847 raw_inode = ext4_raw_inode(iloc);
5849 header = IHDR(inode, raw_inode);
5851 /* No extended attributes present */
5852 if (!ext4_test_inode_state(inode, EXT4_STATE_XATTR) ||
5853 header->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC)) {
5854 memset((void *)raw_inode + EXT4_GOOD_OLD_INODE_SIZE +
5855 EXT4_I(inode)->i_extra_isize, 0,
5856 new_extra_isize - EXT4_I(inode)->i_extra_isize);
5857 EXT4_I(inode)->i_extra_isize = new_extra_isize;
5861 /* try to expand with EAs present */
5862 error = ext4_expand_extra_isize_ea(inode, new_extra_isize,
5866 * Inode size expansion failed; don't try again
5875 * Expand an inode by new_extra_isize bytes.
5876 * Returns 0 on success or negative error number on failure.
5878 static int ext4_try_to_expand_extra_isize(struct inode *inode,
5879 unsigned int new_extra_isize,
5880 struct ext4_iloc iloc,
5886 if (ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND))
5890 * In nojournal mode, we can immediately attempt to expand
5891 * the inode. When journaled, we first need to obtain extra
5892 * buffer credits since we may write into the EA block
5893 * with this same handle. If journal_extend fails, then it will
5894 * only result in a minor loss of functionality for that inode.
5895 * If this is felt to be critical, then e2fsck should be run to
5896 * force a large enough s_min_extra_isize.
5898 if (ext4_journal_extend(handle,
5899 EXT4_DATA_TRANS_BLOCKS(inode->i_sb), 0) != 0)
5902 if (ext4_write_trylock_xattr(inode, &no_expand) == 0)
5905 error = __ext4_expand_extra_isize(inode, new_extra_isize, &iloc,
5906 handle, &no_expand);
5907 ext4_write_unlock_xattr(inode, &no_expand);
5912 int ext4_expand_extra_isize(struct inode *inode,
5913 unsigned int new_extra_isize,
5914 struct ext4_iloc *iloc)
5920 if (ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND)) {
5925 handle = ext4_journal_start(inode, EXT4_HT_INODE,
5926 EXT4_DATA_TRANS_BLOCKS(inode->i_sb));
5927 if (IS_ERR(handle)) {
5928 error = PTR_ERR(handle);
5933 ext4_write_lock_xattr(inode, &no_expand);
5935 BUFFER_TRACE(iloc->bh, "get_write_access");
5936 error = ext4_journal_get_write_access(handle, iloc->bh);
5942 error = __ext4_expand_extra_isize(inode, new_extra_isize, iloc,
5943 handle, &no_expand);
5945 rc = ext4_mark_iloc_dirty(handle, inode, iloc);
5950 ext4_write_unlock_xattr(inode, &no_expand);
5951 ext4_journal_stop(handle);
5956 * What we do here is to mark the in-core inode as clean with respect to inode
5957 * dirtiness (it may still be data-dirty).
5958 * This means that the in-core inode may be reaped by prune_icache
5959 * without having to perform any I/O. This is a very good thing,
5960 * because *any* task may call prune_icache - even ones which
5961 * have a transaction open against a different journal.
5963 * Is this cheating? Not really. Sure, we haven't written the
5964 * inode out, but prune_icache isn't a user-visible syncing function.
5965 * Whenever the user wants stuff synced (sys_sync, sys_msync, sys_fsync)
5966 * we start and wait on commits.
5968 int __ext4_mark_inode_dirty(handle_t *handle, struct inode *inode,
5969 const char *func, unsigned int line)
5971 struct ext4_iloc iloc;
5972 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
5976 trace_ext4_mark_inode_dirty(inode, _RET_IP_);
5977 err = ext4_reserve_inode_write(handle, inode, &iloc);
5981 if (EXT4_I(inode)->i_extra_isize < sbi->s_want_extra_isize)
5982 ext4_try_to_expand_extra_isize(inode, sbi->s_want_extra_isize,
5985 err = ext4_mark_iloc_dirty(handle, inode, &iloc);
5988 ext4_error_inode_err(inode, func, line, 0, err,
5989 "mark_inode_dirty error");
5994 * ext4_dirty_inode() is called from __mark_inode_dirty()
5996 * We're really interested in the case where a file is being extended.
5997 * i_size has been changed by generic_commit_write() and we thus need
5998 * to include the updated inode in the current transaction.
6000 * Also, dquot_alloc_block() will always dirty the inode when blocks
6001 * are allocated to the file.
6003 * If the inode is marked synchronous, we don't honour that here - doing
6004 * so would cause a commit on atime updates, which we don't bother doing.
6005 * We handle synchronous inodes at the highest possible level.
6007 * If only the I_DIRTY_TIME flag is set, we can skip everything. If
6008 * I_DIRTY_TIME and I_DIRTY_SYNC is set, the only inode fields we need
6009 * to copy into the on-disk inode structure are the timestamp files.
6011 void ext4_dirty_inode(struct inode *inode, int flags)
6015 if (flags == I_DIRTY_TIME)
6017 handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
6021 ext4_mark_inode_dirty(handle, inode);
6023 ext4_journal_stop(handle);
6028 int ext4_change_inode_journal_flag(struct inode *inode, int val)
6033 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
6036 * We have to be very careful here: changing a data block's
6037 * journaling status dynamically is dangerous. If we write a
6038 * data block to the journal, change the status and then delete
6039 * that block, we risk forgetting to revoke the old log record
6040 * from the journal and so a subsequent replay can corrupt data.
6041 * So, first we make sure that the journal is empty and that
6042 * nobody is changing anything.
6045 journal = EXT4_JOURNAL(inode);
6048 if (is_journal_aborted(journal))
6051 /* Wait for all existing dio workers */
6052 inode_dio_wait(inode);
6055 * Before flushing the journal and switching inode's aops, we have
6056 * to flush all dirty data the inode has. There can be outstanding
6057 * delayed allocations, there can be unwritten extents created by
6058 * fallocate or buffered writes in dioread_nolock mode covered by
6059 * dirty data which can be converted only after flushing the dirty
6060 * data (and journalled aops don't know how to handle these cases).
6063 down_write(&EXT4_I(inode)->i_mmap_sem);
6064 err = filemap_write_and_wait(inode->i_mapping);
6066 up_write(&EXT4_I(inode)->i_mmap_sem);
6071 percpu_down_write(&sbi->s_writepages_rwsem);
6072 jbd2_journal_lock_updates(journal);
6075 * OK, there are no updates running now, and all cached data is
6076 * synced to disk. We are now in a completely consistent state
6077 * which doesn't have anything in the journal, and we know that
6078 * no filesystem updates are running, so it is safe to modify
6079 * the inode's in-core data-journaling state flag now.
6083 ext4_set_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
6085 err = jbd2_journal_flush(journal);
6087 jbd2_journal_unlock_updates(journal);
6088 percpu_up_write(&sbi->s_writepages_rwsem);
6091 ext4_clear_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
6093 ext4_set_aops(inode);
6095 jbd2_journal_unlock_updates(journal);
6096 percpu_up_write(&sbi->s_writepages_rwsem);
6099 up_write(&EXT4_I(inode)->i_mmap_sem);
6101 /* Finally we can mark the inode as dirty. */
6103 handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
6105 return PTR_ERR(handle);
6107 ext4_fc_mark_ineligible(inode->i_sb,
6108 EXT4_FC_REASON_JOURNAL_FLAG_CHANGE);
6109 err = ext4_mark_inode_dirty(handle, inode);
6110 ext4_handle_sync(handle);
6111 ext4_journal_stop(handle);
6112 ext4_std_error(inode->i_sb, err);
6117 static int ext4_bh_unmapped(handle_t *handle, struct buffer_head *bh)
6119 return !buffer_mapped(bh);
6122 vm_fault_t ext4_page_mkwrite(struct vm_fault *vmf)
6124 struct vm_area_struct *vma = vmf->vma;
6125 struct page *page = vmf->page;
6130 struct file *file = vma->vm_file;
6131 struct inode *inode = file_inode(file);
6132 struct address_space *mapping = inode->i_mapping;
6134 get_block_t *get_block;
6137 if (unlikely(IS_IMMUTABLE(inode)))
6138 return VM_FAULT_SIGBUS;
6140 sb_start_pagefault(inode->i_sb);
6141 file_update_time(vma->vm_file);
6143 down_read(&EXT4_I(inode)->i_mmap_sem);
6145 err = ext4_convert_inline_data(inode);
6150 * On data journalling we skip straight to the transaction handle:
6151 * there's no delalloc; page truncated will be checked later; the
6152 * early return w/ all buffers mapped (calculates size/len) can't
6153 * be used; and there's no dioread_nolock, so only ext4_get_block.
6155 if (ext4_should_journal_data(inode))
6158 /* Delalloc case is easy... */
6159 if (test_opt(inode->i_sb, DELALLOC) &&
6160 !ext4_nonda_switch(inode->i_sb)) {
6162 err = block_page_mkwrite(vma, vmf,
6163 ext4_da_get_block_prep);
6164 } while (err == -ENOSPC &&
6165 ext4_should_retry_alloc(inode->i_sb, &retries));
6170 size = i_size_read(inode);
6171 /* Page got truncated from under us? */
6172 if (page->mapping != mapping || page_offset(page) > size) {
6174 ret = VM_FAULT_NOPAGE;
6178 if (page->index == size >> PAGE_SHIFT)
6179 len = size & ~PAGE_MASK;
6183 * Return if we have all the buffers mapped. This avoids the need to do
6184 * journal_start/journal_stop which can block and take a long time
6186 * This cannot be done for data journalling, as we have to add the
6187 * inode to the transaction's list to writeprotect pages on commit.
6189 if (page_has_buffers(page)) {
6190 if (!ext4_walk_page_buffers(NULL, page_buffers(page),
6192 ext4_bh_unmapped)) {
6193 /* Wait so that we don't change page under IO */
6194 wait_for_stable_page(page);
6195 ret = VM_FAULT_LOCKED;
6200 /* OK, we need to fill the hole... */
6201 if (ext4_should_dioread_nolock(inode))
6202 get_block = ext4_get_block_unwritten;
6204 get_block = ext4_get_block;
6206 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
6207 ext4_writepage_trans_blocks(inode));
6208 if (IS_ERR(handle)) {
6209 ret = VM_FAULT_SIGBUS;
6213 * Data journalling can't use block_page_mkwrite() because it
6214 * will set_buffer_dirty() before do_journal_get_write_access()
6215 * thus might hit warning messages for dirty metadata buffers.
6217 if (!ext4_should_journal_data(inode)) {
6218 err = block_page_mkwrite(vma, vmf, get_block);
6221 size = i_size_read(inode);
6222 /* Page got truncated from under us? */
6223 if (page->mapping != mapping || page_offset(page) > size) {
6224 ret = VM_FAULT_NOPAGE;
6228 if (page->index == size >> PAGE_SHIFT)
6229 len = size & ~PAGE_MASK;
6233 err = __block_write_begin(page, 0, len, ext4_get_block);
6235 ret = VM_FAULT_SIGBUS;
6236 if (ext4_walk_page_buffers(handle, page_buffers(page),
6237 0, len, NULL, do_journal_get_write_access))
6239 if (ext4_walk_page_buffers(handle, page_buffers(page),
6240 0, len, NULL, write_end_fn))
6242 if (ext4_jbd2_inode_add_write(handle, inode,
6243 page_offset(page), len))
6245 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
6250 ext4_journal_stop(handle);
6251 if (err == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
6254 ret = block_page_mkwrite_return(err);
6256 up_read(&EXT4_I(inode)->i_mmap_sem);
6257 sb_end_pagefault(inode->i_sb);
6261 ext4_journal_stop(handle);
6265 vm_fault_t ext4_filemap_fault(struct vm_fault *vmf)
6267 struct inode *inode = file_inode(vmf->vma->vm_file);
6270 down_read(&EXT4_I(inode)->i_mmap_sem);
6271 ret = filemap_fault(vmf);
6272 up_read(&EXT4_I(inode)->i_mmap_sem);