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/mount.h>
24 #include <linux/time.h>
25 #include <linux/highuid.h>
26 #include <linux/pagemap.h>
27 #include <linux/dax.h>
28 #include <linux/quotaops.h>
29 #include <linux/string.h>
30 #include <linux/buffer_head.h>
31 #include <linux/writeback.h>
32 #include <linux/pagevec.h>
33 #include <linux/mpage.h>
34 #include <linux/namei.h>
35 #include <linux/uio.h>
36 #include <linux/bio.h>
37 #include <linux/workqueue.h>
38 #include <linux/kernel.h>
39 #include <linux/printk.h>
40 #include <linux/slab.h>
41 #include <linux/bitops.h>
42 #include <linux/iomap.h>
43 #include <linux/iversion.h>
45 #include "ext4_jbd2.h"
50 #include <trace/events/ext4.h>
52 static __u32 ext4_inode_csum(struct inode *inode, struct ext4_inode *raw,
53 struct ext4_inode_info *ei)
55 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
58 int offset = offsetof(struct ext4_inode, i_checksum_lo);
59 unsigned int csum_size = sizeof(dummy_csum);
61 csum = ext4_chksum(sbi, ei->i_csum_seed, (__u8 *)raw, offset);
62 csum = ext4_chksum(sbi, csum, (__u8 *)&dummy_csum, csum_size);
64 csum = ext4_chksum(sbi, csum, (__u8 *)raw + offset,
65 EXT4_GOOD_OLD_INODE_SIZE - offset);
67 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
68 offset = offsetof(struct ext4_inode, i_checksum_hi);
69 csum = ext4_chksum(sbi, csum, (__u8 *)raw +
70 EXT4_GOOD_OLD_INODE_SIZE,
71 offset - EXT4_GOOD_OLD_INODE_SIZE);
72 if (EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi)) {
73 csum = ext4_chksum(sbi, csum, (__u8 *)&dummy_csum,
77 csum = ext4_chksum(sbi, csum, (__u8 *)raw + offset,
78 EXT4_INODE_SIZE(inode->i_sb) - offset);
84 static int ext4_inode_csum_verify(struct inode *inode, struct ext4_inode *raw,
85 struct ext4_inode_info *ei)
87 __u32 provided, calculated;
89 if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
90 cpu_to_le32(EXT4_OS_LINUX) ||
91 !ext4_has_metadata_csum(inode->i_sb))
94 provided = le16_to_cpu(raw->i_checksum_lo);
95 calculated = ext4_inode_csum(inode, raw, ei);
96 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
97 EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi))
98 provided |= ((__u32)le16_to_cpu(raw->i_checksum_hi)) << 16;
100 calculated &= 0xFFFF;
102 return provided == calculated;
105 void ext4_inode_csum_set(struct inode *inode, struct ext4_inode *raw,
106 struct ext4_inode_info *ei)
110 if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
111 cpu_to_le32(EXT4_OS_LINUX) ||
112 !ext4_has_metadata_csum(inode->i_sb))
115 csum = ext4_inode_csum(inode, raw, ei);
116 raw->i_checksum_lo = cpu_to_le16(csum & 0xFFFF);
117 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
118 EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi))
119 raw->i_checksum_hi = cpu_to_le16(csum >> 16);
122 static inline int ext4_begin_ordered_truncate(struct inode *inode,
125 trace_ext4_begin_ordered_truncate(inode, new_size);
127 * If jinode is zero, then we never opened the file for
128 * writing, so there's no need to call
129 * jbd2_journal_begin_ordered_truncate() since there's no
130 * outstanding writes we need to flush.
132 if (!EXT4_I(inode)->jinode)
134 return jbd2_journal_begin_ordered_truncate(EXT4_JOURNAL(inode),
135 EXT4_I(inode)->jinode,
139 static void ext4_invalidatepage(struct page *page, unsigned int offset,
140 unsigned int length);
141 static int __ext4_journalled_writepage(struct page *page, unsigned int len);
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 (EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL)
183 ext4_evict_ea_inode(inode);
184 if (inode->i_nlink) {
186 * When journalling data dirty buffers are tracked only in the
187 * journal. So although mm thinks everything is clean and
188 * ready for reaping the inode might still have some pages to
189 * write in the running transaction or waiting to be
190 * checkpointed. Thus calling jbd2_journal_invalidatepage()
191 * (via truncate_inode_pages()) to discard these buffers can
192 * cause data loss. Also even if we did not discard these
193 * buffers, we would have no way to find them after the inode
194 * is reaped and thus user could see stale data if he tries to
195 * read them before the transaction is checkpointed. So be
196 * careful and force everything to disk here... We use
197 * ei->i_datasync_tid to store the newest transaction
198 * containing inode's data.
200 * Note that directories do not have this problem because they
201 * don't use page cache.
203 if (inode->i_ino != EXT4_JOURNAL_INO &&
204 ext4_should_journal_data(inode) &&
205 (S_ISLNK(inode->i_mode) || S_ISREG(inode->i_mode)) &&
206 inode->i_data.nrpages) {
207 journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
208 tid_t commit_tid = EXT4_I(inode)->i_datasync_tid;
210 jbd2_complete_transaction(journal, commit_tid);
211 filemap_write_and_wait(&inode->i_data);
213 truncate_inode_pages_final(&inode->i_data);
218 if (is_bad_inode(inode))
220 dquot_initialize(inode);
222 if (ext4_should_order_data(inode))
223 ext4_begin_ordered_truncate(inode, 0);
224 truncate_inode_pages_final(&inode->i_data);
227 * For inodes with journalled data, transaction commit could have
228 * dirtied the inode. And for inodes with dioread_nolock, unwritten
229 * extents converting worker could merge extents and also have dirtied
230 * the inode. Flush worker is ignoring it because of I_FREEING flag but
231 * we still need to remove the inode from the writeback lists.
233 if (!list_empty_careful(&inode->i_io_list))
234 inode_io_list_del(inode);
237 * Protect us against freezing - iput() caller didn't have to have any
238 * protection against it. When we are in a running transaction though,
239 * we are already protected against freezing and we cannot grab further
240 * protection due to lock ordering constraints.
242 if (!ext4_journal_current_handle()) {
243 sb_start_intwrite(inode->i_sb);
244 freeze_protected = true;
247 if (!IS_NOQUOTA(inode))
248 extra_credits += EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb);
251 * Block bitmap, group descriptor, and inode are accounted in both
252 * ext4_blocks_for_truncate() and extra_credits. So subtract 3.
254 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE,
255 ext4_blocks_for_truncate(inode) + extra_credits - 3);
256 if (IS_ERR(handle)) {
257 ext4_std_error(inode->i_sb, PTR_ERR(handle));
259 * If we're going to skip the normal cleanup, we still need to
260 * make sure that the in-core orphan linked list is properly
263 ext4_orphan_del(NULL, inode);
264 if (freeze_protected)
265 sb_end_intwrite(inode->i_sb);
270 ext4_handle_sync(handle);
273 * Set inode->i_size to 0 before calling ext4_truncate(). We need
274 * special handling of symlinks here because i_size is used to
275 * determine whether ext4_inode_info->i_data contains symlink data or
276 * block mappings. Setting i_size to 0 will remove its fast symlink
277 * status. Erase i_data so that it becomes a valid empty block map.
279 if (ext4_inode_is_fast_symlink(inode))
280 memset(EXT4_I(inode)->i_data, 0, sizeof(EXT4_I(inode)->i_data));
282 err = ext4_mark_inode_dirty(handle, inode);
284 ext4_warning(inode->i_sb,
285 "couldn't mark inode dirty (err %d)", err);
288 if (inode->i_blocks) {
289 err = ext4_truncate(inode);
291 ext4_error_err(inode->i_sb, -err,
292 "couldn't truncate inode %lu (err %d)",
298 /* Remove xattr references. */
299 err = ext4_xattr_delete_inode(handle, inode, &ea_inode_array,
302 ext4_warning(inode->i_sb, "xattr delete (err %d)", err);
304 ext4_journal_stop(handle);
305 ext4_orphan_del(NULL, inode);
306 if (freeze_protected)
307 sb_end_intwrite(inode->i_sb);
308 ext4_xattr_inode_array_free(ea_inode_array);
313 * Kill off the orphan record which ext4_truncate created.
314 * AKPM: I think this can be inside the above `if'.
315 * Note that ext4_orphan_del() has to be able to cope with the
316 * deletion of a non-existent orphan - this is because we don't
317 * know if ext4_truncate() actually created an orphan record.
318 * (Well, we could do this if we need to, but heck - it works)
320 ext4_orphan_del(handle, inode);
321 EXT4_I(inode)->i_dtime = (__u32)ktime_get_real_seconds();
324 * One subtle ordering requirement: if anything has gone wrong
325 * (transaction abort, IO errors, whatever), then we can still
326 * do these next steps (the fs will already have been marked as
327 * having errors), but we can't free the inode if the mark_dirty
330 if (ext4_mark_inode_dirty(handle, inode))
331 /* If that failed, just do the required in-core inode clear. */
332 ext4_clear_inode(inode);
334 ext4_free_inode(handle, inode);
335 ext4_journal_stop(handle);
336 if (freeze_protected)
337 sb_end_intwrite(inode->i_sb);
338 ext4_xattr_inode_array_free(ea_inode_array);
342 * Check out some where else accidentally dirty the evicting inode,
343 * which may probably cause inode use-after-free issues later.
345 WARN_ON_ONCE(!list_empty_careful(&inode->i_io_list));
347 if (!list_empty(&EXT4_I(inode)->i_fc_list))
348 ext4_fc_mark_ineligible(inode->i_sb, EXT4_FC_REASON_NOMEM, NULL);
349 ext4_clear_inode(inode); /* We must guarantee clearing of inode... */
353 qsize_t *ext4_get_reserved_space(struct inode *inode)
355 return &EXT4_I(inode)->i_reserved_quota;
360 * Called with i_data_sem down, which is important since we can call
361 * ext4_discard_preallocations() from here.
363 void ext4_da_update_reserve_space(struct inode *inode,
364 int used, int quota_claim)
366 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
367 struct ext4_inode_info *ei = EXT4_I(inode);
369 spin_lock(&ei->i_block_reservation_lock);
370 trace_ext4_da_update_reserve_space(inode, used, quota_claim);
371 if (unlikely(used > ei->i_reserved_data_blocks)) {
372 ext4_warning(inode->i_sb, "%s: ino %lu, used %d "
373 "with only %d reserved data blocks",
374 __func__, inode->i_ino, used,
375 ei->i_reserved_data_blocks);
377 used = ei->i_reserved_data_blocks;
380 /* Update per-inode reservations */
381 ei->i_reserved_data_blocks -= used;
382 percpu_counter_sub(&sbi->s_dirtyclusters_counter, used);
384 spin_unlock(&ei->i_block_reservation_lock);
386 /* Update quota subsystem for data blocks */
388 dquot_claim_block(inode, EXT4_C2B(sbi, used));
391 * We did fallocate with an offset that is already delayed
392 * allocated. So on delayed allocated writeback we should
393 * not re-claim the quota for fallocated blocks.
395 dquot_release_reservation_block(inode, EXT4_C2B(sbi, used));
399 * If we have done all the pending block allocations and if
400 * there aren't any writers on the inode, we can discard the
401 * inode's preallocations.
403 if ((ei->i_reserved_data_blocks == 0) &&
404 !inode_is_open_for_write(inode))
405 ext4_discard_preallocations(inode, 0);
408 static int __check_block_validity(struct inode *inode, const char *func,
410 struct ext4_map_blocks *map)
412 if (ext4_has_feature_journal(inode->i_sb) &&
414 le32_to_cpu(EXT4_SB(inode->i_sb)->s_es->s_journal_inum)))
416 if (!ext4_inode_block_valid(inode, map->m_pblk, map->m_len)) {
417 ext4_error_inode(inode, func, line, map->m_pblk,
418 "lblock %lu mapped to illegal pblock %llu "
419 "(length %d)", (unsigned long) map->m_lblk,
420 map->m_pblk, map->m_len);
421 return -EFSCORRUPTED;
426 int ext4_issue_zeroout(struct inode *inode, ext4_lblk_t lblk, ext4_fsblk_t pblk,
431 if (IS_ENCRYPTED(inode) && S_ISREG(inode->i_mode))
432 return fscrypt_zeroout_range(inode, lblk, pblk, len);
434 ret = sb_issue_zeroout(inode->i_sb, pblk, len, GFP_NOFS);
441 #define check_block_validity(inode, map) \
442 __check_block_validity((inode), __func__, __LINE__, (map))
444 #ifdef ES_AGGRESSIVE_TEST
445 static void ext4_map_blocks_es_recheck(handle_t *handle,
447 struct ext4_map_blocks *es_map,
448 struct ext4_map_blocks *map,
455 * There is a race window that the result is not the same.
456 * e.g. xfstests #223 when dioread_nolock enables. The reason
457 * is that we lookup a block mapping in extent status tree with
458 * out taking i_data_sem. So at the time the unwritten extent
459 * could be converted.
461 down_read(&EXT4_I(inode)->i_data_sem);
462 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
463 retval = ext4_ext_map_blocks(handle, inode, map, 0);
465 retval = ext4_ind_map_blocks(handle, inode, map, 0);
467 up_read((&EXT4_I(inode)->i_data_sem));
470 * We don't check m_len because extent will be collpased in status
471 * tree. So the m_len might not equal.
473 if (es_map->m_lblk != map->m_lblk ||
474 es_map->m_flags != map->m_flags ||
475 es_map->m_pblk != map->m_pblk) {
476 printk("ES cache assertion failed for inode: %lu "
477 "es_cached ex [%d/%d/%llu/%x] != "
478 "found ex [%d/%d/%llu/%x] retval %d flags %x\n",
479 inode->i_ino, es_map->m_lblk, es_map->m_len,
480 es_map->m_pblk, es_map->m_flags, map->m_lblk,
481 map->m_len, map->m_pblk, map->m_flags,
485 #endif /* ES_AGGRESSIVE_TEST */
488 * The ext4_map_blocks() function tries to look up the requested blocks,
489 * and returns if the blocks are already mapped.
491 * Otherwise it takes the write lock of the i_data_sem and allocate blocks
492 * and store the allocated blocks in the result buffer head and mark it
495 * If file type is extents based, it will call ext4_ext_map_blocks(),
496 * Otherwise, call with ext4_ind_map_blocks() to handle indirect mapping
499 * On success, it returns the number of blocks being mapped or allocated. if
500 * create==0 and the blocks are pre-allocated and unwritten, the resulting @map
501 * is marked as unwritten. If the create == 1, it will mark @map as mapped.
503 * It returns 0 if plain look up failed (blocks have not been allocated), in
504 * that case, @map is returned as unmapped but we still do fill map->m_len to
505 * indicate the length of a hole starting at map->m_lblk.
507 * It returns the error in case of allocation failure.
509 int ext4_map_blocks(handle_t *handle, struct inode *inode,
510 struct ext4_map_blocks *map, int flags)
512 struct extent_status es;
515 #ifdef ES_AGGRESSIVE_TEST
516 struct ext4_map_blocks orig_map;
518 memcpy(&orig_map, map, sizeof(*map));
522 ext_debug(inode, "flag 0x%x, max_blocks %u, logical block %lu\n",
523 flags, map->m_len, (unsigned long) map->m_lblk);
526 * ext4_map_blocks returns an int, and m_len is an unsigned int
528 if (unlikely(map->m_len > INT_MAX))
529 map->m_len = INT_MAX;
531 /* We can handle the block number less than EXT_MAX_BLOCKS */
532 if (unlikely(map->m_lblk >= EXT_MAX_BLOCKS))
533 return -EFSCORRUPTED;
535 /* Lookup extent status tree firstly */
536 if (!(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_FC_REPLAY) &&
537 ext4_es_lookup_extent(inode, map->m_lblk, NULL, &es)) {
538 if (ext4_es_is_written(&es) || ext4_es_is_unwritten(&es)) {
539 map->m_pblk = ext4_es_pblock(&es) +
540 map->m_lblk - es.es_lblk;
541 map->m_flags |= ext4_es_is_written(&es) ?
542 EXT4_MAP_MAPPED : EXT4_MAP_UNWRITTEN;
543 retval = es.es_len - (map->m_lblk - es.es_lblk);
544 if (retval > map->m_len)
547 } else if (ext4_es_is_delayed(&es) || ext4_es_is_hole(&es)) {
549 retval = es.es_len - (map->m_lblk - es.es_lblk);
550 if (retval > map->m_len)
557 #ifdef ES_AGGRESSIVE_TEST
558 ext4_map_blocks_es_recheck(handle, inode, map,
565 * Try to see if we can get the block without requesting a new
568 down_read(&EXT4_I(inode)->i_data_sem);
569 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
570 retval = ext4_ext_map_blocks(handle, inode, map, 0);
572 retval = ext4_ind_map_blocks(handle, inode, map, 0);
577 if (unlikely(retval != map->m_len)) {
578 ext4_warning(inode->i_sb,
579 "ES len assertion failed for inode "
580 "%lu: retval %d != map->m_len %d",
581 inode->i_ino, retval, map->m_len);
585 status = map->m_flags & EXT4_MAP_UNWRITTEN ?
586 EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
587 if (!(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) &&
588 !(status & EXTENT_STATUS_WRITTEN) &&
589 ext4_es_scan_range(inode, &ext4_es_is_delayed, map->m_lblk,
590 map->m_lblk + map->m_len - 1))
591 status |= EXTENT_STATUS_DELAYED;
592 ret = ext4_es_insert_extent(inode, map->m_lblk,
593 map->m_len, map->m_pblk, status);
597 up_read((&EXT4_I(inode)->i_data_sem));
600 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
601 ret = check_block_validity(inode, map);
606 /* If it is only a block(s) look up */
607 if ((flags & EXT4_GET_BLOCKS_CREATE) == 0)
611 * Returns if the blocks have already allocated
613 * Note that if blocks have been preallocated
614 * ext4_ext_get_block() returns the create = 0
615 * with buffer head unmapped.
617 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED)
619 * If we need to convert extent to unwritten
620 * we continue and do the actual work in
621 * ext4_ext_map_blocks()
623 if (!(flags & EXT4_GET_BLOCKS_CONVERT_UNWRITTEN))
627 * Here we clear m_flags because after allocating an new extent,
628 * it will be set again.
630 map->m_flags &= ~EXT4_MAP_FLAGS;
633 * New blocks allocate and/or writing to unwritten extent
634 * will possibly result in updating i_data, so we take
635 * the write lock of i_data_sem, and call get_block()
636 * with create == 1 flag.
638 down_write(&EXT4_I(inode)->i_data_sem);
641 * We need to check for EXT4 here because migrate
642 * could have changed the inode type in between
644 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
645 retval = ext4_ext_map_blocks(handle, inode, map, flags);
647 retval = ext4_ind_map_blocks(handle, inode, map, flags);
649 if (retval > 0 && map->m_flags & EXT4_MAP_NEW) {
651 * We allocated new blocks which will result in
652 * i_data's format changing. Force the migrate
653 * to fail by clearing migrate flags
655 ext4_clear_inode_state(inode, EXT4_STATE_EXT_MIGRATE);
662 if (unlikely(retval != map->m_len)) {
663 ext4_warning(inode->i_sb,
664 "ES len assertion failed for inode "
665 "%lu: retval %d != map->m_len %d",
666 inode->i_ino, retval, map->m_len);
671 * We have to zeroout blocks before inserting them into extent
672 * status tree. Otherwise someone could look them up there and
673 * use them before they are really zeroed. We also have to
674 * unmap metadata before zeroing as otherwise writeback can
675 * overwrite zeros with stale data from block device.
677 if (flags & EXT4_GET_BLOCKS_ZERO &&
678 map->m_flags & EXT4_MAP_MAPPED &&
679 map->m_flags & EXT4_MAP_NEW) {
680 ret = ext4_issue_zeroout(inode, map->m_lblk,
681 map->m_pblk, map->m_len);
689 * If the extent has been zeroed out, we don't need to update
690 * extent status tree.
692 if ((flags & EXT4_GET_BLOCKS_PRE_IO) &&
693 ext4_es_lookup_extent(inode, map->m_lblk, NULL, &es)) {
694 if (ext4_es_is_written(&es))
697 status = map->m_flags & EXT4_MAP_UNWRITTEN ?
698 EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
699 if (!(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) &&
700 !(status & EXTENT_STATUS_WRITTEN) &&
701 ext4_es_scan_range(inode, &ext4_es_is_delayed, map->m_lblk,
702 map->m_lblk + map->m_len - 1))
703 status |= EXTENT_STATUS_DELAYED;
704 ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
705 map->m_pblk, status);
713 up_write((&EXT4_I(inode)->i_data_sem));
714 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
715 ret = check_block_validity(inode, map);
720 * Inodes with freshly allocated blocks where contents will be
721 * visible after transaction commit must be on transaction's
724 if (map->m_flags & EXT4_MAP_NEW &&
725 !(map->m_flags & EXT4_MAP_UNWRITTEN) &&
726 !(flags & EXT4_GET_BLOCKS_ZERO) &&
727 !ext4_is_quota_file(inode) &&
728 ext4_should_order_data(inode)) {
730 (loff_t)map->m_lblk << inode->i_blkbits;
731 loff_t length = (loff_t)map->m_len << inode->i_blkbits;
733 if (flags & EXT4_GET_BLOCKS_IO_SUBMIT)
734 ret = ext4_jbd2_inode_add_wait(handle, inode,
737 ret = ext4_jbd2_inode_add_write(handle, inode,
743 if (retval > 0 && (map->m_flags & EXT4_MAP_UNWRITTEN ||
744 map->m_flags & EXT4_MAP_MAPPED))
745 ext4_fc_track_range(handle, inode, map->m_lblk,
746 map->m_lblk + map->m_len - 1);
748 ext_debug(inode, "failed with err %d\n", retval);
753 * Update EXT4_MAP_FLAGS in bh->b_state. For buffer heads attached to pages
754 * we have to be careful as someone else may be manipulating b_state as well.
756 static void ext4_update_bh_state(struct buffer_head *bh, unsigned long flags)
758 unsigned long old_state;
759 unsigned long new_state;
761 flags &= EXT4_MAP_FLAGS;
763 /* Dummy buffer_head? Set non-atomically. */
765 bh->b_state = (bh->b_state & ~EXT4_MAP_FLAGS) | flags;
769 * Someone else may be modifying b_state. Be careful! This is ugly but
770 * once we get rid of using bh as a container for mapping information
771 * to pass to / from get_block functions, this can go away.
774 old_state = READ_ONCE(bh->b_state);
775 new_state = (old_state & ~EXT4_MAP_FLAGS) | flags;
777 cmpxchg(&bh->b_state, old_state, new_state) != old_state));
780 static int _ext4_get_block(struct inode *inode, sector_t iblock,
781 struct buffer_head *bh, int flags)
783 struct ext4_map_blocks map;
786 if (ext4_has_inline_data(inode))
790 map.m_len = bh->b_size >> inode->i_blkbits;
792 ret = ext4_map_blocks(ext4_journal_current_handle(), inode, &map,
795 map_bh(bh, inode->i_sb, map.m_pblk);
796 ext4_update_bh_state(bh, map.m_flags);
797 bh->b_size = inode->i_sb->s_blocksize * map.m_len;
799 } else if (ret == 0) {
800 /* hole case, need to fill in bh->b_size */
801 bh->b_size = inode->i_sb->s_blocksize * map.m_len;
806 int ext4_get_block(struct inode *inode, sector_t iblock,
807 struct buffer_head *bh, int create)
809 return _ext4_get_block(inode, iblock, bh,
810 create ? EXT4_GET_BLOCKS_CREATE : 0);
814 * Get block function used when preparing for buffered write if we require
815 * creating an unwritten extent if blocks haven't been allocated. The extent
816 * will be converted to written after the IO is complete.
818 int ext4_get_block_unwritten(struct inode *inode, sector_t iblock,
819 struct buffer_head *bh_result, int create)
821 ext4_debug("ext4_get_block_unwritten: inode %lu, create flag %d\n",
822 inode->i_ino, create);
823 return _ext4_get_block(inode, iblock, bh_result,
824 EXT4_GET_BLOCKS_IO_CREATE_EXT);
827 /* Maximum number of blocks we map for direct IO at once. */
828 #define DIO_MAX_BLOCKS 4096
831 * `handle' can be NULL if create is zero
833 struct buffer_head *ext4_getblk(handle_t *handle, struct inode *inode,
834 ext4_lblk_t block, int map_flags)
836 struct ext4_map_blocks map;
837 struct buffer_head *bh;
838 int create = map_flags & EXT4_GET_BLOCKS_CREATE;
841 ASSERT((EXT4_SB(inode->i_sb)->s_mount_state & EXT4_FC_REPLAY)
842 || handle != NULL || create == 0);
846 err = ext4_map_blocks(handle, inode, &map, map_flags);
849 return create ? ERR_PTR(-ENOSPC) : NULL;
853 bh = sb_getblk(inode->i_sb, map.m_pblk);
855 return ERR_PTR(-ENOMEM);
856 if (map.m_flags & EXT4_MAP_NEW) {
858 ASSERT((EXT4_SB(inode->i_sb)->s_mount_state & EXT4_FC_REPLAY)
859 || (handle != NULL));
862 * Now that we do not always journal data, we should
863 * keep in mind whether this should always journal the
864 * new buffer as metadata. For now, regular file
865 * writes use ext4_get_block instead, so it's not a
869 BUFFER_TRACE(bh, "call get_create_access");
870 err = ext4_journal_get_create_access(handle, inode->i_sb, bh,
876 if (!buffer_uptodate(bh)) {
877 memset(bh->b_data, 0, inode->i_sb->s_blocksize);
878 set_buffer_uptodate(bh);
881 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
882 err = ext4_handle_dirty_metadata(handle, inode, bh);
886 BUFFER_TRACE(bh, "not a new buffer");
893 struct buffer_head *ext4_bread(handle_t *handle, struct inode *inode,
894 ext4_lblk_t block, int map_flags)
896 struct buffer_head *bh;
899 bh = ext4_getblk(handle, inode, block, map_flags);
902 if (!bh || ext4_buffer_uptodate(bh))
905 ret = ext4_read_bh_lock(bh, REQ_META | REQ_PRIO, true);
913 /* Read a contiguous batch of blocks. */
914 int ext4_bread_batch(struct inode *inode, ext4_lblk_t block, int bh_count,
915 bool wait, struct buffer_head **bhs)
919 for (i = 0; i < bh_count; i++) {
920 bhs[i] = ext4_getblk(NULL, inode, block + i, 0 /* map_flags */);
921 if (IS_ERR(bhs[i])) {
922 err = PTR_ERR(bhs[i]);
928 for (i = 0; i < bh_count; i++)
929 /* Note that NULL bhs[i] is valid because of holes. */
930 if (bhs[i] && !ext4_buffer_uptodate(bhs[i]))
931 ext4_read_bh_lock(bhs[i], REQ_META | REQ_PRIO, false);
936 for (i = 0; i < bh_count; i++)
938 wait_on_buffer(bhs[i]);
940 for (i = 0; i < bh_count; i++) {
941 if (bhs[i] && !buffer_uptodate(bhs[i])) {
949 for (i = 0; i < bh_count; i++) {
956 int ext4_walk_page_buffers(handle_t *handle, struct inode *inode,
957 struct buffer_head *head,
961 int (*fn)(handle_t *handle, struct inode *inode,
962 struct buffer_head *bh))
964 struct buffer_head *bh;
965 unsigned block_start, block_end;
966 unsigned blocksize = head->b_size;
968 struct buffer_head *next;
970 for (bh = head, block_start = 0;
971 ret == 0 && (bh != head || !block_start);
972 block_start = block_end, bh = next) {
973 next = bh->b_this_page;
974 block_end = block_start + blocksize;
975 if (block_end <= from || block_start >= to) {
976 if (partial && !buffer_uptodate(bh))
980 err = (*fn)(handle, inode, bh);
988 * To preserve ordering, it is essential that the hole instantiation and
989 * the data write be encapsulated in a single transaction. We cannot
990 * close off a transaction and start a new one between the ext4_get_block()
991 * and the commit_write(). So doing the jbd2_journal_start at the start of
992 * prepare_write() is the right place.
994 * Also, this function can nest inside ext4_writepage(). In that case, we
995 * *know* that ext4_writepage() has generated enough buffer credits to do the
996 * whole page. So we won't block on the journal in that case, which is good,
997 * because the caller may be PF_MEMALLOC.
999 * By accident, ext4 can be reentered when a transaction is open via
1000 * quota file writes. If we were to commit the transaction while thus
1001 * reentered, there can be a deadlock - we would be holding a quota
1002 * lock, and the commit would never complete if another thread had a
1003 * transaction open and was blocking on the quota lock - a ranking
1006 * So what we do is to rely on the fact that jbd2_journal_stop/journal_start
1007 * will _not_ run commit under these circumstances because handle->h_ref
1008 * is elevated. We'll still have enough credits for the tiny quotafile
1011 int do_journal_get_write_access(handle_t *handle, struct inode *inode,
1012 struct buffer_head *bh)
1014 int dirty = buffer_dirty(bh);
1017 if (!buffer_mapped(bh) || buffer_freed(bh))
1020 * __block_write_begin() could have dirtied some buffers. Clean
1021 * the dirty bit as jbd2_journal_get_write_access() could complain
1022 * otherwise about fs integrity issues. Setting of the dirty bit
1023 * by __block_write_begin() isn't a real problem here as we clear
1024 * the bit before releasing a page lock and thus writeback cannot
1025 * ever write the buffer.
1028 clear_buffer_dirty(bh);
1029 BUFFER_TRACE(bh, "get write access");
1030 ret = ext4_journal_get_write_access(handle, inode->i_sb, 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 set_buffer_uptodate(bh);
1074 clear_buffer_new(bh);
1075 if (!buffer_mapped(bh)) {
1076 WARN_ON(bh->b_size != blocksize);
1077 err = get_block(inode, block, bh, 1);
1080 if (buffer_new(bh)) {
1081 if (PageUptodate(page)) {
1082 clear_buffer_new(bh);
1083 set_buffer_uptodate(bh);
1084 mark_buffer_dirty(bh);
1087 if (block_end > to || block_start < from)
1088 zero_user_segments(page, to, block_end,
1093 if (PageUptodate(page)) {
1094 set_buffer_uptodate(bh);
1097 if (!buffer_uptodate(bh) && !buffer_delay(bh) &&
1098 !buffer_unwritten(bh) &&
1099 (block_start < from || block_end > to)) {
1100 ext4_read_bh_lock(bh, 0, false);
1101 wait[nr_wait++] = bh;
1105 * If we issued read requests, let them complete.
1107 for (i = 0; i < nr_wait; i++) {
1108 wait_on_buffer(wait[i]);
1109 if (!buffer_uptodate(wait[i]))
1112 if (unlikely(err)) {
1113 page_zero_new_buffers(page, from, to);
1114 } else if (fscrypt_inode_uses_fs_layer_crypto(inode)) {
1115 for (i = 0; i < nr_wait; i++) {
1118 err2 = fscrypt_decrypt_pagecache_blocks(page, blocksize,
1119 bh_offset(wait[i]));
1121 clear_buffer_uptodate(wait[i]);
1131 static int ext4_write_begin(struct file *file, struct address_space *mapping,
1132 loff_t pos, unsigned len, unsigned flags,
1133 struct page **pagep, void **fsdata)
1135 struct inode *inode = mapping->host;
1136 int ret, needed_blocks;
1143 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
1146 trace_ext4_write_begin(inode, pos, len, flags);
1148 * Reserve one block more for addition to orphan list in case
1149 * we allocate blocks but write fails for some reason
1151 needed_blocks = ext4_writepage_trans_blocks(inode) + 1;
1152 index = pos >> PAGE_SHIFT;
1153 from = pos & (PAGE_SIZE - 1);
1156 if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
1157 ret = ext4_try_to_write_inline_data(mapping, inode, pos, len,
1166 * grab_cache_page_write_begin() can take a long time if the
1167 * system is thrashing due to memory pressure, or if the page
1168 * is being written back. So grab it first before we start
1169 * the transaction handle. This also allows us to allocate
1170 * the page (if needed) without using GFP_NOFS.
1173 page = grab_cache_page_write_begin(mapping, index, flags);
1177 * The same as page allocation, we prealloc buffer heads before
1178 * starting the handle.
1180 if (!page_has_buffers(page))
1181 create_empty_buffers(page, inode->i_sb->s_blocksize, 0);
1186 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE, needed_blocks);
1187 if (IS_ERR(handle)) {
1189 return PTR_ERR(handle);
1193 if (page->mapping != mapping) {
1194 /* The page got truncated from under us */
1197 ext4_journal_stop(handle);
1200 /* In case writeback began while the page was unlocked */
1201 wait_for_stable_page(page);
1203 #ifdef CONFIG_FS_ENCRYPTION
1204 if (ext4_should_dioread_nolock(inode))
1205 ret = ext4_block_write_begin(page, pos, len,
1206 ext4_get_block_unwritten);
1208 ret = ext4_block_write_begin(page, pos, len,
1211 if (ext4_should_dioread_nolock(inode))
1212 ret = __block_write_begin(page, pos, len,
1213 ext4_get_block_unwritten);
1215 ret = __block_write_begin(page, pos, len, ext4_get_block);
1217 if (!ret && ext4_should_journal_data(inode)) {
1218 ret = ext4_walk_page_buffers(handle, inode,
1219 page_buffers(page), from, to, NULL,
1220 do_journal_get_write_access);
1224 bool extended = (pos + len > inode->i_size) &&
1225 !ext4_verity_in_progress(inode);
1229 * __block_write_begin may have instantiated a few blocks
1230 * outside i_size. Trim these off again. Don't need
1231 * i_size_read because we hold i_mutex.
1233 * Add inode to orphan list in case we crash before
1236 if (extended && ext4_can_truncate(inode))
1237 ext4_orphan_add(handle, inode);
1239 ext4_journal_stop(handle);
1241 ext4_truncate_failed_write(inode);
1243 * If truncate failed early the inode might
1244 * still be on the orphan list; we need to
1245 * make sure the inode is removed from the
1246 * orphan list in that case.
1249 ext4_orphan_del(NULL, inode);
1252 if (ret == -ENOSPC &&
1253 ext4_should_retry_alloc(inode->i_sb, &retries))
1262 /* For write_end() in data=journal mode */
1263 static int write_end_fn(handle_t *handle, struct inode *inode,
1264 struct buffer_head *bh)
1267 if (!buffer_mapped(bh) || buffer_freed(bh))
1269 set_buffer_uptodate(bh);
1270 ret = ext4_handle_dirty_metadata(handle, NULL, bh);
1271 clear_buffer_meta(bh);
1272 clear_buffer_prio(bh);
1277 * We need to pick up the new inode size which generic_commit_write gave us
1278 * `file' can be NULL - eg, when called from page_symlink().
1280 * ext4 never places buffers on inode->i_mapping->private_list. metadata
1281 * buffers are managed internally.
1283 static int ext4_write_end(struct file *file,
1284 struct address_space *mapping,
1285 loff_t pos, unsigned len, unsigned copied,
1286 struct page *page, void *fsdata)
1288 handle_t *handle = ext4_journal_current_handle();
1289 struct inode *inode = mapping->host;
1290 loff_t old_size = inode->i_size;
1292 int i_size_changed = 0;
1293 bool verity = ext4_verity_in_progress(inode);
1295 trace_ext4_write_end(inode, pos, len, copied);
1297 if (ext4_has_inline_data(inode) &&
1298 ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA))
1299 return ext4_write_inline_data_end(inode, pos, len, copied, page);
1301 copied = block_write_end(file, mapping, pos, len, copied, page, fsdata);
1303 * it's important to update i_size while still holding page lock:
1304 * page writeout could otherwise come in and zero beyond i_size.
1306 * If FS_IOC_ENABLE_VERITY is running on this inode, then Merkle tree
1307 * blocks are being written past EOF, so skip the i_size update.
1310 i_size_changed = ext4_update_inode_size(inode, pos + copied);
1314 if (old_size < pos && !verity)
1315 pagecache_isize_extended(inode, old_size, pos);
1317 * Don't mark the inode dirty under page lock. First, it unnecessarily
1318 * makes the holding time of page lock longer. Second, it forces lock
1319 * ordering of page lock and transaction start for journaling
1323 ret = ext4_mark_inode_dirty(handle, inode);
1325 if (pos + len > inode->i_size && !verity && ext4_can_truncate(inode))
1326 /* if we have allocated more blocks and copied
1327 * less. We will have blocks allocated outside
1328 * inode->i_size. So truncate them
1330 ext4_orphan_add(handle, inode);
1332 ret2 = ext4_journal_stop(handle);
1336 if (pos + len > inode->i_size && !verity) {
1337 ext4_truncate_failed_write(inode);
1339 * If truncate failed early the inode might still be
1340 * on the orphan list; we need to make sure the inode
1341 * is removed from the orphan list in that case.
1344 ext4_orphan_del(NULL, inode);
1347 return ret ? ret : copied;
1351 * This is a private version of page_zero_new_buffers() which doesn't
1352 * set the buffer to be dirty, since in data=journalled mode we need
1353 * to call ext4_handle_dirty_metadata() instead.
1355 static void ext4_journalled_zero_new_buffers(handle_t *handle,
1356 struct inode *inode,
1358 unsigned from, unsigned to)
1360 unsigned int block_start = 0, block_end;
1361 struct buffer_head *head, *bh;
1363 bh = head = page_buffers(page);
1365 block_end = block_start + bh->b_size;
1366 if (buffer_new(bh)) {
1367 if (block_end > from && block_start < to) {
1368 if (!PageUptodate(page)) {
1369 unsigned start, size;
1371 start = max(from, block_start);
1372 size = min(to, block_end) - start;
1374 zero_user(page, start, size);
1375 write_end_fn(handle, inode, bh);
1377 clear_buffer_new(bh);
1380 block_start = block_end;
1381 bh = bh->b_this_page;
1382 } while (bh != head);
1385 static int ext4_journalled_write_end(struct file *file,
1386 struct address_space *mapping,
1387 loff_t pos, unsigned len, unsigned copied,
1388 struct page *page, void *fsdata)
1390 handle_t *handle = ext4_journal_current_handle();
1391 struct inode *inode = mapping->host;
1392 loff_t old_size = inode->i_size;
1396 int size_changed = 0;
1397 bool verity = ext4_verity_in_progress(inode);
1399 trace_ext4_journalled_write_end(inode, pos, len, copied);
1400 from = pos & (PAGE_SIZE - 1);
1403 BUG_ON(!ext4_handle_valid(handle));
1405 if (ext4_has_inline_data(inode))
1406 return ext4_write_inline_data_end(inode, pos, len, copied, page);
1408 if (unlikely(copied < len) && !PageUptodate(page)) {
1410 ext4_journalled_zero_new_buffers(handle, inode, page, from, to);
1412 if (unlikely(copied < len))
1413 ext4_journalled_zero_new_buffers(handle, inode, page,
1415 ret = ext4_walk_page_buffers(handle, inode, page_buffers(page),
1416 from, from + copied, &partial,
1419 SetPageUptodate(page);
1422 size_changed = ext4_update_inode_size(inode, pos + copied);
1423 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
1424 EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
1428 if (old_size < pos && !verity)
1429 pagecache_isize_extended(inode, old_size, pos);
1432 ret2 = ext4_mark_inode_dirty(handle, inode);
1437 if (pos + len > inode->i_size && !verity && ext4_can_truncate(inode))
1438 /* if we have allocated more blocks and copied
1439 * less. We will have blocks allocated outside
1440 * inode->i_size. So truncate them
1442 ext4_orphan_add(handle, inode);
1444 ret2 = ext4_journal_stop(handle);
1447 if (pos + len > inode->i_size && !verity) {
1448 ext4_truncate_failed_write(inode);
1450 * If truncate failed early the inode might still be
1451 * on the orphan list; we need to make sure the inode
1452 * is removed from the orphan list in that case.
1455 ext4_orphan_del(NULL, inode);
1458 return ret ? ret : copied;
1462 * Reserve space for a single cluster
1464 static int ext4_da_reserve_space(struct inode *inode)
1466 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1467 struct ext4_inode_info *ei = EXT4_I(inode);
1471 * We will charge metadata quota at writeout time; this saves
1472 * us from metadata over-estimation, though we may go over by
1473 * a small amount in the end. Here we just reserve for data.
1475 ret = dquot_reserve_block(inode, EXT4_C2B(sbi, 1));
1479 spin_lock(&ei->i_block_reservation_lock);
1480 if (ext4_claim_free_clusters(sbi, 1, 0)) {
1481 spin_unlock(&ei->i_block_reservation_lock);
1482 dquot_release_reservation_block(inode, EXT4_C2B(sbi, 1));
1485 ei->i_reserved_data_blocks++;
1486 trace_ext4_da_reserve_space(inode);
1487 spin_unlock(&ei->i_block_reservation_lock);
1489 return 0; /* success */
1492 void ext4_da_release_space(struct inode *inode, int to_free)
1494 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1495 struct ext4_inode_info *ei = EXT4_I(inode);
1498 return; /* Nothing to release, exit */
1500 spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
1502 trace_ext4_da_release_space(inode, to_free);
1503 if (unlikely(to_free > ei->i_reserved_data_blocks)) {
1505 * if there aren't enough reserved blocks, then the
1506 * counter is messed up somewhere. Since this
1507 * function is called from invalidate page, it's
1508 * harmless to return without any action.
1510 ext4_warning(inode->i_sb, "ext4_da_release_space: "
1511 "ino %lu, to_free %d with only %d reserved "
1512 "data blocks", inode->i_ino, to_free,
1513 ei->i_reserved_data_blocks);
1515 to_free = ei->i_reserved_data_blocks;
1517 ei->i_reserved_data_blocks -= to_free;
1519 /* update fs dirty data blocks counter */
1520 percpu_counter_sub(&sbi->s_dirtyclusters_counter, to_free);
1522 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
1524 dquot_release_reservation_block(inode, EXT4_C2B(sbi, to_free));
1528 * Delayed allocation stuff
1531 struct mpage_da_data {
1532 struct inode *inode;
1533 struct writeback_control *wbc;
1535 pgoff_t first_page; /* The first page to write */
1536 pgoff_t next_page; /* Current page to examine */
1537 pgoff_t last_page; /* Last page to examine */
1539 * Extent to map - this can be after first_page because that can be
1540 * fully mapped. We somewhat abuse m_flags to store whether the extent
1541 * is delalloc or unwritten.
1543 struct ext4_map_blocks map;
1544 struct ext4_io_submit io_submit; /* IO submission data */
1545 unsigned int do_map:1;
1546 unsigned int scanned_until_end:1;
1549 static void mpage_release_unused_pages(struct mpage_da_data *mpd,
1554 struct pagevec pvec;
1555 struct inode *inode = mpd->inode;
1556 struct address_space *mapping = inode->i_mapping;
1558 /* This is necessary when next_page == 0. */
1559 if (mpd->first_page >= mpd->next_page)
1562 mpd->scanned_until_end = 0;
1563 index = mpd->first_page;
1564 end = mpd->next_page - 1;
1566 ext4_lblk_t start, last;
1567 start = index << (PAGE_SHIFT - inode->i_blkbits);
1568 last = end << (PAGE_SHIFT - inode->i_blkbits);
1571 * avoid racing with extent status tree scans made by
1572 * ext4_insert_delayed_block()
1574 down_write(&EXT4_I(inode)->i_data_sem);
1575 ext4_es_remove_extent(inode, start, last - start + 1);
1576 up_write(&EXT4_I(inode)->i_data_sem);
1579 pagevec_init(&pvec);
1580 while (index <= end) {
1581 nr_pages = pagevec_lookup_range(&pvec, mapping, &index, end);
1584 for (i = 0; i < nr_pages; i++) {
1585 struct page *page = pvec.pages[i];
1587 BUG_ON(!PageLocked(page));
1588 BUG_ON(PageWriteback(page));
1590 if (page_mapped(page))
1591 clear_page_dirty_for_io(page);
1592 block_invalidatepage(page, 0, PAGE_SIZE);
1593 ClearPageUptodate(page);
1597 pagevec_release(&pvec);
1601 static void ext4_print_free_blocks(struct inode *inode)
1603 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1604 struct super_block *sb = inode->i_sb;
1605 struct ext4_inode_info *ei = EXT4_I(inode);
1607 ext4_msg(sb, KERN_CRIT, "Total free blocks count %lld",
1608 EXT4_C2B(EXT4_SB(inode->i_sb),
1609 ext4_count_free_clusters(sb)));
1610 ext4_msg(sb, KERN_CRIT, "Free/Dirty block details");
1611 ext4_msg(sb, KERN_CRIT, "free_blocks=%lld",
1612 (long long) EXT4_C2B(EXT4_SB(sb),
1613 percpu_counter_sum(&sbi->s_freeclusters_counter)));
1614 ext4_msg(sb, KERN_CRIT, "dirty_blocks=%lld",
1615 (long long) EXT4_C2B(EXT4_SB(sb),
1616 percpu_counter_sum(&sbi->s_dirtyclusters_counter)));
1617 ext4_msg(sb, KERN_CRIT, "Block reservation details");
1618 ext4_msg(sb, KERN_CRIT, "i_reserved_data_blocks=%u",
1619 ei->i_reserved_data_blocks);
1623 static int ext4_bh_delay_or_unwritten(handle_t *handle, struct inode *inode,
1624 struct buffer_head *bh)
1626 return (buffer_delay(bh) || buffer_unwritten(bh)) && buffer_dirty(bh);
1630 * ext4_insert_delayed_block - adds a delayed block to the extents status
1631 * tree, incrementing the reserved cluster/block
1632 * count or making a pending reservation
1635 * @inode - file containing the newly added block
1636 * @lblk - logical block to be added
1638 * Returns 0 on success, negative error code on failure.
1640 static int ext4_insert_delayed_block(struct inode *inode, ext4_lblk_t lblk)
1642 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1644 bool allocated = false;
1645 bool reserved = false;
1648 * If the cluster containing lblk is shared with a delayed,
1649 * written, or unwritten extent in a bigalloc file system, it's
1650 * already been accounted for and does not need to be reserved.
1651 * A pending reservation must be made for the cluster if it's
1652 * shared with a written or unwritten extent and doesn't already
1653 * have one. Written and unwritten extents can be purged from the
1654 * extents status tree if the system is under memory pressure, so
1655 * it's necessary to examine the extent tree if a search of the
1656 * extents status tree doesn't get a match.
1658 if (sbi->s_cluster_ratio == 1) {
1659 ret = ext4_da_reserve_space(inode);
1660 if (ret != 0) /* ENOSPC */
1663 } else { /* bigalloc */
1664 if (!ext4_es_scan_clu(inode, &ext4_es_is_delonly, lblk)) {
1665 if (!ext4_es_scan_clu(inode,
1666 &ext4_es_is_mapped, lblk)) {
1667 ret = ext4_clu_mapped(inode,
1668 EXT4_B2C(sbi, lblk));
1672 ret = ext4_da_reserve_space(inode);
1673 if (ret != 0) /* ENOSPC */
1685 ret = ext4_es_insert_delayed_block(inode, lblk, allocated);
1686 if (ret && reserved)
1687 ext4_da_release_space(inode, 1);
1694 * This function is grabs code from the very beginning of
1695 * ext4_map_blocks, but assumes that the caller is from delayed write
1696 * time. This function looks up the requested blocks and sets the
1697 * buffer delay bit under the protection of i_data_sem.
1699 static int ext4_da_map_blocks(struct inode *inode, sector_t iblock,
1700 struct ext4_map_blocks *map,
1701 struct buffer_head *bh)
1703 struct extent_status es;
1705 sector_t invalid_block = ~((sector_t) 0xffff);
1706 #ifdef ES_AGGRESSIVE_TEST
1707 struct ext4_map_blocks orig_map;
1709 memcpy(&orig_map, map, sizeof(*map));
1712 if (invalid_block < ext4_blocks_count(EXT4_SB(inode->i_sb)->s_es))
1716 ext_debug(inode, "max_blocks %u, logical block %lu\n", map->m_len,
1717 (unsigned long) map->m_lblk);
1719 /* Lookup extent status tree firstly */
1720 if (ext4_es_lookup_extent(inode, iblock, NULL, &es)) {
1721 if (ext4_es_is_hole(&es)) {
1723 down_read(&EXT4_I(inode)->i_data_sem);
1728 * Delayed extent could be allocated by fallocate.
1729 * So we need to check it.
1731 if (ext4_es_is_delayed(&es) && !ext4_es_is_unwritten(&es)) {
1732 map_bh(bh, inode->i_sb, invalid_block);
1734 set_buffer_delay(bh);
1738 map->m_pblk = ext4_es_pblock(&es) + iblock - es.es_lblk;
1739 retval = es.es_len - (iblock - es.es_lblk);
1740 if (retval > map->m_len)
1741 retval = map->m_len;
1742 map->m_len = retval;
1743 if (ext4_es_is_written(&es))
1744 map->m_flags |= EXT4_MAP_MAPPED;
1745 else if (ext4_es_is_unwritten(&es))
1746 map->m_flags |= EXT4_MAP_UNWRITTEN;
1750 #ifdef ES_AGGRESSIVE_TEST
1751 ext4_map_blocks_es_recheck(NULL, inode, map, &orig_map, 0);
1757 * Try to see if we can get the block without requesting a new
1758 * file system block.
1760 down_read(&EXT4_I(inode)->i_data_sem);
1761 if (ext4_has_inline_data(inode))
1763 else if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
1764 retval = ext4_ext_map_blocks(NULL, inode, map, 0);
1766 retval = ext4_ind_map_blocks(NULL, inode, map, 0);
1773 * XXX: __block_prepare_write() unmaps passed block,
1777 ret = ext4_insert_delayed_block(inode, map->m_lblk);
1783 map_bh(bh, inode->i_sb, invalid_block);
1785 set_buffer_delay(bh);
1786 } else if (retval > 0) {
1788 unsigned int status;
1790 if (unlikely(retval != map->m_len)) {
1791 ext4_warning(inode->i_sb,
1792 "ES len assertion failed for inode "
1793 "%lu: retval %d != map->m_len %d",
1794 inode->i_ino, retval, map->m_len);
1798 status = map->m_flags & EXT4_MAP_UNWRITTEN ?
1799 EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
1800 ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
1801 map->m_pblk, status);
1807 up_read((&EXT4_I(inode)->i_data_sem));
1813 * This is a special get_block_t callback which is used by
1814 * ext4_da_write_begin(). It will either return mapped block or
1815 * reserve space for a single block.
1817 * For delayed buffer_head we have BH_Mapped, BH_New, BH_Delay set.
1818 * We also have b_blocknr = -1 and b_bdev initialized properly
1820 * For unwritten buffer_head we have BH_Mapped, BH_New, BH_Unwritten set.
1821 * We also have b_blocknr = physicalblock mapping unwritten extent and b_bdev
1822 * initialized properly.
1824 int ext4_da_get_block_prep(struct inode *inode, sector_t iblock,
1825 struct buffer_head *bh, int create)
1827 struct ext4_map_blocks map;
1830 BUG_ON(create == 0);
1831 BUG_ON(bh->b_size != inode->i_sb->s_blocksize);
1833 map.m_lblk = iblock;
1837 * first, we need to know whether the block is allocated already
1838 * preallocated blocks are unmapped but should treated
1839 * the same as allocated blocks.
1841 ret = ext4_da_map_blocks(inode, iblock, &map, bh);
1845 map_bh(bh, inode->i_sb, map.m_pblk);
1846 ext4_update_bh_state(bh, map.m_flags);
1848 if (buffer_unwritten(bh)) {
1849 /* A delayed write to unwritten bh should be marked
1850 * new and mapped. Mapped ensures that we don't do
1851 * get_block multiple times when we write to the same
1852 * offset and new ensures that we do proper zero out
1853 * for partial write.
1856 set_buffer_mapped(bh);
1861 static int __ext4_journalled_writepage(struct page *page,
1864 struct address_space *mapping = page->mapping;
1865 struct inode *inode = mapping->host;
1866 handle_t *handle = NULL;
1867 int ret = 0, err = 0;
1868 int inline_data = ext4_has_inline_data(inode);
1869 struct buffer_head *inode_bh = NULL;
1872 ClearPageChecked(page);
1875 BUG_ON(page->index != 0);
1876 BUG_ON(len > ext4_get_max_inline_size(inode));
1877 inode_bh = ext4_journalled_write_inline_data(inode, len, page);
1878 if (inode_bh == NULL)
1882 * We need to release the page lock before we start the
1883 * journal, so grab a reference so the page won't disappear
1884 * out from under us.
1889 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
1890 ext4_writepage_trans_blocks(inode));
1891 if (IS_ERR(handle)) {
1892 ret = PTR_ERR(handle);
1894 goto out_no_pagelock;
1896 BUG_ON(!ext4_handle_valid(handle));
1900 size = i_size_read(inode);
1901 if (page->mapping != mapping || page_offset(page) > size) {
1902 /* The page got truncated from under us */
1903 ext4_journal_stop(handle);
1909 ret = ext4_mark_inode_dirty(handle, inode);
1911 struct buffer_head *page_bufs = page_buffers(page);
1913 if (page->index == size >> PAGE_SHIFT)
1914 len = size & ~PAGE_MASK;
1918 ret = ext4_walk_page_buffers(handle, inode, page_bufs, 0, len,
1919 NULL, do_journal_get_write_access);
1921 err = ext4_walk_page_buffers(handle, inode, page_bufs, 0, len,
1922 NULL, write_end_fn);
1926 err = ext4_jbd2_inode_add_write(handle, inode, page_offset(page), len);
1929 EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
1930 err = ext4_journal_stop(handle);
1934 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
1943 * Note that we don't need to start a transaction unless we're journaling data
1944 * because we should have holes filled from ext4_page_mkwrite(). We even don't
1945 * need to file the inode to the transaction's list in ordered mode because if
1946 * we are writing back data added by write(), the inode is already there and if
1947 * we are writing back data modified via mmap(), no one guarantees in which
1948 * transaction the data will hit the disk. In case we are journaling data, we
1949 * cannot start transaction directly because transaction start ranks above page
1950 * lock so we have to do some magic.
1952 * This function can get called via...
1953 * - ext4_writepages after taking page lock (have journal handle)
1954 * - journal_submit_inode_data_buffers (no journal handle)
1955 * - shrink_page_list via the kswapd/direct reclaim (no journal handle)
1956 * - grab_page_cache when doing write_begin (have journal handle)
1958 * We don't do any block allocation in this function. If we have page with
1959 * multiple blocks we need to write those buffer_heads that are mapped. This
1960 * is important for mmaped based write. So if we do with blocksize 1K
1961 * truncate(f, 1024);
1962 * a = mmap(f, 0, 4096);
1964 * truncate(f, 4096);
1965 * we have in the page first buffer_head mapped via page_mkwrite call back
1966 * but other buffer_heads would be unmapped but dirty (dirty done via the
1967 * do_wp_page). So writepage should write the first block. If we modify
1968 * the mmap area beyond 1024 we will again get a page_fault and the
1969 * page_mkwrite callback will do the block allocation and mark the
1970 * buffer_heads mapped.
1972 * We redirty the page if we have any buffer_heads that is either delay or
1973 * unwritten in the page.
1975 * We can get recursively called as show below.
1977 * ext4_writepage() -> kmalloc() -> __alloc_pages() -> page_launder() ->
1980 * But since we don't do any block allocation we should not deadlock.
1981 * Page also have the dirty flag cleared so we don't get recurive page_lock.
1983 static int ext4_writepage(struct page *page,
1984 struct writeback_control *wbc)
1989 struct buffer_head *page_bufs = NULL;
1990 struct inode *inode = page->mapping->host;
1991 struct ext4_io_submit io_submit;
1992 bool keep_towrite = false;
1994 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb)))) {
1995 inode->i_mapping->a_ops->invalidatepage(page, 0, PAGE_SIZE);
2000 trace_ext4_writepage(page);
2001 size = i_size_read(inode);
2002 if (page->index == size >> PAGE_SHIFT &&
2003 !ext4_verity_in_progress(inode))
2004 len = size & ~PAGE_MASK;
2008 /* Should never happen but for bugs in other kernel subsystems */
2009 if (!page_has_buffers(page)) {
2010 ext4_warning_inode(inode,
2011 "page %lu does not have buffers attached", page->index);
2012 ClearPageDirty(page);
2017 page_bufs = page_buffers(page);
2019 * We cannot do block allocation or other extent handling in this
2020 * function. If there are buffers needing that, we have to redirty
2021 * the page. But we may reach here when we do a journal commit via
2022 * journal_submit_inode_data_buffers() and in that case we must write
2023 * allocated buffers to achieve data=ordered mode guarantees.
2025 * Also, if there is only one buffer per page (the fs block
2026 * size == the page size), if one buffer needs block
2027 * allocation or needs to modify the extent tree to clear the
2028 * unwritten flag, we know that the page can't be written at
2029 * all, so we might as well refuse the write immediately.
2030 * Unfortunately if the block size != page size, we can't as
2031 * easily detect this case using ext4_walk_page_buffers(), but
2032 * for the extremely common case, this is an optimization that
2033 * skips a useless round trip through ext4_bio_write_page().
2035 if (ext4_walk_page_buffers(NULL, inode, page_bufs, 0, len, NULL,
2036 ext4_bh_delay_or_unwritten)) {
2037 redirty_page_for_writepage(wbc, page);
2038 if ((current->flags & PF_MEMALLOC) ||
2039 (inode->i_sb->s_blocksize == PAGE_SIZE)) {
2041 * For memory cleaning there's no point in writing only
2042 * some buffers. So just bail out. Warn if we came here
2043 * from direct reclaim.
2045 WARN_ON_ONCE((current->flags & (PF_MEMALLOC|PF_KSWAPD))
2050 keep_towrite = true;
2053 if (PageChecked(page) && ext4_should_journal_data(inode))
2055 * It's mmapped pagecache. Add buffers and journal it. There
2056 * doesn't seem much point in redirtying the page here.
2058 return __ext4_journalled_writepage(page, len);
2060 ext4_io_submit_init(&io_submit, wbc);
2061 io_submit.io_end = ext4_init_io_end(inode, GFP_NOFS);
2062 if (!io_submit.io_end) {
2063 redirty_page_for_writepage(wbc, page);
2067 ret = ext4_bio_write_page(&io_submit, page, len, keep_towrite);
2068 ext4_io_submit(&io_submit);
2069 /* Drop io_end reference we got from init */
2070 ext4_put_io_end_defer(io_submit.io_end);
2074 static int mpage_submit_page(struct mpage_da_data *mpd, struct page *page)
2080 BUG_ON(page->index != mpd->first_page);
2081 clear_page_dirty_for_io(page);
2083 * We have to be very careful here! Nothing protects writeback path
2084 * against i_size changes and the page can be writeably mapped into
2085 * page tables. So an application can be growing i_size and writing
2086 * data through mmap while writeback runs. clear_page_dirty_for_io()
2087 * write-protects our page in page tables and the page cannot get
2088 * written to again until we release page lock. So only after
2089 * clear_page_dirty_for_io() we are safe to sample i_size for
2090 * ext4_bio_write_page() to zero-out tail of the written page. We rely
2091 * on the barrier provided by TestClearPageDirty in
2092 * clear_page_dirty_for_io() to make sure i_size is really sampled only
2093 * after page tables are updated.
2095 size = i_size_read(mpd->inode);
2096 if (page->index == size >> PAGE_SHIFT &&
2097 !ext4_verity_in_progress(mpd->inode))
2098 len = size & ~PAGE_MASK;
2101 err = ext4_bio_write_page(&mpd->io_submit, page, len, false);
2103 mpd->wbc->nr_to_write--;
2109 #define BH_FLAGS (BIT(BH_Unwritten) | BIT(BH_Delay))
2112 * mballoc gives us at most this number of blocks...
2113 * XXX: That seems to be only a limitation of ext4_mb_normalize_request().
2114 * The rest of mballoc seems to handle chunks up to full group size.
2116 #define MAX_WRITEPAGES_EXTENT_LEN 2048
2119 * mpage_add_bh_to_extent - try to add bh to extent of blocks to map
2121 * @mpd - extent of blocks
2122 * @lblk - logical number of the block in the file
2123 * @bh - buffer head we want to add to the extent
2125 * The function is used to collect contig. blocks in the same state. If the
2126 * buffer doesn't require mapping for writeback and we haven't started the
2127 * extent of buffers to map yet, the function returns 'true' immediately - the
2128 * caller can write the buffer right away. Otherwise the function returns true
2129 * if the block has been added to the extent, false if the block couldn't be
2132 static bool mpage_add_bh_to_extent(struct mpage_da_data *mpd, ext4_lblk_t lblk,
2133 struct buffer_head *bh)
2135 struct ext4_map_blocks *map = &mpd->map;
2137 /* Buffer that doesn't need mapping for writeback? */
2138 if (!buffer_dirty(bh) || !buffer_mapped(bh) ||
2139 (!buffer_delay(bh) && !buffer_unwritten(bh))) {
2140 /* So far no extent to map => we write the buffer right away */
2141 if (map->m_len == 0)
2146 /* First block in the extent? */
2147 if (map->m_len == 0) {
2148 /* We cannot map unless handle is started... */
2153 map->m_flags = bh->b_state & BH_FLAGS;
2157 /* Don't go larger than mballoc is willing to allocate */
2158 if (map->m_len >= MAX_WRITEPAGES_EXTENT_LEN)
2161 /* Can we merge the block to our big extent? */
2162 if (lblk == map->m_lblk + map->m_len &&
2163 (bh->b_state & BH_FLAGS) == map->m_flags) {
2171 * mpage_process_page_bufs - submit page buffers for IO or add them to extent
2173 * @mpd - extent of blocks for mapping
2174 * @head - the first buffer in the page
2175 * @bh - buffer we should start processing from
2176 * @lblk - logical number of the block in the file corresponding to @bh
2178 * Walk through page buffers from @bh upto @head (exclusive) and either submit
2179 * the page for IO if all buffers in this page were mapped and there's no
2180 * accumulated extent of buffers to map or add buffers in the page to the
2181 * extent of buffers to map. The function returns 1 if the caller can continue
2182 * by processing the next page, 0 if it should stop adding buffers to the
2183 * extent to map because we cannot extend it anymore. It can also return value
2184 * < 0 in case of error during IO submission.
2186 static int mpage_process_page_bufs(struct mpage_da_data *mpd,
2187 struct buffer_head *head,
2188 struct buffer_head *bh,
2191 struct inode *inode = mpd->inode;
2193 ext4_lblk_t blocks = (i_size_read(inode) + i_blocksize(inode) - 1)
2194 >> inode->i_blkbits;
2196 if (ext4_verity_in_progress(inode))
2197 blocks = EXT_MAX_BLOCKS;
2200 BUG_ON(buffer_locked(bh));
2202 if (lblk >= blocks || !mpage_add_bh_to_extent(mpd, lblk, bh)) {
2203 /* Found extent to map? */
2206 /* Buffer needs mapping and handle is not started? */
2209 /* Everything mapped so far and we hit EOF */
2212 } while (lblk++, (bh = bh->b_this_page) != head);
2213 /* So far everything mapped? Submit the page for IO. */
2214 if (mpd->map.m_len == 0) {
2215 err = mpage_submit_page(mpd, head->b_page);
2219 if (lblk >= blocks) {
2220 mpd->scanned_until_end = 1;
2227 * mpage_process_page - update page buffers corresponding to changed extent and
2228 * may submit fully mapped page for IO
2230 * @mpd - description of extent to map, on return next extent to map
2231 * @m_lblk - logical block mapping.
2232 * @m_pblk - corresponding physical mapping.
2233 * @map_bh - determines on return whether this page requires any further
2235 * Scan given page buffers corresponding to changed extent and update buffer
2236 * state according to new extent state.
2237 * We map delalloc buffers to their physical location, clear unwritten bits.
2238 * If the given page is not fully mapped, we update @map to the next extent in
2239 * the given page that needs mapping & return @map_bh as true.
2241 static int mpage_process_page(struct mpage_da_data *mpd, struct page *page,
2242 ext4_lblk_t *m_lblk, ext4_fsblk_t *m_pblk,
2245 struct buffer_head *head, *bh;
2246 ext4_io_end_t *io_end = mpd->io_submit.io_end;
2247 ext4_lblk_t lblk = *m_lblk;
2248 ext4_fsblk_t pblock = *m_pblk;
2250 int blkbits = mpd->inode->i_blkbits;
2251 ssize_t io_end_size = 0;
2252 struct ext4_io_end_vec *io_end_vec = ext4_last_io_end_vec(io_end);
2254 bh = head = page_buffers(page);
2256 if (lblk < mpd->map.m_lblk)
2258 if (lblk >= mpd->map.m_lblk + mpd->map.m_len) {
2260 * Buffer after end of mapped extent.
2261 * Find next buffer in the page to map.
2264 mpd->map.m_flags = 0;
2265 io_end_vec->size += io_end_size;
2268 err = mpage_process_page_bufs(mpd, head, bh, lblk);
2271 if (!err && mpd->map.m_len && mpd->map.m_lblk > lblk) {
2272 io_end_vec = ext4_alloc_io_end_vec(io_end);
2273 if (IS_ERR(io_end_vec)) {
2274 err = PTR_ERR(io_end_vec);
2277 io_end_vec->offset = (loff_t)mpd->map.m_lblk << blkbits;
2282 if (buffer_delay(bh)) {
2283 clear_buffer_delay(bh);
2284 bh->b_blocknr = pblock++;
2286 clear_buffer_unwritten(bh);
2287 io_end_size += (1 << blkbits);
2288 } while (lblk++, (bh = bh->b_this_page) != head);
2290 io_end_vec->size += io_end_size;
2300 * mpage_map_buffers - update buffers corresponding to changed extent and
2301 * submit fully mapped pages for IO
2303 * @mpd - description of extent to map, on return next extent to map
2305 * Scan buffers corresponding to changed extent (we expect corresponding pages
2306 * to be already locked) and update buffer state according to new extent state.
2307 * We map delalloc buffers to their physical location, clear unwritten bits,
2308 * and mark buffers as uninit when we perform writes to unwritten extents
2309 * and do extent conversion after IO is finished. If the last page is not fully
2310 * mapped, we update @map to the next extent in the last page that needs
2311 * mapping. Otherwise we submit the page for IO.
2313 static int mpage_map_and_submit_buffers(struct mpage_da_data *mpd)
2315 struct pagevec pvec;
2317 struct inode *inode = mpd->inode;
2318 int bpp_bits = PAGE_SHIFT - inode->i_blkbits;
2321 ext4_fsblk_t pblock;
2323 bool map_bh = false;
2325 start = mpd->map.m_lblk >> bpp_bits;
2326 end = (mpd->map.m_lblk + mpd->map.m_len - 1) >> bpp_bits;
2327 lblk = start << bpp_bits;
2328 pblock = mpd->map.m_pblk;
2330 pagevec_init(&pvec);
2331 while (start <= end) {
2332 nr_pages = pagevec_lookup_range(&pvec, inode->i_mapping,
2336 for (i = 0; i < nr_pages; i++) {
2337 struct page *page = pvec.pages[i];
2339 err = mpage_process_page(mpd, page, &lblk, &pblock,
2342 * If map_bh is true, means page may require further bh
2343 * mapping, or maybe the page was submitted for IO.
2344 * So we return to call further extent mapping.
2346 if (err < 0 || map_bh)
2348 /* Page fully mapped - let IO run! */
2349 err = mpage_submit_page(mpd, page);
2353 pagevec_release(&pvec);
2355 /* Extent fully mapped and matches with page boundary. We are done. */
2357 mpd->map.m_flags = 0;
2360 pagevec_release(&pvec);
2364 static int mpage_map_one_extent(handle_t *handle, struct mpage_da_data *mpd)
2366 struct inode *inode = mpd->inode;
2367 struct ext4_map_blocks *map = &mpd->map;
2368 int get_blocks_flags;
2369 int err, dioread_nolock;
2371 trace_ext4_da_write_pages_extent(inode, map);
2373 * Call ext4_map_blocks() to allocate any delayed allocation blocks, or
2374 * to convert an unwritten extent to be initialized (in the case
2375 * where we have written into one or more preallocated blocks). It is
2376 * possible that we're going to need more metadata blocks than
2377 * previously reserved. However we must not fail because we're in
2378 * writeback and there is nothing we can do about it so it might result
2379 * in data loss. So use reserved blocks to allocate metadata if
2382 * We pass in the magic EXT4_GET_BLOCKS_DELALLOC_RESERVE if
2383 * the blocks in question are delalloc blocks. This indicates
2384 * that the blocks and quotas has already been checked when
2385 * the data was copied into the page cache.
2387 get_blocks_flags = EXT4_GET_BLOCKS_CREATE |
2388 EXT4_GET_BLOCKS_METADATA_NOFAIL |
2389 EXT4_GET_BLOCKS_IO_SUBMIT;
2390 dioread_nolock = ext4_should_dioread_nolock(inode);
2392 get_blocks_flags |= EXT4_GET_BLOCKS_IO_CREATE_EXT;
2393 if (map->m_flags & BIT(BH_Delay))
2394 get_blocks_flags |= EXT4_GET_BLOCKS_DELALLOC_RESERVE;
2396 err = ext4_map_blocks(handle, inode, map, get_blocks_flags);
2399 if (dioread_nolock && (map->m_flags & EXT4_MAP_UNWRITTEN)) {
2400 if (!mpd->io_submit.io_end->handle &&
2401 ext4_handle_valid(handle)) {
2402 mpd->io_submit.io_end->handle = handle->h_rsv_handle;
2403 handle->h_rsv_handle = NULL;
2405 ext4_set_io_unwritten_flag(inode, mpd->io_submit.io_end);
2408 BUG_ON(map->m_len == 0);
2413 * mpage_map_and_submit_extent - map extent starting at mpd->lblk of length
2414 * mpd->len and submit pages underlying it for IO
2416 * @handle - handle for journal operations
2417 * @mpd - extent to map
2418 * @give_up_on_write - we set this to true iff there is a fatal error and there
2419 * is no hope of writing the data. The caller should discard
2420 * dirty pages to avoid infinite loops.
2422 * The function maps extent starting at mpd->lblk of length mpd->len. If it is
2423 * delayed, blocks are allocated, if it is unwritten, we may need to convert
2424 * them to initialized or split the described range from larger unwritten
2425 * extent. Note that we need not map all the described range since allocation
2426 * can return less blocks or the range is covered by more unwritten extents. We
2427 * cannot map more because we are limited by reserved transaction credits. On
2428 * the other hand we always make sure that the last touched page is fully
2429 * mapped so that it can be written out (and thus forward progress is
2430 * guaranteed). After mapping we submit all mapped pages for IO.
2432 static int mpage_map_and_submit_extent(handle_t *handle,
2433 struct mpage_da_data *mpd,
2434 bool *give_up_on_write)
2436 struct inode *inode = mpd->inode;
2437 struct ext4_map_blocks *map = &mpd->map;
2441 ext4_io_end_t *io_end = mpd->io_submit.io_end;
2442 struct ext4_io_end_vec *io_end_vec;
2444 io_end_vec = ext4_alloc_io_end_vec(io_end);
2445 if (IS_ERR(io_end_vec))
2446 return PTR_ERR(io_end_vec);
2447 io_end_vec->offset = ((loff_t)map->m_lblk) << inode->i_blkbits;
2449 err = mpage_map_one_extent(handle, mpd);
2451 struct super_block *sb = inode->i_sb;
2453 if (ext4_forced_shutdown(EXT4_SB(sb)) ||
2454 ext4_test_mount_flag(sb, EXT4_MF_FS_ABORTED))
2455 goto invalidate_dirty_pages;
2457 * Let the uper layers retry transient errors.
2458 * In the case of ENOSPC, if ext4_count_free_blocks()
2459 * is non-zero, a commit should free up blocks.
2461 if ((err == -ENOMEM) ||
2462 (err == -ENOSPC && ext4_count_free_clusters(sb))) {
2464 goto update_disksize;
2467 ext4_msg(sb, KERN_CRIT,
2468 "Delayed block allocation failed for "
2469 "inode %lu at logical offset %llu with"
2470 " max blocks %u with error %d",
2472 (unsigned long long)map->m_lblk,
2473 (unsigned)map->m_len, -err);
2474 ext4_msg(sb, KERN_CRIT,
2475 "This should not happen!! Data will "
2478 ext4_print_free_blocks(inode);
2479 invalidate_dirty_pages:
2480 *give_up_on_write = true;
2485 * Update buffer state, submit mapped pages, and get us new
2488 err = mpage_map_and_submit_buffers(mpd);
2490 goto update_disksize;
2491 } while (map->m_len);
2495 * Update on-disk size after IO is submitted. Races with
2496 * truncate are avoided by checking i_size under i_data_sem.
2498 disksize = ((loff_t)mpd->first_page) << PAGE_SHIFT;
2499 if (disksize > READ_ONCE(EXT4_I(inode)->i_disksize)) {
2503 down_write(&EXT4_I(inode)->i_data_sem);
2504 i_size = i_size_read(inode);
2505 if (disksize > i_size)
2507 if (disksize > EXT4_I(inode)->i_disksize)
2508 EXT4_I(inode)->i_disksize = disksize;
2509 up_write(&EXT4_I(inode)->i_data_sem);
2510 err2 = ext4_mark_inode_dirty(handle, inode);
2512 ext4_error_err(inode->i_sb, -err2,
2513 "Failed to mark inode %lu dirty",
2523 * Calculate the total number of credits to reserve for one writepages
2524 * iteration. This is called from ext4_writepages(). We map an extent of
2525 * up to MAX_WRITEPAGES_EXTENT_LEN blocks and then we go on and finish mapping
2526 * the last partial page. So in total we can map MAX_WRITEPAGES_EXTENT_LEN +
2527 * bpp - 1 blocks in bpp different extents.
2529 static int ext4_da_writepages_trans_blocks(struct inode *inode)
2531 int bpp = ext4_journal_blocks_per_page(inode);
2533 return ext4_meta_trans_blocks(inode,
2534 MAX_WRITEPAGES_EXTENT_LEN + bpp - 1, bpp);
2538 * mpage_prepare_extent_to_map - find & lock contiguous range of dirty pages
2539 * and underlying extent to map
2541 * @mpd - where to look for pages
2543 * Walk dirty pages in the mapping. If they are fully mapped, submit them for
2544 * IO immediately. When we find a page which isn't mapped we start accumulating
2545 * extent of buffers underlying these pages that needs mapping (formed by
2546 * either delayed or unwritten buffers). We also lock the pages containing
2547 * these buffers. The extent found is returned in @mpd structure (starting at
2548 * mpd->lblk with length mpd->len blocks).
2550 * Note that this function can attach bios to one io_end structure which are
2551 * neither logically nor physically contiguous. Although it may seem as an
2552 * unnecessary complication, it is actually inevitable in blocksize < pagesize
2553 * case as we need to track IO to all buffers underlying a page in one io_end.
2555 static int mpage_prepare_extent_to_map(struct mpage_da_data *mpd)
2557 struct address_space *mapping = mpd->inode->i_mapping;
2558 struct pagevec pvec;
2559 unsigned int nr_pages;
2560 long left = mpd->wbc->nr_to_write;
2561 pgoff_t index = mpd->first_page;
2562 pgoff_t end = mpd->last_page;
2565 int blkbits = mpd->inode->i_blkbits;
2567 struct buffer_head *head;
2569 if (mpd->wbc->sync_mode == WB_SYNC_ALL || mpd->wbc->tagged_writepages)
2570 tag = PAGECACHE_TAG_TOWRITE;
2572 tag = PAGECACHE_TAG_DIRTY;
2574 pagevec_init(&pvec);
2576 mpd->next_page = index;
2577 while (index <= end) {
2578 nr_pages = pagevec_lookup_range_tag(&pvec, mapping, &index, end,
2583 for (i = 0; i < nr_pages; i++) {
2584 struct page *page = pvec.pages[i];
2587 * Accumulated enough dirty pages? This doesn't apply
2588 * to WB_SYNC_ALL mode. For integrity sync we have to
2589 * keep going because someone may be concurrently
2590 * dirtying pages, and we might have synced a lot of
2591 * newly appeared dirty pages, but have not synced all
2592 * of the old dirty pages.
2594 if (mpd->wbc->sync_mode == WB_SYNC_NONE && left <= 0)
2597 /* If we can't merge this page, we are done. */
2598 if (mpd->map.m_len > 0 && mpd->next_page != page->index)
2603 * If the page is no longer dirty, or its mapping no
2604 * longer corresponds to inode we are writing (which
2605 * means it has been truncated or invalidated), or the
2606 * page is already under writeback and we are not doing
2607 * a data integrity writeback, skip the page
2609 if (!PageDirty(page) ||
2610 (PageWriteback(page) &&
2611 (mpd->wbc->sync_mode == WB_SYNC_NONE)) ||
2612 unlikely(page->mapping != mapping)) {
2617 wait_on_page_writeback(page);
2618 BUG_ON(PageWriteback(page));
2621 * Should never happen but for buggy code in
2622 * other subsystems that call
2623 * set_page_dirty() without properly warning
2624 * the file system first. See [1] for more
2627 * [1] https://lore.kernel.org/linux-mm/20180103100430.GE4911@quack2.suse.cz
2629 if (!page_has_buffers(page)) {
2630 ext4_warning_inode(mpd->inode, "page %lu does not have buffers attached", page->index);
2631 ClearPageDirty(page);
2636 if (mpd->map.m_len == 0)
2637 mpd->first_page = page->index;
2638 mpd->next_page = page->index + 1;
2639 /* Add all dirty buffers to mpd */
2640 lblk = ((ext4_lblk_t)page->index) <<
2641 (PAGE_SHIFT - blkbits);
2642 head = page_buffers(page);
2643 err = mpage_process_page_bufs(mpd, head, head, lblk);
2649 pagevec_release(&pvec);
2652 mpd->scanned_until_end = 1;
2655 pagevec_release(&pvec);
2659 static int ext4_writepages(struct address_space *mapping,
2660 struct writeback_control *wbc)
2662 pgoff_t writeback_index = 0;
2663 long nr_to_write = wbc->nr_to_write;
2664 int range_whole = 0;
2666 handle_t *handle = NULL;
2667 struct mpage_da_data mpd;
2668 struct inode *inode = mapping->host;
2669 int needed_blocks, rsv_blocks = 0, ret = 0;
2670 struct ext4_sb_info *sbi = EXT4_SB(mapping->host->i_sb);
2671 struct blk_plug plug;
2672 bool give_up_on_write = false;
2674 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
2677 percpu_down_read(&sbi->s_writepages_rwsem);
2678 trace_ext4_writepages(inode, wbc);
2681 * No pages to write? This is mainly a kludge to avoid starting
2682 * a transaction for special inodes like journal inode on last iput()
2683 * because that could violate lock ordering on umount
2685 if (!mapping->nrpages || !mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
2686 goto out_writepages;
2688 if (ext4_should_journal_data(inode)) {
2689 ret = generic_writepages(mapping, wbc);
2690 goto out_writepages;
2694 * If the filesystem has aborted, it is read-only, so return
2695 * right away instead of dumping stack traces later on that
2696 * will obscure the real source of the problem. We test
2697 * EXT4_MF_FS_ABORTED instead of sb->s_flag's SB_RDONLY because
2698 * the latter could be true if the filesystem is mounted
2699 * read-only, and in that case, ext4_writepages should
2700 * *never* be called, so if that ever happens, we would want
2703 if (unlikely(ext4_forced_shutdown(EXT4_SB(mapping->host->i_sb)) ||
2704 ext4_test_mount_flag(inode->i_sb, EXT4_MF_FS_ABORTED))) {
2706 goto out_writepages;
2710 * If we have inline data and arrive here, it means that
2711 * we will soon create the block for the 1st page, so
2712 * we'd better clear the inline data here.
2714 if (ext4_has_inline_data(inode)) {
2715 /* Just inode will be modified... */
2716 handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
2717 if (IS_ERR(handle)) {
2718 ret = PTR_ERR(handle);
2719 goto out_writepages;
2721 BUG_ON(ext4_test_inode_state(inode,
2722 EXT4_STATE_MAY_INLINE_DATA));
2723 ext4_destroy_inline_data(handle, inode);
2724 ext4_journal_stop(handle);
2727 if (ext4_should_dioread_nolock(inode)) {
2729 * We may need to convert up to one extent per block in
2730 * the page and we may dirty the inode.
2732 rsv_blocks = 1 + ext4_chunk_trans_blocks(inode,
2733 PAGE_SIZE >> inode->i_blkbits);
2736 if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
2739 if (wbc->range_cyclic) {
2740 writeback_index = mapping->writeback_index;
2741 if (writeback_index)
2743 mpd.first_page = writeback_index;
2746 mpd.first_page = wbc->range_start >> PAGE_SHIFT;
2747 mpd.last_page = wbc->range_end >> PAGE_SHIFT;
2752 ext4_io_submit_init(&mpd.io_submit, wbc);
2754 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
2755 tag_pages_for_writeback(mapping, mpd.first_page, mpd.last_page);
2756 blk_start_plug(&plug);
2759 * First writeback pages that don't need mapping - we can avoid
2760 * starting a transaction unnecessarily and also avoid being blocked
2761 * in the block layer on device congestion while having transaction
2765 mpd.scanned_until_end = 0;
2766 mpd.io_submit.io_end = ext4_init_io_end(inode, GFP_KERNEL);
2767 if (!mpd.io_submit.io_end) {
2771 ret = mpage_prepare_extent_to_map(&mpd);
2772 /* Unlock pages we didn't use */
2773 mpage_release_unused_pages(&mpd, false);
2774 /* Submit prepared bio */
2775 ext4_io_submit(&mpd.io_submit);
2776 ext4_put_io_end_defer(mpd.io_submit.io_end);
2777 mpd.io_submit.io_end = NULL;
2781 while (!mpd.scanned_until_end && wbc->nr_to_write > 0) {
2782 /* For each extent of pages we use new io_end */
2783 mpd.io_submit.io_end = ext4_init_io_end(inode, GFP_KERNEL);
2784 if (!mpd.io_submit.io_end) {
2790 * We have two constraints: We find one extent to map and we
2791 * must always write out whole page (makes a difference when
2792 * blocksize < pagesize) so that we don't block on IO when we
2793 * try to write out the rest of the page. Journalled mode is
2794 * not supported by delalloc.
2796 BUG_ON(ext4_should_journal_data(inode));
2797 needed_blocks = ext4_da_writepages_trans_blocks(inode);
2799 /* start a new transaction */
2800 handle = ext4_journal_start_with_reserve(inode,
2801 EXT4_HT_WRITE_PAGE, needed_blocks, rsv_blocks);
2802 if (IS_ERR(handle)) {
2803 ret = PTR_ERR(handle);
2804 ext4_msg(inode->i_sb, KERN_CRIT, "%s: jbd2_start: "
2805 "%ld pages, ino %lu; err %d", __func__,
2806 wbc->nr_to_write, inode->i_ino, ret);
2807 /* Release allocated io_end */
2808 ext4_put_io_end(mpd.io_submit.io_end);
2809 mpd.io_submit.io_end = NULL;
2814 trace_ext4_da_write_pages(inode, mpd.first_page, mpd.wbc);
2815 ret = mpage_prepare_extent_to_map(&mpd);
2816 if (!ret && mpd.map.m_len)
2817 ret = mpage_map_and_submit_extent(handle, &mpd,
2820 * Caution: If the handle is synchronous,
2821 * ext4_journal_stop() can wait for transaction commit
2822 * to finish which may depend on writeback of pages to
2823 * complete or on page lock to be released. In that
2824 * case, we have to wait until after we have
2825 * submitted all the IO, released page locks we hold,
2826 * and dropped io_end reference (for extent conversion
2827 * to be able to complete) before stopping the handle.
2829 if (!ext4_handle_valid(handle) || handle->h_sync == 0) {
2830 ext4_journal_stop(handle);
2834 /* Unlock pages we didn't use */
2835 mpage_release_unused_pages(&mpd, give_up_on_write);
2836 /* Submit prepared bio */
2837 ext4_io_submit(&mpd.io_submit);
2840 * Drop our io_end reference we got from init. We have
2841 * to be careful and use deferred io_end finishing if
2842 * we are still holding the transaction as we can
2843 * release the last reference to io_end which may end
2844 * up doing unwritten extent conversion.
2847 ext4_put_io_end_defer(mpd.io_submit.io_end);
2848 ext4_journal_stop(handle);
2850 ext4_put_io_end(mpd.io_submit.io_end);
2851 mpd.io_submit.io_end = NULL;
2853 if (ret == -ENOSPC && sbi->s_journal) {
2855 * Commit the transaction which would
2856 * free blocks released in the transaction
2859 jbd2_journal_force_commit_nested(sbi->s_journal);
2863 /* Fatal error - ENOMEM, EIO... */
2868 blk_finish_plug(&plug);
2869 if (!ret && !cycled && wbc->nr_to_write > 0) {
2871 mpd.last_page = writeback_index - 1;
2877 if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
2879 * Set the writeback_index so that range_cyclic
2880 * mode will write it back later
2882 mapping->writeback_index = mpd.first_page;
2885 trace_ext4_writepages_result(inode, wbc, ret,
2886 nr_to_write - wbc->nr_to_write);
2887 percpu_up_read(&sbi->s_writepages_rwsem);
2891 static int ext4_dax_writepages(struct address_space *mapping,
2892 struct writeback_control *wbc)
2895 long nr_to_write = wbc->nr_to_write;
2896 struct inode *inode = mapping->host;
2897 struct ext4_sb_info *sbi = EXT4_SB(mapping->host->i_sb);
2899 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
2902 percpu_down_read(&sbi->s_writepages_rwsem);
2903 trace_ext4_writepages(inode, wbc);
2905 ret = dax_writeback_mapping_range(mapping, sbi->s_daxdev, wbc);
2906 trace_ext4_writepages_result(inode, wbc, ret,
2907 nr_to_write - wbc->nr_to_write);
2908 percpu_up_read(&sbi->s_writepages_rwsem);
2912 static int ext4_nonda_switch(struct super_block *sb)
2914 s64 free_clusters, dirty_clusters;
2915 struct ext4_sb_info *sbi = EXT4_SB(sb);
2918 * switch to non delalloc mode if we are running low
2919 * on free block. The free block accounting via percpu
2920 * counters can get slightly wrong with percpu_counter_batch getting
2921 * accumulated on each CPU without updating global counters
2922 * Delalloc need an accurate free block accounting. So switch
2923 * to non delalloc when we are near to error range.
2926 percpu_counter_read_positive(&sbi->s_freeclusters_counter);
2928 percpu_counter_read_positive(&sbi->s_dirtyclusters_counter);
2930 * Start pushing delalloc when 1/2 of free blocks are dirty.
2932 if (dirty_clusters && (free_clusters < 2 * dirty_clusters))
2933 try_to_writeback_inodes_sb(sb, WB_REASON_FS_FREE_SPACE);
2935 if (2 * free_clusters < 3 * dirty_clusters ||
2936 free_clusters < (dirty_clusters + EXT4_FREECLUSTERS_WATERMARK)) {
2938 * free block count is less than 150% of dirty blocks
2939 * or free blocks is less than watermark
2946 static int ext4_da_write_begin(struct file *file, struct address_space *mapping,
2947 loff_t pos, unsigned len, unsigned flags,
2948 struct page **pagep, void **fsdata)
2950 int ret, retries = 0;
2953 struct inode *inode = mapping->host;
2955 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
2958 index = pos >> PAGE_SHIFT;
2960 if (ext4_nonda_switch(inode->i_sb) || S_ISLNK(inode->i_mode) ||
2961 ext4_verity_in_progress(inode)) {
2962 *fsdata = (void *)FALL_BACK_TO_NONDELALLOC;
2963 return ext4_write_begin(file, mapping, pos,
2964 len, flags, pagep, fsdata);
2966 *fsdata = (void *)0;
2967 trace_ext4_da_write_begin(inode, pos, len, flags);
2969 if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
2970 ret = ext4_da_write_inline_data_begin(mapping, inode,
2980 page = grab_cache_page_write_begin(mapping, index, flags);
2984 /* In case writeback began while the page was unlocked */
2985 wait_for_stable_page(page);
2987 #ifdef CONFIG_FS_ENCRYPTION
2988 ret = ext4_block_write_begin(page, pos, len,
2989 ext4_da_get_block_prep);
2991 ret = __block_write_begin(page, pos, len, ext4_da_get_block_prep);
2997 * block_write_begin may have instantiated a few blocks
2998 * outside i_size. Trim these off again. Don't need
2999 * i_size_read because we hold inode lock.
3001 if (pos + len > inode->i_size)
3002 ext4_truncate_failed_write(inode);
3004 if (ret == -ENOSPC &&
3005 ext4_should_retry_alloc(inode->i_sb, &retries))
3015 * Check if we should update i_disksize
3016 * when write to the end of file but not require block allocation
3018 static int ext4_da_should_update_i_disksize(struct page *page,
3019 unsigned long offset)
3021 struct buffer_head *bh;
3022 struct inode *inode = page->mapping->host;
3026 bh = page_buffers(page);
3027 idx = offset >> inode->i_blkbits;
3029 for (i = 0; i < idx; i++)
3030 bh = bh->b_this_page;
3032 if (!buffer_mapped(bh) || (buffer_delay(bh)) || buffer_unwritten(bh))
3037 static int ext4_da_write_end(struct file *file,
3038 struct address_space *mapping,
3039 loff_t pos, unsigned len, unsigned copied,
3040 struct page *page, void *fsdata)
3042 struct inode *inode = mapping->host;
3044 unsigned long start, end;
3045 int write_mode = (int)(unsigned long)fsdata;
3047 if (write_mode == FALL_BACK_TO_NONDELALLOC)
3048 return ext4_write_end(file, mapping, pos,
3049 len, copied, page, fsdata);
3051 trace_ext4_da_write_end(inode, pos, len, copied);
3053 if (write_mode != CONVERT_INLINE_DATA &&
3054 ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA) &&
3055 ext4_has_inline_data(inode))
3056 return ext4_write_inline_data_end(inode, pos, len, copied, page);
3058 if (unlikely(copied < len) && !PageUptodate(page))
3061 start = pos & (PAGE_SIZE - 1);
3062 end = start + copied - 1;
3065 * Since we are holding inode lock, we are sure i_disksize <=
3066 * i_size. We also know that if i_disksize < i_size, there are
3067 * delalloc writes pending in the range upto i_size. If the end of
3068 * the current write is <= i_size, there's no need to touch
3069 * i_disksize since writeback will push i_disksize upto i_size
3070 * eventually. If the end of the current write is > i_size and
3071 * inside an allocated block (ext4_da_should_update_i_disksize()
3072 * check), we need to update i_disksize here as neither
3073 * ext4_writepage() nor certain ext4_writepages() paths not
3074 * allocating blocks update i_disksize.
3076 * Note that we defer inode dirtying to generic_write_end() /
3077 * ext4_da_write_inline_data_end().
3079 new_i_size = pos + copied;
3080 if (copied && new_i_size > inode->i_size &&
3081 ext4_da_should_update_i_disksize(page, end))
3082 ext4_update_i_disksize(inode, new_i_size);
3084 return generic_write_end(file, mapping, pos, len, copied, page, fsdata);
3088 * Force all delayed allocation blocks to be allocated for a given inode.
3090 int ext4_alloc_da_blocks(struct inode *inode)
3092 trace_ext4_alloc_da_blocks(inode);
3094 if (!EXT4_I(inode)->i_reserved_data_blocks)
3098 * We do something simple for now. The filemap_flush() will
3099 * also start triggering a write of the data blocks, which is
3100 * not strictly speaking necessary (and for users of
3101 * laptop_mode, not even desirable). However, to do otherwise
3102 * would require replicating code paths in:
3104 * ext4_writepages() ->
3105 * write_cache_pages() ---> (via passed in callback function)
3106 * __mpage_da_writepage() -->
3107 * mpage_add_bh_to_extent()
3108 * mpage_da_map_blocks()
3110 * The problem is that write_cache_pages(), located in
3111 * mm/page-writeback.c, marks pages clean in preparation for
3112 * doing I/O, which is not desirable if we're not planning on
3115 * We could call write_cache_pages(), and then redirty all of
3116 * the pages by calling redirty_page_for_writepage() but that
3117 * would be ugly in the extreme. So instead we would need to
3118 * replicate parts of the code in the above functions,
3119 * simplifying them because we wouldn't actually intend to
3120 * write out the pages, but rather only collect contiguous
3121 * logical block extents, call the multi-block allocator, and
3122 * then update the buffer heads with the block allocations.
3124 * For now, though, we'll cheat by calling filemap_flush(),
3125 * which will map the blocks, and start the I/O, but not
3126 * actually wait for the I/O to complete.
3128 return filemap_flush(inode->i_mapping);
3132 * bmap() is special. It gets used by applications such as lilo and by
3133 * the swapper to find the on-disk block of a specific piece of data.
3135 * Naturally, this is dangerous if the block concerned is still in the
3136 * journal. If somebody makes a swapfile on an ext4 data-journaling
3137 * filesystem and enables swap, then they may get a nasty shock when the
3138 * data getting swapped to that swapfile suddenly gets overwritten by
3139 * the original zero's written out previously to the journal and
3140 * awaiting writeback in the kernel's buffer cache.
3142 * So, if we see any bmap calls here on a modified, data-journaled file,
3143 * take extra steps to flush any blocks which might be in the cache.
3145 static sector_t ext4_bmap(struct address_space *mapping, sector_t block)
3147 struct inode *inode = mapping->host;
3152 inode_lock_shared(inode);
3154 * We can get here for an inline file via the FIBMAP ioctl
3156 if (ext4_has_inline_data(inode))
3159 if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY) &&
3160 test_opt(inode->i_sb, DELALLOC)) {
3162 * With delalloc we want to sync the file
3163 * so that we can make sure we allocate
3166 filemap_write_and_wait(mapping);
3169 if (EXT4_JOURNAL(inode) &&
3170 ext4_test_inode_state(inode, EXT4_STATE_JDATA)) {
3172 * This is a REALLY heavyweight approach, but the use of
3173 * bmap on dirty files is expected to be extremely rare:
3174 * only if we run lilo or swapon on a freshly made file
3175 * do we expect this to happen.
3177 * (bmap requires CAP_SYS_RAWIO so this does not
3178 * represent an unprivileged user DOS attack --- we'd be
3179 * in trouble if mortal users could trigger this path at
3182 * NB. EXT4_STATE_JDATA is not set on files other than
3183 * regular files. If somebody wants to bmap a directory
3184 * or symlink and gets confused because the buffer
3185 * hasn't yet been flushed to disk, they deserve
3186 * everything they get.
3189 ext4_clear_inode_state(inode, EXT4_STATE_JDATA);
3190 journal = EXT4_JOURNAL(inode);
3191 jbd2_journal_lock_updates(journal);
3192 err = jbd2_journal_flush(journal, 0);
3193 jbd2_journal_unlock_updates(journal);
3199 ret = iomap_bmap(mapping, block, &ext4_iomap_ops);
3202 inode_unlock_shared(inode);
3206 static int ext4_readpage(struct file *file, struct page *page)
3209 struct inode *inode = page->mapping->host;
3211 trace_ext4_readpage(page);
3213 if (ext4_has_inline_data(inode))
3214 ret = ext4_readpage_inline(inode, page);
3217 return ext4_mpage_readpages(inode, NULL, page);
3222 static void ext4_readahead(struct readahead_control *rac)
3224 struct inode *inode = rac->mapping->host;
3226 /* If the file has inline data, no need to do readahead. */
3227 if (ext4_has_inline_data(inode))
3230 ext4_mpage_readpages(inode, rac, NULL);
3233 static void ext4_invalidatepage(struct page *page, unsigned int offset,
3234 unsigned int length)
3236 trace_ext4_invalidatepage(page, offset, length);
3238 /* No journalling happens on data buffers when this function is used */
3239 WARN_ON(page_has_buffers(page) && buffer_jbd(page_buffers(page)));
3241 block_invalidatepage(page, offset, length);
3244 static int __ext4_journalled_invalidatepage(struct page *page,
3245 unsigned int offset,
3246 unsigned int length)
3248 journal_t *journal = EXT4_JOURNAL(page->mapping->host);
3250 trace_ext4_journalled_invalidatepage(page, offset, length);
3253 * If it's a full truncate we just forget about the pending dirtying
3255 if (offset == 0 && length == PAGE_SIZE)
3256 ClearPageChecked(page);
3258 return jbd2_journal_invalidatepage(journal, page, offset, length);
3261 /* Wrapper for aops... */
3262 static void ext4_journalled_invalidatepage(struct page *page,
3263 unsigned int offset,
3264 unsigned int length)
3266 WARN_ON(__ext4_journalled_invalidatepage(page, offset, length) < 0);
3269 static int ext4_releasepage(struct page *page, gfp_t wait)
3271 journal_t *journal = EXT4_JOURNAL(page->mapping->host);
3273 trace_ext4_releasepage(page);
3275 /* Page has dirty journalled data -> cannot release */
3276 if (PageChecked(page))
3279 return jbd2_journal_try_to_free_buffers(journal, page);
3281 return try_to_free_buffers(page);
3284 static bool ext4_inode_datasync_dirty(struct inode *inode)
3286 journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
3289 if (jbd2_transaction_committed(journal,
3290 EXT4_I(inode)->i_datasync_tid))
3292 if (test_opt2(inode->i_sb, JOURNAL_FAST_COMMIT))
3293 return !list_empty(&EXT4_I(inode)->i_fc_list);
3297 /* Any metadata buffers to write? */
3298 if (!list_empty(&inode->i_mapping->private_list))
3300 return inode->i_state & I_DIRTY_DATASYNC;
3303 static void ext4_set_iomap(struct inode *inode, struct iomap *iomap,
3304 struct ext4_map_blocks *map, loff_t offset,
3307 u8 blkbits = inode->i_blkbits;
3310 * Writes that span EOF might trigger an I/O size update on completion,
3311 * so consider them to be dirty for the purpose of O_DSYNC, even if
3312 * there is no other metadata changes being made or are pending.
3315 if (ext4_inode_datasync_dirty(inode) ||
3316 offset + length > i_size_read(inode))
3317 iomap->flags |= IOMAP_F_DIRTY;
3319 if (map->m_flags & EXT4_MAP_NEW)
3320 iomap->flags |= IOMAP_F_NEW;
3322 iomap->bdev = inode->i_sb->s_bdev;
3323 iomap->dax_dev = EXT4_SB(inode->i_sb)->s_daxdev;
3324 iomap->offset = (u64) map->m_lblk << blkbits;
3325 iomap->length = (u64) map->m_len << blkbits;
3327 if ((map->m_flags & EXT4_MAP_MAPPED) &&
3328 !ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3329 iomap->flags |= IOMAP_F_MERGED;
3332 * Flags passed to ext4_map_blocks() for direct I/O writes can result
3333 * in m_flags having both EXT4_MAP_MAPPED and EXT4_MAP_UNWRITTEN bits
3334 * set. In order for any allocated unwritten extents to be converted
3335 * into written extents correctly within the ->end_io() handler, we
3336 * need to ensure that the iomap->type is set appropriately. Hence, the
3337 * reason why we need to check whether the EXT4_MAP_UNWRITTEN bit has
3340 if (map->m_flags & EXT4_MAP_UNWRITTEN) {
3341 iomap->type = IOMAP_UNWRITTEN;
3342 iomap->addr = (u64) map->m_pblk << blkbits;
3343 } else if (map->m_flags & EXT4_MAP_MAPPED) {
3344 iomap->type = IOMAP_MAPPED;
3345 iomap->addr = (u64) map->m_pblk << blkbits;
3347 iomap->type = IOMAP_HOLE;
3348 iomap->addr = IOMAP_NULL_ADDR;
3352 static int ext4_iomap_alloc(struct inode *inode, struct ext4_map_blocks *map,
3356 u8 blkbits = inode->i_blkbits;
3357 int ret, dio_credits, m_flags = 0, retries = 0;
3360 * Trim the mapping request to the maximum value that we can map at
3361 * once for direct I/O.
3363 if (map->m_len > DIO_MAX_BLOCKS)
3364 map->m_len = DIO_MAX_BLOCKS;
3365 dio_credits = ext4_chunk_trans_blocks(inode, map->m_len);
3369 * Either we allocate blocks and then don't get an unwritten extent, so
3370 * in that case we have reserved enough credits. Or, the blocks are
3371 * already allocated and unwritten. In that case, the extent conversion
3372 * fits into the credits as well.
3374 handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS, dio_credits);
3376 return PTR_ERR(handle);
3379 * DAX and direct I/O are the only two operations that are currently
3380 * supported with IOMAP_WRITE.
3382 WARN_ON(!IS_DAX(inode) && !(flags & IOMAP_DIRECT));
3384 m_flags = EXT4_GET_BLOCKS_CREATE_ZERO;
3386 * We use i_size instead of i_disksize here because delalloc writeback
3387 * can complete at any point during the I/O and subsequently push the
3388 * i_disksize out to i_size. This could be beyond where direct I/O is
3389 * happening and thus expose allocated blocks to direct I/O reads.
3391 else if (((loff_t)map->m_lblk << blkbits) >= i_size_read(inode))
3392 m_flags = EXT4_GET_BLOCKS_CREATE;
3393 else if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
3394 m_flags = EXT4_GET_BLOCKS_IO_CREATE_EXT;
3396 ret = ext4_map_blocks(handle, inode, map, m_flags);
3399 * We cannot fill holes in indirect tree based inodes as that could
3400 * expose stale data in the case of a crash. Use the magic error code
3401 * to fallback to buffered I/O.
3403 if (!m_flags && !ret)
3406 ext4_journal_stop(handle);
3407 if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
3414 static int ext4_iomap_begin(struct inode *inode, loff_t offset, loff_t length,
3415 unsigned flags, struct iomap *iomap, struct iomap *srcmap)
3418 struct ext4_map_blocks map;
3419 u8 blkbits = inode->i_blkbits;
3421 if ((offset >> blkbits) > EXT4_MAX_LOGICAL_BLOCK)
3424 if (WARN_ON_ONCE(ext4_has_inline_data(inode)))
3428 * Calculate the first and last logical blocks respectively.
3430 map.m_lblk = offset >> blkbits;
3431 map.m_len = min_t(loff_t, (offset + length - 1) >> blkbits,
3432 EXT4_MAX_LOGICAL_BLOCK) - map.m_lblk + 1;
3434 if (flags & IOMAP_WRITE) {
3436 * We check here if the blocks are already allocated, then we
3437 * don't need to start a journal txn and we can directly return
3438 * the mapping information. This could boost performance
3439 * especially in multi-threaded overwrite requests.
3441 if (offset + length <= i_size_read(inode)) {
3442 ret = ext4_map_blocks(NULL, inode, &map, 0);
3443 if (ret > 0 && (map.m_flags & EXT4_MAP_MAPPED))
3446 ret = ext4_iomap_alloc(inode, &map, flags);
3448 ret = ext4_map_blocks(NULL, inode, &map, 0);
3454 ext4_set_iomap(inode, iomap, &map, offset, length);
3459 static int ext4_iomap_overwrite_begin(struct inode *inode, loff_t offset,
3460 loff_t length, unsigned flags, struct iomap *iomap,
3461 struct iomap *srcmap)
3466 * Even for writes we don't need to allocate blocks, so just pretend
3467 * we are reading to save overhead of starting a transaction.
3469 flags &= ~IOMAP_WRITE;
3470 ret = ext4_iomap_begin(inode, offset, length, flags, iomap, srcmap);
3471 WARN_ON_ONCE(!ret && iomap->type != IOMAP_MAPPED);
3475 static int ext4_iomap_end(struct inode *inode, loff_t offset, loff_t length,
3476 ssize_t written, unsigned flags, struct iomap *iomap)
3479 * Check to see whether an error occurred while writing out the data to
3480 * the allocated blocks. If so, return the magic error code so that we
3481 * fallback to buffered I/O and attempt to complete the remainder of
3482 * the I/O. Any blocks that may have been allocated in preparation for
3483 * the direct I/O will be reused during buffered I/O.
3485 if (flags & (IOMAP_WRITE | IOMAP_DIRECT) && written == 0)
3491 const struct iomap_ops ext4_iomap_ops = {
3492 .iomap_begin = ext4_iomap_begin,
3493 .iomap_end = ext4_iomap_end,
3496 const struct iomap_ops ext4_iomap_overwrite_ops = {
3497 .iomap_begin = ext4_iomap_overwrite_begin,
3498 .iomap_end = ext4_iomap_end,
3501 static bool ext4_iomap_is_delalloc(struct inode *inode,
3502 struct ext4_map_blocks *map)
3504 struct extent_status es;
3505 ext4_lblk_t offset = 0, end = map->m_lblk + map->m_len - 1;
3507 ext4_es_find_extent_range(inode, &ext4_es_is_delayed,
3508 map->m_lblk, end, &es);
3510 if (!es.es_len || es.es_lblk > end)
3513 if (es.es_lblk > map->m_lblk) {
3514 map->m_len = es.es_lblk - map->m_lblk;
3518 offset = map->m_lblk - es.es_lblk;
3519 map->m_len = es.es_len - offset;
3524 static int ext4_iomap_begin_report(struct inode *inode, loff_t offset,
3525 loff_t length, unsigned int flags,
3526 struct iomap *iomap, struct iomap *srcmap)
3529 bool delalloc = false;
3530 struct ext4_map_blocks map;
3531 u8 blkbits = inode->i_blkbits;
3533 if ((offset >> blkbits) > EXT4_MAX_LOGICAL_BLOCK)
3536 if (ext4_has_inline_data(inode)) {
3537 ret = ext4_inline_data_iomap(inode, iomap);
3538 if (ret != -EAGAIN) {
3539 if (ret == 0 && offset >= iomap->length)
3546 * Calculate the first and last logical block respectively.
3548 map.m_lblk = offset >> blkbits;
3549 map.m_len = min_t(loff_t, (offset + length - 1) >> blkbits,
3550 EXT4_MAX_LOGICAL_BLOCK) - map.m_lblk + 1;
3553 * Fiemap callers may call for offset beyond s_bitmap_maxbytes.
3554 * So handle it here itself instead of querying ext4_map_blocks().
3555 * Since ext4_map_blocks() will warn about it and will return
3558 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
3559 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
3561 if (offset >= sbi->s_bitmap_maxbytes) {
3567 ret = ext4_map_blocks(NULL, inode, &map, 0);
3571 delalloc = ext4_iomap_is_delalloc(inode, &map);
3574 ext4_set_iomap(inode, iomap, &map, offset, length);
3575 if (delalloc && iomap->type == IOMAP_HOLE)
3576 iomap->type = IOMAP_DELALLOC;
3581 const struct iomap_ops ext4_iomap_report_ops = {
3582 .iomap_begin = ext4_iomap_begin_report,
3586 * Pages can be marked dirty completely asynchronously from ext4's journalling
3587 * activity. By filemap_sync_pte(), try_to_unmap_one(), etc. We cannot do
3588 * much here because ->set_page_dirty is called under VFS locks. The page is
3589 * not necessarily locked.
3591 * We cannot just dirty the page and leave attached buffers clean, because the
3592 * buffers' dirty state is "definitive". We cannot just set the buffers dirty
3593 * or jbddirty because all the journalling code will explode.
3595 * So what we do is to mark the page "pending dirty" and next time writepage
3596 * is called, propagate that into the buffers appropriately.
3598 static int ext4_journalled_set_page_dirty(struct page *page)
3600 SetPageChecked(page);
3601 return __set_page_dirty_nobuffers(page);
3604 static int ext4_set_page_dirty(struct page *page)
3606 WARN_ON_ONCE(!PageLocked(page) && !PageDirty(page));
3607 WARN_ON_ONCE(!page_has_buffers(page));
3608 return __set_page_dirty_buffers(page);
3611 static int ext4_iomap_swap_activate(struct swap_info_struct *sis,
3612 struct file *file, sector_t *span)
3614 return iomap_swapfile_activate(sis, file, span,
3615 &ext4_iomap_report_ops);
3618 static const struct address_space_operations ext4_aops = {
3619 .readpage = ext4_readpage,
3620 .readahead = ext4_readahead,
3621 .writepage = ext4_writepage,
3622 .writepages = ext4_writepages,
3623 .write_begin = ext4_write_begin,
3624 .write_end = ext4_write_end,
3625 .set_page_dirty = ext4_set_page_dirty,
3627 .invalidatepage = ext4_invalidatepage,
3628 .releasepage = ext4_releasepage,
3629 .direct_IO = noop_direct_IO,
3630 .migratepage = buffer_migrate_page,
3631 .is_partially_uptodate = block_is_partially_uptodate,
3632 .error_remove_page = generic_error_remove_page,
3633 .swap_activate = ext4_iomap_swap_activate,
3636 static const struct address_space_operations ext4_journalled_aops = {
3637 .readpage = ext4_readpage,
3638 .readahead = ext4_readahead,
3639 .writepage = ext4_writepage,
3640 .writepages = ext4_writepages,
3641 .write_begin = ext4_write_begin,
3642 .write_end = ext4_journalled_write_end,
3643 .set_page_dirty = ext4_journalled_set_page_dirty,
3645 .invalidatepage = ext4_journalled_invalidatepage,
3646 .releasepage = ext4_releasepage,
3647 .direct_IO = noop_direct_IO,
3648 .is_partially_uptodate = block_is_partially_uptodate,
3649 .error_remove_page = generic_error_remove_page,
3650 .swap_activate = ext4_iomap_swap_activate,
3653 static const struct address_space_operations ext4_da_aops = {
3654 .readpage = ext4_readpage,
3655 .readahead = ext4_readahead,
3656 .writepage = ext4_writepage,
3657 .writepages = ext4_writepages,
3658 .write_begin = ext4_da_write_begin,
3659 .write_end = ext4_da_write_end,
3660 .set_page_dirty = ext4_set_page_dirty,
3662 .invalidatepage = ext4_invalidatepage,
3663 .releasepage = ext4_releasepage,
3664 .direct_IO = noop_direct_IO,
3665 .migratepage = buffer_migrate_page,
3666 .is_partially_uptodate = block_is_partially_uptodate,
3667 .error_remove_page = generic_error_remove_page,
3668 .swap_activate = ext4_iomap_swap_activate,
3671 static const struct address_space_operations ext4_dax_aops = {
3672 .writepages = ext4_dax_writepages,
3673 .direct_IO = noop_direct_IO,
3674 .set_page_dirty = __set_page_dirty_no_writeback,
3676 .invalidatepage = noop_invalidatepage,
3677 .swap_activate = ext4_iomap_swap_activate,
3680 void ext4_set_aops(struct inode *inode)
3682 switch (ext4_inode_journal_mode(inode)) {
3683 case EXT4_INODE_ORDERED_DATA_MODE:
3684 case EXT4_INODE_WRITEBACK_DATA_MODE:
3686 case EXT4_INODE_JOURNAL_DATA_MODE:
3687 inode->i_mapping->a_ops = &ext4_journalled_aops;
3693 inode->i_mapping->a_ops = &ext4_dax_aops;
3694 else if (test_opt(inode->i_sb, DELALLOC))
3695 inode->i_mapping->a_ops = &ext4_da_aops;
3697 inode->i_mapping->a_ops = &ext4_aops;
3700 static int __ext4_block_zero_page_range(handle_t *handle,
3701 struct address_space *mapping, loff_t from, loff_t length)
3703 ext4_fsblk_t index = from >> PAGE_SHIFT;
3704 unsigned offset = from & (PAGE_SIZE-1);
3705 unsigned blocksize, pos;
3707 struct inode *inode = mapping->host;
3708 struct buffer_head *bh;
3712 page = find_or_create_page(mapping, from >> PAGE_SHIFT,
3713 mapping_gfp_constraint(mapping, ~__GFP_FS));
3717 blocksize = inode->i_sb->s_blocksize;
3719 iblock = index << (PAGE_SHIFT - inode->i_sb->s_blocksize_bits);
3721 if (!page_has_buffers(page))
3722 create_empty_buffers(page, blocksize, 0);
3724 /* Find the buffer that contains "offset" */
3725 bh = page_buffers(page);
3727 while (offset >= pos) {
3728 bh = bh->b_this_page;
3732 if (buffer_freed(bh)) {
3733 BUFFER_TRACE(bh, "freed: skip");
3736 if (!buffer_mapped(bh)) {
3737 BUFFER_TRACE(bh, "unmapped");
3738 ext4_get_block(inode, iblock, bh, 0);
3739 /* unmapped? It's a hole - nothing to do */
3740 if (!buffer_mapped(bh)) {
3741 BUFFER_TRACE(bh, "still unmapped");
3746 /* Ok, it's mapped. Make sure it's up-to-date */
3747 if (PageUptodate(page))
3748 set_buffer_uptodate(bh);
3750 if (!buffer_uptodate(bh)) {
3751 err = ext4_read_bh_lock(bh, 0, true);
3754 if (fscrypt_inode_uses_fs_layer_crypto(inode)) {
3755 /* We expect the key to be set. */
3756 BUG_ON(!fscrypt_has_encryption_key(inode));
3757 err = fscrypt_decrypt_pagecache_blocks(page, blocksize,
3760 clear_buffer_uptodate(bh);
3765 if (ext4_should_journal_data(inode)) {
3766 BUFFER_TRACE(bh, "get write access");
3767 err = ext4_journal_get_write_access(handle, inode->i_sb, bh,
3772 zero_user(page, offset, length);
3773 BUFFER_TRACE(bh, "zeroed end of block");
3775 if (ext4_should_journal_data(inode)) {
3776 err = ext4_handle_dirty_metadata(handle, inode, bh);
3779 mark_buffer_dirty(bh);
3780 if (ext4_should_order_data(inode))
3781 err = ext4_jbd2_inode_add_write(handle, inode, from,
3792 * ext4_block_zero_page_range() zeros out a mapping of length 'length'
3793 * starting from file offset 'from'. The range to be zero'd must
3794 * be contained with in one block. If the specified range exceeds
3795 * the end of the block it will be shortened to end of the block
3796 * that corresponds to 'from'
3798 static int ext4_block_zero_page_range(handle_t *handle,
3799 struct address_space *mapping, loff_t from, loff_t length)
3801 struct inode *inode = mapping->host;
3802 unsigned offset = from & (PAGE_SIZE-1);
3803 unsigned blocksize = inode->i_sb->s_blocksize;
3804 unsigned max = blocksize - (offset & (blocksize - 1));
3807 * correct length if it does not fall between
3808 * 'from' and the end of the block
3810 if (length > max || length < 0)
3813 if (IS_DAX(inode)) {
3814 return iomap_zero_range(inode, from, length, NULL,
3817 return __ext4_block_zero_page_range(handle, mapping, from, length);
3821 * ext4_block_truncate_page() zeroes out a mapping from file offset `from'
3822 * up to the end of the block which corresponds to `from'.
3823 * This required during truncate. We need to physically zero the tail end
3824 * of that block so it doesn't yield old data if the file is later grown.
3826 static int ext4_block_truncate_page(handle_t *handle,
3827 struct address_space *mapping, loff_t from)
3829 unsigned offset = from & (PAGE_SIZE-1);
3832 struct inode *inode = mapping->host;
3834 /* If we are processing an encrypted inode during orphan list handling */
3835 if (IS_ENCRYPTED(inode) && !fscrypt_has_encryption_key(inode))
3838 blocksize = inode->i_sb->s_blocksize;
3839 length = blocksize - (offset & (blocksize - 1));
3841 return ext4_block_zero_page_range(handle, mapping, from, length);
3844 int ext4_zero_partial_blocks(handle_t *handle, struct inode *inode,
3845 loff_t lstart, loff_t length)
3847 struct super_block *sb = inode->i_sb;
3848 struct address_space *mapping = inode->i_mapping;
3849 unsigned partial_start, partial_end;
3850 ext4_fsblk_t start, end;
3851 loff_t byte_end = (lstart + length - 1);
3854 partial_start = lstart & (sb->s_blocksize - 1);
3855 partial_end = byte_end & (sb->s_blocksize - 1);
3857 start = lstart >> sb->s_blocksize_bits;
3858 end = byte_end >> sb->s_blocksize_bits;
3860 /* Handle partial zero within the single block */
3862 (partial_start || (partial_end != sb->s_blocksize - 1))) {
3863 err = ext4_block_zero_page_range(handle, mapping,
3867 /* Handle partial zero out on the start of the range */
3868 if (partial_start) {
3869 err = ext4_block_zero_page_range(handle, mapping,
3870 lstart, sb->s_blocksize);
3874 /* Handle partial zero out on the end of the range */
3875 if (partial_end != sb->s_blocksize - 1)
3876 err = ext4_block_zero_page_range(handle, mapping,
3877 byte_end - partial_end,
3882 int ext4_can_truncate(struct inode *inode)
3884 if (S_ISREG(inode->i_mode))
3886 if (S_ISDIR(inode->i_mode))
3888 if (S_ISLNK(inode->i_mode))
3889 return !ext4_inode_is_fast_symlink(inode);
3894 * We have to make sure i_disksize gets properly updated before we truncate
3895 * page cache due to hole punching or zero range. Otherwise i_disksize update
3896 * can get lost as it may have been postponed to submission of writeback but
3897 * that will never happen after we truncate page cache.
3899 int ext4_update_disksize_before_punch(struct inode *inode, loff_t offset,
3905 loff_t size = i_size_read(inode);
3907 WARN_ON(!inode_is_locked(inode));
3908 if (offset > size || offset + len < size)
3911 if (EXT4_I(inode)->i_disksize >= size)
3914 handle = ext4_journal_start(inode, EXT4_HT_MISC, 1);
3916 return PTR_ERR(handle);
3917 ext4_update_i_disksize(inode, size);
3918 ret = ext4_mark_inode_dirty(handle, inode);
3919 ext4_journal_stop(handle);
3924 static void ext4_wait_dax_page(struct inode *inode)
3926 filemap_invalidate_unlock(inode->i_mapping);
3928 filemap_invalidate_lock(inode->i_mapping);
3931 int ext4_break_layouts(struct inode *inode)
3936 if (WARN_ON_ONCE(!rwsem_is_locked(&inode->i_mapping->invalidate_lock)))
3940 page = dax_layout_busy_page(inode->i_mapping);
3944 error = ___wait_var_event(&page->_refcount,
3945 atomic_read(&page->_refcount) == 1,
3946 TASK_INTERRUPTIBLE, 0, 0,
3947 ext4_wait_dax_page(inode));
3948 } while (error == 0);
3954 * ext4_punch_hole: punches a hole in a file by releasing the blocks
3955 * associated with the given offset and length
3957 * @inode: File inode
3958 * @offset: The offset where the hole will begin
3959 * @len: The length of the hole
3961 * Returns: 0 on success or negative on failure
3964 int ext4_punch_hole(struct file *file, loff_t offset, loff_t length)
3966 struct inode *inode = file_inode(file);
3967 struct super_block *sb = inode->i_sb;
3968 ext4_lblk_t first_block, stop_block;
3969 struct address_space *mapping = inode->i_mapping;
3970 loff_t first_block_offset, last_block_offset, max_length;
3971 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
3973 unsigned int credits;
3974 int ret = 0, ret2 = 0;
3976 trace_ext4_punch_hole(inode, offset, length, 0);
3979 * Write out all dirty pages to avoid race conditions
3980 * Then release them.
3982 if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY)) {
3983 ret = filemap_write_and_wait_range(mapping, offset,
3984 offset + length - 1);
3991 /* No need to punch hole beyond i_size */
3992 if (offset >= inode->i_size)
3996 * If the hole extends beyond i_size, set the hole
3997 * to end after the page that contains i_size
3999 if (offset + length > inode->i_size) {
4000 length = inode->i_size +
4001 PAGE_SIZE - (inode->i_size & (PAGE_SIZE - 1)) -
4006 * For punch hole the length + offset needs to be within one block
4007 * before last range. Adjust the length if it goes beyond that limit.
4009 max_length = sbi->s_bitmap_maxbytes - inode->i_sb->s_blocksize;
4010 if (offset + length > max_length)
4011 length = max_length - offset;
4013 if (offset & (sb->s_blocksize - 1) ||
4014 (offset + length) & (sb->s_blocksize - 1)) {
4016 * Attach jinode to inode for jbd2 if we do any zeroing of
4019 ret = ext4_inode_attach_jinode(inode);
4025 /* Wait all existing dio workers, newcomers will block on i_mutex */
4026 inode_dio_wait(inode);
4028 ret = file_modified(file);
4033 * Prevent page faults from reinstantiating pages we have released from
4036 filemap_invalidate_lock(mapping);
4038 ret = ext4_break_layouts(inode);
4042 first_block_offset = round_up(offset, sb->s_blocksize);
4043 last_block_offset = round_down((offset + length), sb->s_blocksize) - 1;
4045 /* Now release the pages and zero block aligned part of pages*/
4046 if (last_block_offset > first_block_offset) {
4047 ret = ext4_update_disksize_before_punch(inode, offset, length);
4050 truncate_pagecache_range(inode, first_block_offset,
4054 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4055 credits = ext4_writepage_trans_blocks(inode);
4057 credits = ext4_blocks_for_truncate(inode);
4058 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
4059 if (IS_ERR(handle)) {
4060 ret = PTR_ERR(handle);
4061 ext4_std_error(sb, ret);
4065 ret = ext4_zero_partial_blocks(handle, inode, offset,
4070 first_block = (offset + sb->s_blocksize - 1) >>
4071 EXT4_BLOCK_SIZE_BITS(sb);
4072 stop_block = (offset + length) >> EXT4_BLOCK_SIZE_BITS(sb);
4074 /* If there are blocks to remove, do it */
4075 if (stop_block > first_block) {
4077 down_write(&EXT4_I(inode)->i_data_sem);
4078 ext4_discard_preallocations(inode, 0);
4080 ret = ext4_es_remove_extent(inode, first_block,
4081 stop_block - first_block);
4083 up_write(&EXT4_I(inode)->i_data_sem);
4087 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4088 ret = ext4_ext_remove_space(inode, first_block,
4091 ret = ext4_ind_remove_space(handle, inode, first_block,
4094 up_write(&EXT4_I(inode)->i_data_sem);
4096 ext4_fc_track_range(handle, inode, first_block, stop_block);
4098 ext4_handle_sync(handle);
4100 inode->i_mtime = inode->i_ctime = current_time(inode);
4101 ret2 = ext4_mark_inode_dirty(handle, inode);
4105 ext4_update_inode_fsync_trans(handle, inode, 1);
4107 ext4_journal_stop(handle);
4109 filemap_invalidate_unlock(mapping);
4111 inode_unlock(inode);
4115 int ext4_inode_attach_jinode(struct inode *inode)
4117 struct ext4_inode_info *ei = EXT4_I(inode);
4118 struct jbd2_inode *jinode;
4120 if (ei->jinode || !EXT4_SB(inode->i_sb)->s_journal)
4123 jinode = jbd2_alloc_inode(GFP_KERNEL);
4124 spin_lock(&inode->i_lock);
4127 spin_unlock(&inode->i_lock);
4130 ei->jinode = jinode;
4131 jbd2_journal_init_jbd_inode(ei->jinode, inode);
4134 spin_unlock(&inode->i_lock);
4135 if (unlikely(jinode != NULL))
4136 jbd2_free_inode(jinode);
4143 * We block out ext4_get_block() block instantiations across the entire
4144 * transaction, and VFS/VM ensures that ext4_truncate() cannot run
4145 * simultaneously on behalf of the same inode.
4147 * As we work through the truncate and commit bits of it to the journal there
4148 * is one core, guiding principle: the file's tree must always be consistent on
4149 * disk. We must be able to restart the truncate after a crash.
4151 * The file's tree may be transiently inconsistent in memory (although it
4152 * probably isn't), but whenever we close off and commit a journal transaction,
4153 * the contents of (the filesystem + the journal) must be consistent and
4154 * restartable. It's pretty simple, really: bottom up, right to left (although
4155 * left-to-right works OK too).
4157 * Note that at recovery time, journal replay occurs *before* the restart of
4158 * truncate against the orphan inode list.
4160 * The committed inode has the new, desired i_size (which is the same as
4161 * i_disksize in this case). After a crash, ext4_orphan_cleanup() will see
4162 * that this inode's truncate did not complete and it will again call
4163 * ext4_truncate() to have another go. So there will be instantiated blocks
4164 * to the right of the truncation point in a crashed ext4 filesystem. But
4165 * that's fine - as long as they are linked from the inode, the post-crash
4166 * ext4_truncate() run will find them and release them.
4168 int ext4_truncate(struct inode *inode)
4170 struct ext4_inode_info *ei = EXT4_I(inode);
4171 unsigned int credits;
4174 struct address_space *mapping = inode->i_mapping;
4177 * There is a possibility that we're either freeing the inode
4178 * or it's a completely new inode. In those cases we might not
4179 * have i_mutex locked because it's not necessary.
4181 if (!(inode->i_state & (I_NEW|I_FREEING)))
4182 WARN_ON(!inode_is_locked(inode));
4183 trace_ext4_truncate_enter(inode);
4185 if (!ext4_can_truncate(inode))
4188 if (inode->i_size == 0 && !test_opt(inode->i_sb, NO_AUTO_DA_ALLOC))
4189 ext4_set_inode_state(inode, EXT4_STATE_DA_ALLOC_CLOSE);
4191 if (ext4_has_inline_data(inode)) {
4194 err = ext4_inline_data_truncate(inode, &has_inline);
4195 if (err || has_inline)
4199 /* If we zero-out tail of the page, we have to create jinode for jbd2 */
4200 if (inode->i_size & (inode->i_sb->s_blocksize - 1)) {
4201 err = ext4_inode_attach_jinode(inode);
4206 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4207 credits = ext4_writepage_trans_blocks(inode);
4209 credits = ext4_blocks_for_truncate(inode);
4211 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
4212 if (IS_ERR(handle)) {
4213 err = PTR_ERR(handle);
4217 if (inode->i_size & (inode->i_sb->s_blocksize - 1))
4218 ext4_block_truncate_page(handle, mapping, inode->i_size);
4221 * We add the inode to the orphan list, so that if this
4222 * truncate spans multiple transactions, and we crash, we will
4223 * resume the truncate when the filesystem recovers. It also
4224 * marks the inode dirty, to catch the new size.
4226 * Implication: the file must always be in a sane, consistent
4227 * truncatable state while each transaction commits.
4229 err = ext4_orphan_add(handle, inode);
4233 down_write(&EXT4_I(inode)->i_data_sem);
4235 ext4_discard_preallocations(inode, 0);
4237 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4238 err = ext4_ext_truncate(handle, inode);
4240 ext4_ind_truncate(handle, inode);
4242 up_write(&ei->i_data_sem);
4247 ext4_handle_sync(handle);
4251 * If this was a simple ftruncate() and the file will remain alive,
4252 * then we need to clear up the orphan record which we created above.
4253 * However, if this was a real unlink then we were called by
4254 * ext4_evict_inode(), and we allow that function to clean up the
4255 * orphan info for us.
4258 ext4_orphan_del(handle, inode);
4260 inode->i_mtime = inode->i_ctime = current_time(inode);
4261 err2 = ext4_mark_inode_dirty(handle, inode);
4262 if (unlikely(err2 && !err))
4264 ext4_journal_stop(handle);
4267 trace_ext4_truncate_exit(inode);
4272 * ext4_get_inode_loc returns with an extra refcount against the inode's
4273 * underlying buffer_head on success. If 'in_mem' is true, we have all
4274 * data in memory that is needed to recreate the on-disk version of this
4277 static int __ext4_get_inode_loc(struct super_block *sb, unsigned long ino,
4278 struct ext4_iloc *iloc, int in_mem,
4279 ext4_fsblk_t *ret_block)
4281 struct ext4_group_desc *gdp;
4282 struct buffer_head *bh;
4284 struct blk_plug plug;
4285 int inodes_per_block, inode_offset;
4288 if (ino < EXT4_ROOT_INO ||
4289 ino > le32_to_cpu(EXT4_SB(sb)->s_es->s_inodes_count))
4290 return -EFSCORRUPTED;
4292 iloc->block_group = (ino - 1) / EXT4_INODES_PER_GROUP(sb);
4293 gdp = ext4_get_group_desc(sb, iloc->block_group, NULL);
4298 * Figure out the offset within the block group inode table
4300 inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
4301 inode_offset = ((ino - 1) %
4302 EXT4_INODES_PER_GROUP(sb));
4303 iloc->offset = (inode_offset % inodes_per_block) * EXT4_INODE_SIZE(sb);
4305 block = ext4_inode_table(sb, gdp);
4306 if ((block <= le32_to_cpu(EXT4_SB(sb)->s_es->s_first_data_block)) ||
4307 (block >= ext4_blocks_count(EXT4_SB(sb)->s_es))) {
4308 ext4_error(sb, "Invalid inode table block %llu in "
4309 "block_group %u", block, iloc->block_group);
4310 return -EFSCORRUPTED;
4312 block += (inode_offset / inodes_per_block);
4314 bh = sb_getblk(sb, block);
4317 if (ext4_buffer_uptodate(bh))
4321 if (ext4_buffer_uptodate(bh)) {
4322 /* Someone brought it uptodate while we waited */
4328 * If we have all information of the inode in memory and this
4329 * is the only valid inode in the block, we need not read the
4333 struct buffer_head *bitmap_bh;
4336 start = inode_offset & ~(inodes_per_block - 1);
4338 /* Is the inode bitmap in cache? */
4339 bitmap_bh = sb_getblk(sb, ext4_inode_bitmap(sb, gdp));
4340 if (unlikely(!bitmap_bh))
4344 * If the inode bitmap isn't in cache then the
4345 * optimisation may end up performing two reads instead
4346 * of one, so skip it.
4348 if (!buffer_uptodate(bitmap_bh)) {
4352 for (i = start; i < start + inodes_per_block; i++) {
4353 if (i == inode_offset)
4355 if (ext4_test_bit(i, bitmap_bh->b_data))
4359 if (i == start + inodes_per_block) {
4360 /* all other inodes are free, so skip I/O */
4361 memset(bh->b_data, 0, bh->b_size);
4362 set_buffer_uptodate(bh);
4370 * If we need to do any I/O, try to pre-readahead extra
4371 * blocks from the inode table.
4373 blk_start_plug(&plug);
4374 if (EXT4_SB(sb)->s_inode_readahead_blks) {
4375 ext4_fsblk_t b, end, table;
4377 __u32 ra_blks = EXT4_SB(sb)->s_inode_readahead_blks;
4379 table = ext4_inode_table(sb, gdp);
4380 /* s_inode_readahead_blks is always a power of 2 */
4381 b = block & ~((ext4_fsblk_t) ra_blks - 1);
4385 num = EXT4_INODES_PER_GROUP(sb);
4386 if (ext4_has_group_desc_csum(sb))
4387 num -= ext4_itable_unused_count(sb, gdp);
4388 table += num / inodes_per_block;
4392 ext4_sb_breadahead_unmovable(sb, b++);
4396 * There are other valid inodes in the buffer, this inode
4397 * has in-inode xattrs, or we don't have this inode in memory.
4398 * Read the block from disk.
4400 trace_ext4_load_inode(sb, ino);
4401 ext4_read_bh_nowait(bh, REQ_META | REQ_PRIO, NULL);
4402 blk_finish_plug(&plug);
4404 ext4_simulate_fail_bh(sb, bh, EXT4_SIM_INODE_EIO);
4405 if (!buffer_uptodate(bh)) {
4416 static int __ext4_get_inode_loc_noinmem(struct inode *inode,
4417 struct ext4_iloc *iloc)
4419 ext4_fsblk_t err_blk = 0;
4422 ret = __ext4_get_inode_loc(inode->i_sb, inode->i_ino, iloc, 0,
4426 ext4_error_inode_block(inode, err_blk, EIO,
4427 "unable to read itable block");
4432 int ext4_get_inode_loc(struct inode *inode, struct ext4_iloc *iloc)
4434 ext4_fsblk_t err_blk = 0;
4437 /* We have all inode data except xattrs in memory here. */
4438 ret = __ext4_get_inode_loc(inode->i_sb, inode->i_ino, iloc,
4439 !ext4_test_inode_state(inode, EXT4_STATE_XATTR), &err_blk);
4442 ext4_error_inode_block(inode, err_blk, EIO,
4443 "unable to read itable block");
4449 int ext4_get_fc_inode_loc(struct super_block *sb, unsigned long ino,
4450 struct ext4_iloc *iloc)
4452 return __ext4_get_inode_loc(sb, ino, iloc, 0, NULL);
4455 static bool ext4_should_enable_dax(struct inode *inode)
4457 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4459 if (test_opt2(inode->i_sb, DAX_NEVER))
4461 if (!S_ISREG(inode->i_mode))
4463 if (ext4_should_journal_data(inode))
4465 if (ext4_has_inline_data(inode))
4467 if (ext4_test_inode_flag(inode, EXT4_INODE_ENCRYPT))
4469 if (ext4_test_inode_flag(inode, EXT4_INODE_VERITY))
4471 if (!test_bit(EXT4_FLAGS_BDEV_IS_DAX, &sbi->s_ext4_flags))
4473 if (test_opt(inode->i_sb, DAX_ALWAYS))
4476 return ext4_test_inode_flag(inode, EXT4_INODE_DAX);
4479 void ext4_set_inode_flags(struct inode *inode, bool init)
4481 unsigned int flags = EXT4_I(inode)->i_flags;
4482 unsigned int new_fl = 0;
4484 WARN_ON_ONCE(IS_DAX(inode) && init);
4486 if (flags & EXT4_SYNC_FL)
4488 if (flags & EXT4_APPEND_FL)
4490 if (flags & EXT4_IMMUTABLE_FL)
4491 new_fl |= S_IMMUTABLE;
4492 if (flags & EXT4_NOATIME_FL)
4493 new_fl |= S_NOATIME;
4494 if (flags & EXT4_DIRSYNC_FL)
4495 new_fl |= S_DIRSYNC;
4497 /* Because of the way inode_set_flags() works we must preserve S_DAX
4498 * here if already set. */
4499 new_fl |= (inode->i_flags & S_DAX);
4500 if (init && ext4_should_enable_dax(inode))
4503 if (flags & EXT4_ENCRYPT_FL)
4504 new_fl |= S_ENCRYPTED;
4505 if (flags & EXT4_CASEFOLD_FL)
4506 new_fl |= S_CASEFOLD;
4507 if (flags & EXT4_VERITY_FL)
4509 inode_set_flags(inode, new_fl,
4510 S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME|S_DIRSYNC|S_DAX|
4511 S_ENCRYPTED|S_CASEFOLD|S_VERITY);
4514 static blkcnt_t ext4_inode_blocks(struct ext4_inode *raw_inode,
4515 struct ext4_inode_info *ei)
4518 struct inode *inode = &(ei->vfs_inode);
4519 struct super_block *sb = inode->i_sb;
4521 if (ext4_has_feature_huge_file(sb)) {
4522 /* we are using combined 48 bit field */
4523 i_blocks = ((u64)le16_to_cpu(raw_inode->i_blocks_high)) << 32 |
4524 le32_to_cpu(raw_inode->i_blocks_lo);
4525 if (ext4_test_inode_flag(inode, EXT4_INODE_HUGE_FILE)) {
4526 /* i_blocks represent file system block size */
4527 return i_blocks << (inode->i_blkbits - 9);
4532 return le32_to_cpu(raw_inode->i_blocks_lo);
4536 static inline int ext4_iget_extra_inode(struct inode *inode,
4537 struct ext4_inode *raw_inode,
4538 struct ext4_inode_info *ei)
4540 __le32 *magic = (void *)raw_inode +
4541 EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize;
4543 if (EXT4_INODE_HAS_XATTR_SPACE(inode) &&
4544 *magic == cpu_to_le32(EXT4_XATTR_MAGIC)) {
4547 ext4_set_inode_state(inode, EXT4_STATE_XATTR);
4548 err = ext4_find_inline_data_nolock(inode);
4549 if (!err && ext4_has_inline_data(inode))
4550 ext4_set_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA);
4553 EXT4_I(inode)->i_inline_off = 0;
4557 int ext4_get_projid(struct inode *inode, kprojid_t *projid)
4559 if (!ext4_has_feature_project(inode->i_sb))
4561 *projid = EXT4_I(inode)->i_projid;
4566 * ext4 has self-managed i_version for ea inodes, it stores the lower 32bit of
4567 * refcount in i_version, so use raw values if inode has EXT4_EA_INODE_FL flag
4570 static inline void ext4_inode_set_iversion_queried(struct inode *inode, u64 val)
4572 if (unlikely(EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL))
4573 inode_set_iversion_raw(inode, val);
4575 inode_set_iversion_queried(inode, val);
4577 static inline u64 ext4_inode_peek_iversion(const struct inode *inode)
4579 if (unlikely(EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL))
4580 return inode_peek_iversion_raw(inode);
4582 return inode_peek_iversion(inode);
4585 static const char *check_igot_inode(struct inode *inode, ext4_iget_flags flags)
4588 if (flags & EXT4_IGET_EA_INODE) {
4589 if (!(EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL))
4590 return "missing EA_INODE flag";
4591 if (ext4_test_inode_state(inode, EXT4_STATE_XATTR) ||
4592 EXT4_I(inode)->i_file_acl)
4593 return "ea_inode with extended attributes";
4595 if ((EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL))
4596 return "unexpected EA_INODE flag";
4598 if (is_bad_inode(inode) && !(flags & EXT4_IGET_BAD))
4599 return "unexpected bad inode w/o EXT4_IGET_BAD";
4603 struct inode *__ext4_iget(struct super_block *sb, unsigned long ino,
4604 ext4_iget_flags flags, const char *function,
4607 struct ext4_iloc iloc;
4608 struct ext4_inode *raw_inode;
4609 struct ext4_inode_info *ei;
4610 struct ext4_super_block *es = EXT4_SB(sb)->s_es;
4611 struct inode *inode;
4612 const char *err_str;
4613 journal_t *journal = EXT4_SB(sb)->s_journal;
4621 if ((!(flags & EXT4_IGET_SPECIAL) &&
4622 ((ino < EXT4_FIRST_INO(sb) && ino != EXT4_ROOT_INO) ||
4623 ino == le32_to_cpu(es->s_usr_quota_inum) ||
4624 ino == le32_to_cpu(es->s_grp_quota_inum) ||
4625 ino == le32_to_cpu(es->s_prj_quota_inum) ||
4626 ino == le32_to_cpu(es->s_orphan_file_inum))) ||
4627 (ino < EXT4_ROOT_INO) ||
4628 (ino > le32_to_cpu(es->s_inodes_count))) {
4629 if (flags & EXT4_IGET_HANDLE)
4630 return ERR_PTR(-ESTALE);
4631 __ext4_error(sb, function, line, false, EFSCORRUPTED, 0,
4632 "inode #%lu: comm %s: iget: illegal inode #",
4633 ino, current->comm);
4634 return ERR_PTR(-EFSCORRUPTED);
4637 inode = iget_locked(sb, ino);
4639 return ERR_PTR(-ENOMEM);
4640 if (!(inode->i_state & I_NEW)) {
4641 if ((err_str = check_igot_inode(inode, flags)) != NULL) {
4642 ext4_error_inode(inode, function, line, 0, err_str);
4644 return ERR_PTR(-EFSCORRUPTED);
4652 ret = __ext4_get_inode_loc_noinmem(inode, &iloc);
4655 raw_inode = ext4_raw_inode(&iloc);
4657 if ((flags & EXT4_IGET_HANDLE) &&
4658 (raw_inode->i_links_count == 0) && (raw_inode->i_mode == 0)) {
4663 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4664 ei->i_extra_isize = le16_to_cpu(raw_inode->i_extra_isize);
4665 if (EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize >
4666 EXT4_INODE_SIZE(inode->i_sb) ||
4667 (ei->i_extra_isize & 3)) {
4668 ext4_error_inode(inode, function, line, 0,
4669 "iget: bad extra_isize %u "
4672 EXT4_INODE_SIZE(inode->i_sb));
4673 ret = -EFSCORRUPTED;
4677 ei->i_extra_isize = 0;
4679 /* Precompute checksum seed for inode metadata */
4680 if (ext4_has_metadata_csum(sb)) {
4681 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
4683 __le32 inum = cpu_to_le32(inode->i_ino);
4684 __le32 gen = raw_inode->i_generation;
4685 csum = ext4_chksum(sbi, sbi->s_csum_seed, (__u8 *)&inum,
4687 ei->i_csum_seed = ext4_chksum(sbi, csum, (__u8 *)&gen,
4691 if ((!ext4_inode_csum_verify(inode, raw_inode, ei) ||
4692 ext4_simulate_fail(sb, EXT4_SIM_INODE_CRC)) &&
4693 (!(EXT4_SB(sb)->s_mount_state & EXT4_FC_REPLAY))) {
4694 ext4_error_inode_err(inode, function, line, 0,
4695 EFSBADCRC, "iget: checksum invalid");
4700 inode->i_mode = le16_to_cpu(raw_inode->i_mode);
4701 i_uid = (uid_t)le16_to_cpu(raw_inode->i_uid_low);
4702 i_gid = (gid_t)le16_to_cpu(raw_inode->i_gid_low);
4703 if (ext4_has_feature_project(sb) &&
4704 EXT4_INODE_SIZE(sb) > EXT4_GOOD_OLD_INODE_SIZE &&
4705 EXT4_FITS_IN_INODE(raw_inode, ei, i_projid))
4706 i_projid = (projid_t)le32_to_cpu(raw_inode->i_projid);
4708 i_projid = EXT4_DEF_PROJID;
4710 if (!(test_opt(inode->i_sb, NO_UID32))) {
4711 i_uid |= le16_to_cpu(raw_inode->i_uid_high) << 16;
4712 i_gid |= le16_to_cpu(raw_inode->i_gid_high) << 16;
4714 i_uid_write(inode, i_uid);
4715 i_gid_write(inode, i_gid);
4716 ei->i_projid = make_kprojid(&init_user_ns, i_projid);
4717 set_nlink(inode, le16_to_cpu(raw_inode->i_links_count));
4719 ext4_clear_state_flags(ei); /* Only relevant on 32-bit archs */
4720 ei->i_inline_off = 0;
4721 ei->i_dir_start_lookup = 0;
4722 ei->i_dtime = le32_to_cpu(raw_inode->i_dtime);
4723 /* We now have enough fields to check if the inode was active or not.
4724 * This is needed because nfsd might try to access dead inodes
4725 * the test is that same one that e2fsck uses
4726 * NeilBrown 1999oct15
4728 if (inode->i_nlink == 0) {
4729 if ((inode->i_mode == 0 || flags & EXT4_IGET_SPECIAL ||
4730 !(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_ORPHAN_FS)) &&
4731 ino != EXT4_BOOT_LOADER_INO) {
4732 /* this inode is deleted or unallocated */
4733 if (flags & EXT4_IGET_SPECIAL) {
4734 ext4_error_inode(inode, function, line, 0,
4735 "iget: special inode unallocated");
4736 ret = -EFSCORRUPTED;
4741 /* The only unlinked inodes we let through here have
4742 * valid i_mode and are being read by the orphan
4743 * recovery code: that's fine, we're about to complete
4744 * the process of deleting those.
4745 * OR it is the EXT4_BOOT_LOADER_INO which is
4746 * not initialized on a new filesystem. */
4748 ei->i_flags = le32_to_cpu(raw_inode->i_flags);
4749 ext4_set_inode_flags(inode, true);
4750 inode->i_blocks = ext4_inode_blocks(raw_inode, ei);
4751 ei->i_file_acl = le32_to_cpu(raw_inode->i_file_acl_lo);
4752 if (ext4_has_feature_64bit(sb))
4754 ((__u64)le16_to_cpu(raw_inode->i_file_acl_high)) << 32;
4755 inode->i_size = ext4_isize(sb, raw_inode);
4756 if ((size = i_size_read(inode)) < 0) {
4757 ext4_error_inode(inode, function, line, 0,
4758 "iget: bad i_size value: %lld", size);
4759 ret = -EFSCORRUPTED;
4763 * If dir_index is not enabled but there's dir with INDEX flag set,
4764 * we'd normally treat htree data as empty space. But with metadata
4765 * checksumming that corrupts checksums so forbid that.
4767 if (!ext4_has_feature_dir_index(sb) && ext4_has_metadata_csum(sb) &&
4768 ext4_test_inode_flag(inode, EXT4_INODE_INDEX)) {
4769 ext4_error_inode(inode, function, line, 0,
4770 "iget: Dir with htree data on filesystem without dir_index feature.");
4771 ret = -EFSCORRUPTED;
4774 ei->i_disksize = inode->i_size;
4776 ei->i_reserved_quota = 0;
4778 inode->i_generation = le32_to_cpu(raw_inode->i_generation);
4779 ei->i_block_group = iloc.block_group;
4780 ei->i_last_alloc_group = ~0;
4782 * NOTE! The in-memory inode i_data array is in little-endian order
4783 * even on big-endian machines: we do NOT byteswap the block numbers!
4785 for (block = 0; block < EXT4_N_BLOCKS; block++)
4786 ei->i_data[block] = raw_inode->i_block[block];
4787 INIT_LIST_HEAD(&ei->i_orphan);
4788 ext4_fc_init_inode(&ei->vfs_inode);
4791 * Set transaction id's of transactions that have to be committed
4792 * to finish f[data]sync. We set them to currently running transaction
4793 * as we cannot be sure that the inode or some of its metadata isn't
4794 * part of the transaction - the inode could have been reclaimed and
4795 * now it is reread from disk.
4798 transaction_t *transaction;
4801 read_lock(&journal->j_state_lock);
4802 if (journal->j_running_transaction)
4803 transaction = journal->j_running_transaction;
4805 transaction = journal->j_committing_transaction;
4807 tid = transaction->t_tid;
4809 tid = journal->j_commit_sequence;
4810 read_unlock(&journal->j_state_lock);
4811 ei->i_sync_tid = tid;
4812 ei->i_datasync_tid = tid;
4815 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4816 if (ei->i_extra_isize == 0) {
4817 /* The extra space is currently unused. Use it. */
4818 BUILD_BUG_ON(sizeof(struct ext4_inode) & 3);
4819 ei->i_extra_isize = sizeof(struct ext4_inode) -
4820 EXT4_GOOD_OLD_INODE_SIZE;
4822 ret = ext4_iget_extra_inode(inode, raw_inode, ei);
4828 EXT4_INODE_GET_XTIME(i_ctime, inode, raw_inode);
4829 EXT4_INODE_GET_XTIME(i_mtime, inode, raw_inode);
4830 EXT4_INODE_GET_XTIME(i_atime, inode, raw_inode);
4831 EXT4_EINODE_GET_XTIME(i_crtime, ei, raw_inode);
4833 if (likely(!test_opt2(inode->i_sb, HURD_COMPAT))) {
4834 u64 ivers = le32_to_cpu(raw_inode->i_disk_version);
4836 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4837 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
4839 (__u64)(le32_to_cpu(raw_inode->i_version_hi)) << 32;
4841 ext4_inode_set_iversion_queried(inode, ivers);
4845 if (ei->i_file_acl &&
4846 !ext4_inode_block_valid(inode, ei->i_file_acl, 1)) {
4847 ext4_error_inode(inode, function, line, 0,
4848 "iget: bad extended attribute block %llu",
4850 ret = -EFSCORRUPTED;
4852 } else if (!ext4_has_inline_data(inode)) {
4853 /* validate the block references in the inode */
4854 if (!(EXT4_SB(sb)->s_mount_state & EXT4_FC_REPLAY) &&
4855 (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
4856 (S_ISLNK(inode->i_mode) &&
4857 !ext4_inode_is_fast_symlink(inode)))) {
4858 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4859 ret = ext4_ext_check_inode(inode);
4861 ret = ext4_ind_check_inode(inode);
4867 if (S_ISREG(inode->i_mode)) {
4868 inode->i_op = &ext4_file_inode_operations;
4869 inode->i_fop = &ext4_file_operations;
4870 ext4_set_aops(inode);
4871 } else if (S_ISDIR(inode->i_mode)) {
4872 inode->i_op = &ext4_dir_inode_operations;
4873 inode->i_fop = &ext4_dir_operations;
4874 } else if (S_ISLNK(inode->i_mode)) {
4875 /* VFS does not allow setting these so must be corruption */
4876 if (IS_APPEND(inode) || IS_IMMUTABLE(inode)) {
4877 ext4_error_inode(inode, function, line, 0,
4878 "iget: immutable or append flags "
4879 "not allowed on symlinks");
4880 ret = -EFSCORRUPTED;
4883 if (IS_ENCRYPTED(inode)) {
4884 inode->i_op = &ext4_encrypted_symlink_inode_operations;
4885 ext4_set_aops(inode);
4886 } else if (ext4_inode_is_fast_symlink(inode)) {
4887 inode->i_link = (char *)ei->i_data;
4888 inode->i_op = &ext4_fast_symlink_inode_operations;
4889 nd_terminate_link(ei->i_data, inode->i_size,
4890 sizeof(ei->i_data) - 1);
4892 inode->i_op = &ext4_symlink_inode_operations;
4893 ext4_set_aops(inode);
4895 inode_nohighmem(inode);
4896 } else if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode) ||
4897 S_ISFIFO(inode->i_mode) || S_ISSOCK(inode->i_mode)) {
4898 inode->i_op = &ext4_special_inode_operations;
4899 if (raw_inode->i_block[0])
4900 init_special_inode(inode, inode->i_mode,
4901 old_decode_dev(le32_to_cpu(raw_inode->i_block[0])));
4903 init_special_inode(inode, inode->i_mode,
4904 new_decode_dev(le32_to_cpu(raw_inode->i_block[1])));
4905 } else if (ino == EXT4_BOOT_LOADER_INO) {
4906 make_bad_inode(inode);
4908 ret = -EFSCORRUPTED;
4909 ext4_error_inode(inode, function, line, 0,
4910 "iget: bogus i_mode (%o)", inode->i_mode);
4913 if (IS_CASEFOLDED(inode) && !ext4_has_feature_casefold(inode->i_sb))
4914 ext4_error_inode(inode, function, line, 0,
4915 "casefold flag without casefold feature");
4916 if ((err_str = check_igot_inode(inode, flags)) != NULL) {
4917 ext4_error_inode(inode, function, line, 0, err_str);
4918 ret = -EFSCORRUPTED;
4923 unlock_new_inode(inode);
4929 return ERR_PTR(ret);
4932 static int ext4_inode_blocks_set(handle_t *handle,
4933 struct ext4_inode *raw_inode,
4934 struct ext4_inode_info *ei)
4936 struct inode *inode = &(ei->vfs_inode);
4937 u64 i_blocks = READ_ONCE(inode->i_blocks);
4938 struct super_block *sb = inode->i_sb;
4940 if (i_blocks <= ~0U) {
4942 * i_blocks can be represented in a 32 bit variable
4943 * as multiple of 512 bytes
4945 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
4946 raw_inode->i_blocks_high = 0;
4947 ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
4952 * This should never happen since sb->s_maxbytes should not have
4953 * allowed this, sb->s_maxbytes was set according to the huge_file
4954 * feature in ext4_fill_super().
4956 if (!ext4_has_feature_huge_file(sb))
4957 return -EFSCORRUPTED;
4959 if (i_blocks <= 0xffffffffffffULL) {
4961 * i_blocks can be represented in a 48 bit variable
4962 * as multiple of 512 bytes
4964 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
4965 raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
4966 ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
4968 ext4_set_inode_flag(inode, EXT4_INODE_HUGE_FILE);
4969 /* i_block is stored in file system block size */
4970 i_blocks = i_blocks >> (inode->i_blkbits - 9);
4971 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
4972 raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
4977 static void __ext4_update_other_inode_time(struct super_block *sb,
4978 unsigned long orig_ino,
4980 struct ext4_inode *raw_inode)
4982 struct inode *inode;
4984 inode = find_inode_by_ino_rcu(sb, ino);
4988 if (!inode_is_dirtytime_only(inode))
4991 spin_lock(&inode->i_lock);
4992 if (inode_is_dirtytime_only(inode)) {
4993 struct ext4_inode_info *ei = EXT4_I(inode);
4995 inode->i_state &= ~I_DIRTY_TIME;
4996 spin_unlock(&inode->i_lock);
4998 spin_lock(&ei->i_raw_lock);
4999 EXT4_INODE_SET_XTIME(i_ctime, inode, raw_inode);
5000 EXT4_INODE_SET_XTIME(i_mtime, inode, raw_inode);
5001 EXT4_INODE_SET_XTIME(i_atime, inode, raw_inode);
5002 ext4_inode_csum_set(inode, raw_inode, ei);
5003 spin_unlock(&ei->i_raw_lock);
5004 trace_ext4_other_inode_update_time(inode, orig_ino);
5007 spin_unlock(&inode->i_lock);
5011 * Opportunistically update the other time fields for other inodes in
5012 * the same inode table block.
5014 static void ext4_update_other_inodes_time(struct super_block *sb,
5015 unsigned long orig_ino, char *buf)
5018 int i, inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
5019 int inode_size = EXT4_INODE_SIZE(sb);
5022 * Calculate the first inode in the inode table block. Inode
5023 * numbers are one-based. That is, the first inode in a block
5024 * (assuming 4k blocks and 256 byte inodes) is (n*16 + 1).
5026 ino = ((orig_ino - 1) & ~(inodes_per_block - 1)) + 1;
5028 for (i = 0; i < inodes_per_block; i++, ino++, buf += inode_size) {
5029 if (ino == orig_ino)
5031 __ext4_update_other_inode_time(sb, orig_ino, ino,
5032 (struct ext4_inode *)buf);
5038 * Post the struct inode info into an on-disk inode location in the
5039 * buffer-cache. This gobbles the caller's reference to the
5040 * buffer_head in the inode location struct.
5042 * The caller must have write access to iloc->bh.
5044 static int ext4_do_update_inode(handle_t *handle,
5045 struct inode *inode,
5046 struct ext4_iloc *iloc)
5048 struct ext4_inode *raw_inode = ext4_raw_inode(iloc);
5049 struct ext4_inode_info *ei = EXT4_I(inode);
5050 struct buffer_head *bh = iloc->bh;
5051 struct super_block *sb = inode->i_sb;
5053 int need_datasync = 0, set_large_file = 0;
5058 spin_lock(&ei->i_raw_lock);
5061 * For fields not tracked in the in-memory inode, initialise them
5062 * to zero for new inodes.
5064 if (ext4_test_inode_state(inode, EXT4_STATE_NEW))
5065 memset(raw_inode, 0, EXT4_SB(inode->i_sb)->s_inode_size);
5067 err = ext4_inode_blocks_set(handle, raw_inode, ei);
5069 raw_inode->i_mode = cpu_to_le16(inode->i_mode);
5070 i_uid = i_uid_read(inode);
5071 i_gid = i_gid_read(inode);
5072 i_projid = from_kprojid(&init_user_ns, ei->i_projid);
5073 if (!(test_opt(inode->i_sb, NO_UID32))) {
5074 raw_inode->i_uid_low = cpu_to_le16(low_16_bits(i_uid));
5075 raw_inode->i_gid_low = cpu_to_le16(low_16_bits(i_gid));
5077 * Fix up interoperability with old kernels. Otherwise,
5078 * old inodes get re-used with the upper 16 bits of the
5081 if (ei->i_dtime && list_empty(&ei->i_orphan)) {
5082 raw_inode->i_uid_high = 0;
5083 raw_inode->i_gid_high = 0;
5085 raw_inode->i_uid_high =
5086 cpu_to_le16(high_16_bits(i_uid));
5087 raw_inode->i_gid_high =
5088 cpu_to_le16(high_16_bits(i_gid));
5091 raw_inode->i_uid_low = cpu_to_le16(fs_high2lowuid(i_uid));
5092 raw_inode->i_gid_low = cpu_to_le16(fs_high2lowgid(i_gid));
5093 raw_inode->i_uid_high = 0;
5094 raw_inode->i_gid_high = 0;
5096 raw_inode->i_links_count = cpu_to_le16(inode->i_nlink);
5098 EXT4_INODE_SET_XTIME(i_ctime, inode, raw_inode);
5099 EXT4_INODE_SET_XTIME(i_mtime, inode, raw_inode);
5100 EXT4_INODE_SET_XTIME(i_atime, inode, raw_inode);
5101 EXT4_EINODE_SET_XTIME(i_crtime, ei, raw_inode);
5103 raw_inode->i_dtime = cpu_to_le32(ei->i_dtime);
5104 raw_inode->i_flags = cpu_to_le32(ei->i_flags & 0xFFFFFFFF);
5105 if (likely(!test_opt2(inode->i_sb, HURD_COMPAT)))
5106 raw_inode->i_file_acl_high =
5107 cpu_to_le16(ei->i_file_acl >> 32);
5108 raw_inode->i_file_acl_lo = cpu_to_le32(ei->i_file_acl);
5109 if (READ_ONCE(ei->i_disksize) != ext4_isize(inode->i_sb, raw_inode)) {
5110 ext4_isize_set(raw_inode, ei->i_disksize);
5113 if (ei->i_disksize > 0x7fffffffULL) {
5114 if (!ext4_has_feature_large_file(sb) ||
5115 EXT4_SB(sb)->s_es->s_rev_level ==
5116 cpu_to_le32(EXT4_GOOD_OLD_REV))
5119 raw_inode->i_generation = cpu_to_le32(inode->i_generation);
5120 if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) {
5121 if (old_valid_dev(inode->i_rdev)) {
5122 raw_inode->i_block[0] =
5123 cpu_to_le32(old_encode_dev(inode->i_rdev));
5124 raw_inode->i_block[1] = 0;
5126 raw_inode->i_block[0] = 0;
5127 raw_inode->i_block[1] =
5128 cpu_to_le32(new_encode_dev(inode->i_rdev));
5129 raw_inode->i_block[2] = 0;
5131 } else if (!ext4_has_inline_data(inode)) {
5132 for (block = 0; block < EXT4_N_BLOCKS; block++)
5133 raw_inode->i_block[block] = ei->i_data[block];
5136 if (likely(!test_opt2(inode->i_sb, HURD_COMPAT))) {
5137 u64 ivers = ext4_inode_peek_iversion(inode);
5139 raw_inode->i_disk_version = cpu_to_le32(ivers);
5140 if (ei->i_extra_isize) {
5141 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
5142 raw_inode->i_version_hi =
5143 cpu_to_le32(ivers >> 32);
5144 raw_inode->i_extra_isize =
5145 cpu_to_le16(ei->i_extra_isize);
5149 if (i_projid != EXT4_DEF_PROJID &&
5150 !ext4_has_feature_project(inode->i_sb))
5151 err = err ?: -EFSCORRUPTED;
5153 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
5154 EXT4_FITS_IN_INODE(raw_inode, ei, i_projid))
5155 raw_inode->i_projid = cpu_to_le32(i_projid);
5157 ext4_inode_csum_set(inode, raw_inode, ei);
5158 spin_unlock(&ei->i_raw_lock);
5160 EXT4_ERROR_INODE(inode, "corrupted inode contents");
5164 if (inode->i_sb->s_flags & SB_LAZYTIME)
5165 ext4_update_other_inodes_time(inode->i_sb, inode->i_ino,
5168 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
5169 err = ext4_handle_dirty_metadata(handle, NULL, bh);
5172 ext4_clear_inode_state(inode, EXT4_STATE_NEW);
5173 if (set_large_file) {
5174 BUFFER_TRACE(EXT4_SB(sb)->s_sbh, "get write access");
5175 err = ext4_journal_get_write_access(handle, sb,
5180 lock_buffer(EXT4_SB(sb)->s_sbh);
5181 ext4_set_feature_large_file(sb);
5182 ext4_superblock_csum_set(sb);
5183 unlock_buffer(EXT4_SB(sb)->s_sbh);
5184 ext4_handle_sync(handle);
5185 err = ext4_handle_dirty_metadata(handle, NULL,
5186 EXT4_SB(sb)->s_sbh);
5188 ext4_update_inode_fsync_trans(handle, inode, need_datasync);
5190 ext4_std_error(inode->i_sb, err);
5197 * ext4_write_inode()
5199 * We are called from a few places:
5201 * - Within generic_file_aio_write() -> generic_write_sync() for O_SYNC files.
5202 * Here, there will be no transaction running. We wait for any running
5203 * transaction to commit.
5205 * - Within flush work (sys_sync(), kupdate and such).
5206 * We wait on commit, if told to.
5208 * - Within iput_final() -> write_inode_now()
5209 * We wait on commit, if told to.
5211 * In all cases it is actually safe for us to return without doing anything,
5212 * because the inode has been copied into a raw inode buffer in
5213 * ext4_mark_inode_dirty(). This is a correctness thing for WB_SYNC_ALL
5216 * Note that we are absolutely dependent upon all inode dirtiers doing the
5217 * right thing: they *must* call mark_inode_dirty() after dirtying info in
5218 * which we are interested.
5220 * It would be a bug for them to not do this. The code:
5222 * mark_inode_dirty(inode)
5224 * inode->i_size = expr;
5226 * is in error because write_inode() could occur while `stuff()' is running,
5227 * and the new i_size will be lost. Plus the inode will no longer be on the
5228 * superblock's dirty inode list.
5230 int ext4_write_inode(struct inode *inode, struct writeback_control *wbc)
5234 if (WARN_ON_ONCE(current->flags & PF_MEMALLOC) ||
5235 sb_rdonly(inode->i_sb))
5238 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
5241 if (EXT4_SB(inode->i_sb)->s_journal) {
5242 if (ext4_journal_current_handle()) {
5243 ext4_debug("called recursively, non-PF_MEMALLOC!\n");
5249 * No need to force transaction in WB_SYNC_NONE mode. Also
5250 * ext4_sync_fs() will force the commit after everything is
5253 if (wbc->sync_mode != WB_SYNC_ALL || wbc->for_sync)
5256 err = ext4_fc_commit(EXT4_SB(inode->i_sb)->s_journal,
5257 EXT4_I(inode)->i_sync_tid);
5259 struct ext4_iloc iloc;
5261 err = __ext4_get_inode_loc_noinmem(inode, &iloc);
5265 * sync(2) will flush the whole buffer cache. No need to do
5266 * it here separately for each inode.
5268 if (wbc->sync_mode == WB_SYNC_ALL && !wbc->for_sync)
5269 sync_dirty_buffer(iloc.bh);
5270 if (buffer_req(iloc.bh) && !buffer_uptodate(iloc.bh)) {
5271 ext4_error_inode_block(inode, iloc.bh->b_blocknr, EIO,
5272 "IO error syncing inode");
5281 * In data=journal mode ext4_journalled_invalidatepage() may fail to invalidate
5282 * buffers that are attached to a page stradding i_size and are undergoing
5283 * commit. In that case we have to wait for commit to finish and try again.
5285 static void ext4_wait_for_tail_page_commit(struct inode *inode)
5289 journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
5290 tid_t commit_tid = 0;
5293 offset = inode->i_size & (PAGE_SIZE - 1);
5295 * If the page is fully truncated, we don't need to wait for any commit
5296 * (and we even should not as __ext4_journalled_invalidatepage() may
5297 * strip all buffers from the page but keep the page dirty which can then
5298 * confuse e.g. concurrent ext4_writepage() seeing dirty page without
5299 * buffers). Also we don't need to wait for any commit if all buffers in
5300 * the page remain valid. This is most beneficial for the common case of
5301 * blocksize == PAGESIZE.
5303 if (!offset || offset > (PAGE_SIZE - i_blocksize(inode)))
5306 page = find_lock_page(inode->i_mapping,
5307 inode->i_size >> PAGE_SHIFT);
5310 ret = __ext4_journalled_invalidatepage(page, offset,
5311 PAGE_SIZE - offset);
5317 read_lock(&journal->j_state_lock);
5318 if (journal->j_committing_transaction)
5319 commit_tid = journal->j_committing_transaction->t_tid;
5320 read_unlock(&journal->j_state_lock);
5322 jbd2_log_wait_commit(journal, commit_tid);
5329 * Called from notify_change.
5331 * We want to trap VFS attempts to truncate the file as soon as
5332 * possible. In particular, we want to make sure that when the VFS
5333 * shrinks i_size, we put the inode on the orphan list and modify
5334 * i_disksize immediately, so that during the subsequent flushing of
5335 * dirty pages and freeing of disk blocks, we can guarantee that any
5336 * commit will leave the blocks being flushed in an unused state on
5337 * disk. (On recovery, the inode will get truncated and the blocks will
5338 * be freed, so we have a strong guarantee that no future commit will
5339 * leave these blocks visible to the user.)
5341 * Another thing we have to assure is that if we are in ordered mode
5342 * and inode is still attached to the committing transaction, we must
5343 * we start writeout of all the dirty pages which are being truncated.
5344 * This way we are sure that all the data written in the previous
5345 * transaction are already on disk (truncate waits for pages under
5348 * Called with inode->i_mutex down.
5350 int ext4_setattr(struct user_namespace *mnt_userns, struct dentry *dentry,
5353 struct inode *inode = d_inode(dentry);
5356 const unsigned int ia_valid = attr->ia_valid;
5358 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
5361 if (unlikely(IS_IMMUTABLE(inode)))
5364 if (unlikely(IS_APPEND(inode) &&
5365 (ia_valid & (ATTR_MODE | ATTR_UID |
5366 ATTR_GID | ATTR_TIMES_SET))))
5369 error = setattr_prepare(mnt_userns, dentry, attr);
5373 error = fscrypt_prepare_setattr(dentry, attr);
5377 error = fsverity_prepare_setattr(dentry, attr);
5381 if (is_quota_modification(inode, attr)) {
5382 error = dquot_initialize(inode);
5387 if ((ia_valid & ATTR_UID && !uid_eq(attr->ia_uid, inode->i_uid)) ||
5388 (ia_valid & ATTR_GID && !gid_eq(attr->ia_gid, inode->i_gid))) {
5391 /* (user+group)*(old+new) structure, inode write (sb,
5392 * inode block, ? - but truncate inode update has it) */
5393 handle = ext4_journal_start(inode, EXT4_HT_QUOTA,
5394 (EXT4_MAXQUOTAS_INIT_BLOCKS(inode->i_sb) +
5395 EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb)) + 3);
5396 if (IS_ERR(handle)) {
5397 error = PTR_ERR(handle);
5401 /* dquot_transfer() calls back ext4_get_inode_usage() which
5402 * counts xattr inode references.
5404 down_read(&EXT4_I(inode)->xattr_sem);
5405 error = dquot_transfer(inode, attr);
5406 up_read(&EXT4_I(inode)->xattr_sem);
5409 ext4_journal_stop(handle);
5412 /* Update corresponding info in inode so that everything is in
5413 * one transaction */
5414 if (attr->ia_valid & ATTR_UID)
5415 inode->i_uid = attr->ia_uid;
5416 if (attr->ia_valid & ATTR_GID)
5417 inode->i_gid = attr->ia_gid;
5418 error = ext4_mark_inode_dirty(handle, inode);
5419 ext4_journal_stop(handle);
5420 if (unlikely(error)) {
5425 if (attr->ia_valid & ATTR_SIZE) {
5427 loff_t oldsize = inode->i_size;
5428 loff_t old_disksize;
5429 int shrink = (attr->ia_size < inode->i_size);
5431 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
5432 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
5434 if (attr->ia_size > sbi->s_bitmap_maxbytes) {
5438 if (!S_ISREG(inode->i_mode)) {
5442 if (IS_I_VERSION(inode) && attr->ia_size != inode->i_size)
5443 inode_inc_iversion(inode);
5446 if (ext4_should_order_data(inode)) {
5447 error = ext4_begin_ordered_truncate(inode,
5453 * Blocks are going to be removed from the inode. Wait
5454 * for dio in flight.
5456 inode_dio_wait(inode);
5459 filemap_invalidate_lock(inode->i_mapping);
5461 rc = ext4_break_layouts(inode);
5463 filemap_invalidate_unlock(inode->i_mapping);
5467 if (attr->ia_size != inode->i_size) {
5468 handle = ext4_journal_start(inode, EXT4_HT_INODE, 3);
5469 if (IS_ERR(handle)) {
5470 error = PTR_ERR(handle);
5473 if (ext4_handle_valid(handle) && shrink) {
5474 error = ext4_orphan_add(handle, inode);
5478 * Update c/mtime on truncate up, ext4_truncate() will
5479 * update c/mtime in shrink case below
5482 inode->i_mtime = current_time(inode);
5483 inode->i_ctime = inode->i_mtime;
5487 ext4_fc_track_range(handle, inode,
5488 (attr->ia_size > 0 ? attr->ia_size - 1 : 0) >>
5489 inode->i_sb->s_blocksize_bits,
5490 EXT_MAX_BLOCKS - 1);
5492 ext4_fc_track_range(
5494 (oldsize > 0 ? oldsize - 1 : oldsize) >>
5495 inode->i_sb->s_blocksize_bits,
5496 (attr->ia_size > 0 ? attr->ia_size - 1 : 0) >>
5497 inode->i_sb->s_blocksize_bits);
5499 down_write(&EXT4_I(inode)->i_data_sem);
5500 old_disksize = EXT4_I(inode)->i_disksize;
5501 EXT4_I(inode)->i_disksize = attr->ia_size;
5502 rc = ext4_mark_inode_dirty(handle, inode);
5506 * We have to update i_size under i_data_sem together
5507 * with i_disksize to avoid races with writeback code
5508 * running ext4_wb_update_i_disksize().
5511 i_size_write(inode, attr->ia_size);
5513 EXT4_I(inode)->i_disksize = old_disksize;
5514 up_write(&EXT4_I(inode)->i_data_sem);
5515 ext4_journal_stop(handle);
5519 pagecache_isize_extended(inode, oldsize,
5521 } else if (ext4_should_journal_data(inode)) {
5522 ext4_wait_for_tail_page_commit(inode);
5527 * Truncate pagecache after we've waited for commit
5528 * in data=journal mode to make pages freeable.
5530 truncate_pagecache(inode, inode->i_size);
5532 * Call ext4_truncate() even if i_size didn't change to
5533 * truncate possible preallocated blocks.
5535 if (attr->ia_size <= oldsize) {
5536 rc = ext4_truncate(inode);
5541 filemap_invalidate_unlock(inode->i_mapping);
5545 setattr_copy(mnt_userns, inode, attr);
5546 mark_inode_dirty(inode);
5550 * If the call to ext4_truncate failed to get a transaction handle at
5551 * all, we need to clean up the in-core orphan list manually.
5553 if (orphan && inode->i_nlink)
5554 ext4_orphan_del(NULL, inode);
5556 if (!error && (ia_valid & ATTR_MODE))
5557 rc = posix_acl_chmod(mnt_userns, inode, inode->i_mode);
5561 ext4_std_error(inode->i_sb, error);
5567 int ext4_getattr(struct user_namespace *mnt_userns, const struct path *path,
5568 struct kstat *stat, u32 request_mask, unsigned int query_flags)
5570 struct inode *inode = d_inode(path->dentry);
5571 struct ext4_inode *raw_inode;
5572 struct ext4_inode_info *ei = EXT4_I(inode);
5575 if ((request_mask & STATX_BTIME) &&
5576 EXT4_FITS_IN_INODE(raw_inode, ei, i_crtime)) {
5577 stat->result_mask |= STATX_BTIME;
5578 stat->btime.tv_sec = ei->i_crtime.tv_sec;
5579 stat->btime.tv_nsec = ei->i_crtime.tv_nsec;
5582 flags = ei->i_flags & EXT4_FL_USER_VISIBLE;
5583 if (flags & EXT4_APPEND_FL)
5584 stat->attributes |= STATX_ATTR_APPEND;
5585 if (flags & EXT4_COMPR_FL)
5586 stat->attributes |= STATX_ATTR_COMPRESSED;
5587 if (flags & EXT4_ENCRYPT_FL)
5588 stat->attributes |= STATX_ATTR_ENCRYPTED;
5589 if (flags & EXT4_IMMUTABLE_FL)
5590 stat->attributes |= STATX_ATTR_IMMUTABLE;
5591 if (flags & EXT4_NODUMP_FL)
5592 stat->attributes |= STATX_ATTR_NODUMP;
5593 if (flags & EXT4_VERITY_FL)
5594 stat->attributes |= STATX_ATTR_VERITY;
5596 stat->attributes_mask |= (STATX_ATTR_APPEND |
5597 STATX_ATTR_COMPRESSED |
5598 STATX_ATTR_ENCRYPTED |
5599 STATX_ATTR_IMMUTABLE |
5603 generic_fillattr(mnt_userns, inode, stat);
5607 int ext4_file_getattr(struct user_namespace *mnt_userns,
5608 const struct path *path, struct kstat *stat,
5609 u32 request_mask, unsigned int query_flags)
5611 struct inode *inode = d_inode(path->dentry);
5612 u64 delalloc_blocks;
5614 ext4_getattr(mnt_userns, path, stat, request_mask, query_flags);
5617 * If there is inline data in the inode, the inode will normally not
5618 * have data blocks allocated (it may have an external xattr block).
5619 * Report at least one sector for such files, so tools like tar, rsync,
5620 * others don't incorrectly think the file is completely sparse.
5622 if (unlikely(ext4_has_inline_data(inode)))
5623 stat->blocks += (stat->size + 511) >> 9;
5626 * We can't update i_blocks if the block allocation is delayed
5627 * otherwise in the case of system crash before the real block
5628 * allocation is done, we will have i_blocks inconsistent with
5629 * on-disk file blocks.
5630 * We always keep i_blocks updated together with real
5631 * allocation. But to not confuse with user, stat
5632 * will return the blocks that include the delayed allocation
5633 * blocks for this file.
5635 delalloc_blocks = EXT4_C2B(EXT4_SB(inode->i_sb),
5636 EXT4_I(inode)->i_reserved_data_blocks);
5637 stat->blocks += delalloc_blocks << (inode->i_sb->s_blocksize_bits - 9);
5641 static int ext4_index_trans_blocks(struct inode *inode, int lblocks,
5644 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
5645 return ext4_ind_trans_blocks(inode, lblocks);
5646 return ext4_ext_index_trans_blocks(inode, pextents);
5650 * Account for index blocks, block groups bitmaps and block group
5651 * descriptor blocks if modify datablocks and index blocks
5652 * worse case, the indexs blocks spread over different block groups
5654 * If datablocks are discontiguous, they are possible to spread over
5655 * different block groups too. If they are contiguous, with flexbg,
5656 * they could still across block group boundary.
5658 * Also account for superblock, inode, quota and xattr blocks
5660 static int ext4_meta_trans_blocks(struct inode *inode, int lblocks,
5663 ext4_group_t groups, ngroups = ext4_get_groups_count(inode->i_sb);
5669 * How many index blocks need to touch to map @lblocks logical blocks
5670 * to @pextents physical extents?
5672 idxblocks = ext4_index_trans_blocks(inode, lblocks, pextents);
5677 * Now let's see how many group bitmaps and group descriptors need
5680 groups = idxblocks + pextents;
5682 if (groups > ngroups)
5684 if (groups > EXT4_SB(inode->i_sb)->s_gdb_count)
5685 gdpblocks = EXT4_SB(inode->i_sb)->s_gdb_count;
5687 /* bitmaps and block group descriptor blocks */
5688 ret += groups + gdpblocks;
5690 /* Blocks for super block, inode, quota and xattr blocks */
5691 ret += EXT4_META_TRANS_BLOCKS(inode->i_sb);
5697 * Calculate the total number of credits to reserve to fit
5698 * the modification of a single pages into a single transaction,
5699 * which may include multiple chunks of block allocations.
5701 * This could be called via ext4_write_begin()
5703 * We need to consider the worse case, when
5704 * one new block per extent.
5706 int ext4_writepage_trans_blocks(struct inode *inode)
5708 int bpp = ext4_journal_blocks_per_page(inode);
5711 ret = ext4_meta_trans_blocks(inode, bpp, bpp);
5713 /* Account for data blocks for journalled mode */
5714 if (ext4_should_journal_data(inode))
5720 * Calculate the journal credits for a chunk of data modification.
5722 * This is called from DIO, fallocate or whoever calling
5723 * ext4_map_blocks() to map/allocate a chunk of contiguous disk blocks.
5725 * journal buffers for data blocks are not included here, as DIO
5726 * and fallocate do no need to journal data buffers.
5728 int ext4_chunk_trans_blocks(struct inode *inode, int nrblocks)
5730 return ext4_meta_trans_blocks(inode, nrblocks, 1);
5734 * The caller must have previously called ext4_reserve_inode_write().
5735 * Give this, we know that the caller already has write access to iloc->bh.
5737 int ext4_mark_iloc_dirty(handle_t *handle,
5738 struct inode *inode, struct ext4_iloc *iloc)
5742 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb)))) {
5746 ext4_fc_track_inode(handle, inode);
5749 * ea_inodes are using i_version for storing reference count, don't
5752 if (IS_I_VERSION(inode) &&
5753 !(EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL))
5754 inode_inc_iversion(inode);
5756 /* the do_update_inode consumes one bh->b_count */
5759 /* ext4_do_update_inode() does jbd2_journal_dirty_metadata */
5760 err = ext4_do_update_inode(handle, inode, iloc);
5766 * On success, We end up with an outstanding reference count against
5767 * iloc->bh. This _must_ be cleaned up later.
5771 ext4_reserve_inode_write(handle_t *handle, struct inode *inode,
5772 struct ext4_iloc *iloc)
5776 if (unlikely(ext4_forced_shutdown(EXT4_SB(inode->i_sb))))
5779 err = ext4_get_inode_loc(inode, iloc);
5781 BUFFER_TRACE(iloc->bh, "get_write_access");
5782 err = ext4_journal_get_write_access(handle, inode->i_sb,
5783 iloc->bh, EXT4_JTR_NONE);
5789 ext4_std_error(inode->i_sb, err);
5793 static int __ext4_expand_extra_isize(struct inode *inode,
5794 unsigned int new_extra_isize,
5795 struct ext4_iloc *iloc,
5796 handle_t *handle, int *no_expand)
5798 struct ext4_inode *raw_inode;
5799 struct ext4_xattr_ibody_header *header;
5800 unsigned int inode_size = EXT4_INODE_SIZE(inode->i_sb);
5801 struct ext4_inode_info *ei = EXT4_I(inode);
5804 /* this was checked at iget time, but double check for good measure */
5805 if ((EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize > inode_size) ||
5806 (ei->i_extra_isize & 3)) {
5807 EXT4_ERROR_INODE(inode, "bad extra_isize %u (inode size %u)",
5809 EXT4_INODE_SIZE(inode->i_sb));
5810 return -EFSCORRUPTED;
5812 if ((new_extra_isize < ei->i_extra_isize) ||
5813 (new_extra_isize < 4) ||
5814 (new_extra_isize > inode_size - EXT4_GOOD_OLD_INODE_SIZE))
5815 return -EINVAL; /* Should never happen */
5817 raw_inode = ext4_raw_inode(iloc);
5819 header = IHDR(inode, raw_inode);
5821 /* No extended attributes present */
5822 if (!ext4_test_inode_state(inode, EXT4_STATE_XATTR) ||
5823 header->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC)) {
5824 memset((void *)raw_inode + EXT4_GOOD_OLD_INODE_SIZE +
5825 EXT4_I(inode)->i_extra_isize, 0,
5826 new_extra_isize - EXT4_I(inode)->i_extra_isize);
5827 EXT4_I(inode)->i_extra_isize = new_extra_isize;
5832 * We may need to allocate external xattr block so we need quotas
5833 * initialized. Here we can be called with various locks held so we
5834 * cannot affort to initialize quotas ourselves. So just bail.
5836 if (dquot_initialize_needed(inode))
5839 /* try to expand with EAs present */
5840 error = ext4_expand_extra_isize_ea(inode, new_extra_isize,
5844 * Inode size expansion failed; don't try again
5853 * Expand an inode by new_extra_isize bytes.
5854 * Returns 0 on success or negative error number on failure.
5856 static int ext4_try_to_expand_extra_isize(struct inode *inode,
5857 unsigned int new_extra_isize,
5858 struct ext4_iloc iloc,
5864 if (ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND))
5868 * In nojournal mode, we can immediately attempt to expand
5869 * the inode. When journaled, we first need to obtain extra
5870 * buffer credits since we may write into the EA block
5871 * with this same handle. If journal_extend fails, then it will
5872 * only result in a minor loss of functionality for that inode.
5873 * If this is felt to be critical, then e2fsck should be run to
5874 * force a large enough s_min_extra_isize.
5876 if (ext4_journal_extend(handle,
5877 EXT4_DATA_TRANS_BLOCKS(inode->i_sb), 0) != 0)
5880 if (ext4_write_trylock_xattr(inode, &no_expand) == 0)
5883 error = __ext4_expand_extra_isize(inode, new_extra_isize, &iloc,
5884 handle, &no_expand);
5885 ext4_write_unlock_xattr(inode, &no_expand);
5890 int ext4_expand_extra_isize(struct inode *inode,
5891 unsigned int new_extra_isize,
5892 struct ext4_iloc *iloc)
5898 if (ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND)) {
5903 handle = ext4_journal_start(inode, EXT4_HT_INODE,
5904 EXT4_DATA_TRANS_BLOCKS(inode->i_sb));
5905 if (IS_ERR(handle)) {
5906 error = PTR_ERR(handle);
5911 ext4_write_lock_xattr(inode, &no_expand);
5913 BUFFER_TRACE(iloc->bh, "get_write_access");
5914 error = ext4_journal_get_write_access(handle, inode->i_sb, iloc->bh,
5921 error = __ext4_expand_extra_isize(inode, new_extra_isize, iloc,
5922 handle, &no_expand);
5924 rc = ext4_mark_iloc_dirty(handle, inode, iloc);
5929 ext4_write_unlock_xattr(inode, &no_expand);
5930 ext4_journal_stop(handle);
5935 * What we do here is to mark the in-core inode as clean with respect to inode
5936 * dirtiness (it may still be data-dirty).
5937 * This means that the in-core inode may be reaped by prune_icache
5938 * without having to perform any I/O. This is a very good thing,
5939 * because *any* task may call prune_icache - even ones which
5940 * have a transaction open against a different journal.
5942 * Is this cheating? Not really. Sure, we haven't written the
5943 * inode out, but prune_icache isn't a user-visible syncing function.
5944 * Whenever the user wants stuff synced (sys_sync, sys_msync, sys_fsync)
5945 * we start and wait on commits.
5947 int __ext4_mark_inode_dirty(handle_t *handle, struct inode *inode,
5948 const char *func, unsigned int line)
5950 struct ext4_iloc iloc;
5951 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
5955 trace_ext4_mark_inode_dirty(inode, _RET_IP_);
5956 err = ext4_reserve_inode_write(handle, inode, &iloc);
5960 if (EXT4_I(inode)->i_extra_isize < sbi->s_want_extra_isize)
5961 ext4_try_to_expand_extra_isize(inode, sbi->s_want_extra_isize,
5964 err = ext4_mark_iloc_dirty(handle, inode, &iloc);
5967 ext4_error_inode_err(inode, func, line, 0, err,
5968 "mark_inode_dirty error");
5973 * ext4_dirty_inode() is called from __mark_inode_dirty()
5975 * We're really interested in the case where a file is being extended.
5976 * i_size has been changed by generic_commit_write() and we thus need
5977 * to include the updated inode in the current transaction.
5979 * Also, dquot_alloc_block() will always dirty the inode when blocks
5980 * are allocated to the file.
5982 * If the inode is marked synchronous, we don't honour that here - doing
5983 * so would cause a commit on atime updates, which we don't bother doing.
5984 * We handle synchronous inodes at the highest possible level.
5986 void ext4_dirty_inode(struct inode *inode, int flags)
5990 handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
5993 ext4_mark_inode_dirty(handle, inode);
5994 ext4_journal_stop(handle);
5997 int ext4_change_inode_journal_flag(struct inode *inode, int val)
6002 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
6005 * We have to be very careful here: changing a data block's
6006 * journaling status dynamically is dangerous. If we write a
6007 * data block to the journal, change the status and then delete
6008 * that block, we risk forgetting to revoke the old log record
6009 * from the journal and so a subsequent replay can corrupt data.
6010 * So, first we make sure that the journal is empty and that
6011 * nobody is changing anything.
6014 journal = EXT4_JOURNAL(inode);
6017 if (is_journal_aborted(journal))
6020 /* Wait for all existing dio workers */
6021 inode_dio_wait(inode);
6024 * Before flushing the journal and switching inode's aops, we have
6025 * to flush all dirty data the inode has. There can be outstanding
6026 * delayed allocations, there can be unwritten extents created by
6027 * fallocate or buffered writes in dioread_nolock mode covered by
6028 * dirty data which can be converted only after flushing the dirty
6029 * data (and journalled aops don't know how to handle these cases).
6032 filemap_invalidate_lock(inode->i_mapping);
6033 err = filemap_write_and_wait(inode->i_mapping);
6035 filemap_invalidate_unlock(inode->i_mapping);
6040 percpu_down_write(&sbi->s_writepages_rwsem);
6041 jbd2_journal_lock_updates(journal);
6044 * OK, there are no updates running now, and all cached data is
6045 * synced to disk. We are now in a completely consistent state
6046 * which doesn't have anything in the journal, and we know that
6047 * no filesystem updates are running, so it is safe to modify
6048 * the inode's in-core data-journaling state flag now.
6052 ext4_set_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
6054 err = jbd2_journal_flush(journal, 0);
6056 jbd2_journal_unlock_updates(journal);
6057 percpu_up_write(&sbi->s_writepages_rwsem);
6060 ext4_clear_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
6062 ext4_set_aops(inode);
6064 jbd2_journal_unlock_updates(journal);
6065 percpu_up_write(&sbi->s_writepages_rwsem);
6068 filemap_invalidate_unlock(inode->i_mapping);
6070 /* Finally we can mark the inode as dirty. */
6072 handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
6074 return PTR_ERR(handle);
6076 ext4_fc_mark_ineligible(inode->i_sb,
6077 EXT4_FC_REASON_JOURNAL_FLAG_CHANGE, handle);
6078 err = ext4_mark_inode_dirty(handle, inode);
6079 ext4_handle_sync(handle);
6080 ext4_journal_stop(handle);
6081 ext4_std_error(inode->i_sb, err);
6086 static int ext4_bh_unmapped(handle_t *handle, struct inode *inode,
6087 struct buffer_head *bh)
6089 return !buffer_mapped(bh);
6092 vm_fault_t ext4_page_mkwrite(struct vm_fault *vmf)
6094 struct vm_area_struct *vma = vmf->vma;
6095 struct page *page = vmf->page;
6100 struct file *file = vma->vm_file;
6101 struct inode *inode = file_inode(file);
6102 struct address_space *mapping = inode->i_mapping;
6104 get_block_t *get_block;
6107 if (unlikely(IS_IMMUTABLE(inode)))
6108 return VM_FAULT_SIGBUS;
6110 sb_start_pagefault(inode->i_sb);
6111 file_update_time(vma->vm_file);
6113 filemap_invalidate_lock_shared(mapping);
6115 err = ext4_convert_inline_data(inode);
6120 * On data journalling we skip straight to the transaction handle:
6121 * there's no delalloc; page truncated will be checked later; the
6122 * early return w/ all buffers mapped (calculates size/len) can't
6123 * be used; and there's no dioread_nolock, so only ext4_get_block.
6125 if (ext4_should_journal_data(inode))
6128 /* Delalloc case is easy... */
6129 if (test_opt(inode->i_sb, DELALLOC) &&
6130 !ext4_nonda_switch(inode->i_sb)) {
6132 err = block_page_mkwrite(vma, vmf,
6133 ext4_da_get_block_prep);
6134 } while (err == -ENOSPC &&
6135 ext4_should_retry_alloc(inode->i_sb, &retries));
6140 size = i_size_read(inode);
6141 /* Page got truncated from under us? */
6142 if (page->mapping != mapping || page_offset(page) > size) {
6144 ret = VM_FAULT_NOPAGE;
6148 if (page->index == size >> PAGE_SHIFT)
6149 len = size & ~PAGE_MASK;
6153 * Return if we have all the buffers mapped. This avoids the need to do
6154 * journal_start/journal_stop which can block and take a long time
6156 * This cannot be done for data journalling, as we have to add the
6157 * inode to the transaction's list to writeprotect pages on commit.
6159 if (page_has_buffers(page)) {
6160 if (!ext4_walk_page_buffers(NULL, inode, page_buffers(page),
6162 ext4_bh_unmapped)) {
6163 /* Wait so that we don't change page under IO */
6164 wait_for_stable_page(page);
6165 ret = VM_FAULT_LOCKED;
6170 /* OK, we need to fill the hole... */
6171 if (ext4_should_dioread_nolock(inode))
6172 get_block = ext4_get_block_unwritten;
6174 get_block = ext4_get_block;
6176 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
6177 ext4_writepage_trans_blocks(inode));
6178 if (IS_ERR(handle)) {
6179 ret = VM_FAULT_SIGBUS;
6183 * Data journalling can't use block_page_mkwrite() because it
6184 * will set_buffer_dirty() before do_journal_get_write_access()
6185 * thus might hit warning messages for dirty metadata buffers.
6187 if (!ext4_should_journal_data(inode)) {
6188 err = block_page_mkwrite(vma, vmf, get_block);
6191 size = i_size_read(inode);
6192 /* Page got truncated from under us? */
6193 if (page->mapping != mapping || page_offset(page) > size) {
6194 ret = VM_FAULT_NOPAGE;
6198 if (page->index == size >> PAGE_SHIFT)
6199 len = size & ~PAGE_MASK;
6203 err = __block_write_begin(page, 0, len, ext4_get_block);
6205 ret = VM_FAULT_SIGBUS;
6206 if (ext4_walk_page_buffers(handle, inode,
6207 page_buffers(page), 0, len, NULL,
6208 do_journal_get_write_access))
6210 if (ext4_walk_page_buffers(handle, inode,
6211 page_buffers(page), 0, len, NULL,
6214 if (ext4_jbd2_inode_add_write(handle, inode,
6215 page_offset(page), len))
6217 ext4_set_inode_state(inode, EXT4_STATE_JDATA);
6222 ext4_journal_stop(handle);
6223 if (err == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
6226 ret = block_page_mkwrite_return(err);
6228 filemap_invalidate_unlock_shared(mapping);
6229 sb_end_pagefault(inode->i_sb);
6233 ext4_journal_stop(handle);