1 // SPDX-License-Identifier: GPL-2.0 2 /* 3 * linux/fs/ext4/inode.c 4 * 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) 9 * 10 * from 11 * 12 * linux/fs/minix/inode.c 13 * 14 * Copyright (C) 1991, 1992 Linus Torvalds 15 * 16 * 64-bit file support on 64-bit platforms by Jakub Jelinek 17 * (jj@sunsite.ms.mff.cuni.cz) 18 * 19 * Assorted race fixes, rewrite of ext4_get_block() by Al Viro, 2000 20 */ 21 22 #include <linux/fs.h> 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/folio_batch.h> 33 #include <linux/mpage.h> 34 #include <linux/rmap.h> 35 #include <linux/namei.h> 36 #include <linux/uio.h> 37 #include <linux/bio.h> 38 #include <linux/workqueue.h> 39 #include <linux/kernel.h> 40 #include <linux/printk.h> 41 #include <linux/slab.h> 42 #include <linux/bitops.h> 43 #include <linux/iomap.h> 44 #include <linux/iversion.h> 45 46 #include "ext4_jbd2.h" 47 #include "ext4_extents.h" 48 #include "xattr.h" 49 #include "acl.h" 50 #include "truncate.h" 51 52 #include <kunit/static_stub.h> 53 54 #include <trace/events/ext4.h> 55 56 static void ext4_journalled_zero_new_buffers(handle_t *handle, 57 struct inode *inode, 58 struct folio *folio, 59 unsigned from, unsigned to); 60 static void ext4_wait_for_tail_page_commit(struct inode *inode); 61 62 static __u32 ext4_inode_csum(struct inode *inode, struct ext4_inode *raw, 63 struct ext4_inode_info *ei) 64 { 65 __u32 csum; 66 __u16 dummy_csum = 0; 67 int offset = offsetof(struct ext4_inode, i_checksum_lo); 68 unsigned int csum_size = sizeof(dummy_csum); 69 70 csum = ext4_chksum(ei->i_csum_seed, (__u8 *)raw, offset); 71 csum = ext4_chksum(csum, (__u8 *)&dummy_csum, csum_size); 72 offset += csum_size; 73 csum = ext4_chksum(csum, (__u8 *)raw + offset, 74 EXT4_GOOD_OLD_INODE_SIZE - offset); 75 76 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) { 77 offset = offsetof(struct ext4_inode, i_checksum_hi); 78 csum = ext4_chksum(csum, (__u8 *)raw + EXT4_GOOD_OLD_INODE_SIZE, 79 offset - EXT4_GOOD_OLD_INODE_SIZE); 80 if (EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi)) { 81 csum = ext4_chksum(csum, (__u8 *)&dummy_csum, 82 csum_size); 83 offset += csum_size; 84 } 85 csum = ext4_chksum(csum, (__u8 *)raw + offset, 86 EXT4_INODE_SIZE(inode->i_sb) - offset); 87 } 88 89 return csum; 90 } 91 92 static int ext4_inode_csum_verify(struct inode *inode, struct ext4_inode *raw, 93 struct ext4_inode_info *ei) 94 { 95 __u32 provided, calculated; 96 97 if (EXT4_SB(inode->i_sb)->s_es->s_creator_os != 98 cpu_to_le32(EXT4_OS_LINUX) || 99 !ext4_has_feature_metadata_csum(inode->i_sb)) 100 return 1; 101 102 provided = le16_to_cpu(raw->i_checksum_lo); 103 calculated = ext4_inode_csum(inode, raw, ei); 104 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE && 105 EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi)) 106 provided |= ((__u32)le16_to_cpu(raw->i_checksum_hi)) << 16; 107 else 108 calculated &= 0xFFFF; 109 110 return provided == calculated; 111 } 112 113 void ext4_inode_csum_set(struct inode *inode, struct ext4_inode *raw, 114 struct ext4_inode_info *ei) 115 { 116 __u32 csum; 117 118 if (EXT4_SB(inode->i_sb)->s_es->s_creator_os != 119 cpu_to_le32(EXT4_OS_LINUX) || 120 !ext4_has_feature_metadata_csum(inode->i_sb)) 121 return; 122 123 csum = ext4_inode_csum(inode, raw, ei); 124 raw->i_checksum_lo = cpu_to_le16(csum & 0xFFFF); 125 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE && 126 EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi)) 127 raw->i_checksum_hi = cpu_to_le16(csum >> 16); 128 } 129 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_inode_csum_set); 130 131 /* 132 * Clear the disksize-grow-pending state and wake up all waiters. 133 * Called when the pending zeroed EOF block which straddles i_disksize 134 * has completed writeback or its folio is discarded. 135 */ 136 void ext4_iomap_clear_disksize_pending(struct inode *inode) 137 { 138 if (!test_and_clear_wake_up_bit( 139 ext4_inode_state_wait_bit(EXT4_STATE_DISKSIZE_GROW_PENDING), 140 ext4_inode_state_wait_word(inode))) 141 return; 142 143 trace_ext4_iomap_clear_disksize_pending(inode); 144 } 145 146 /* 147 * Wait for the disksize-grow-pending zeroed EOF block which straddles 148 * i_disksize to be written back or cleared. 149 */ 150 void ext4_iomap_wait_disksize_pending(struct inode *inode) 151 { 152 /* Only emit the trace when the bit is actually set */ 153 if (ext4_test_inode_state(inode, EXT4_STATE_DISKSIZE_GROW_PENDING)) 154 trace_ext4_iomap_wait_disksize_pending(inode); 155 156 wait_on_bit(ext4_inode_state_wait_word(inode), 157 ext4_inode_state_wait_bit(EXT4_STATE_DISKSIZE_GROW_PENDING), 158 TASK_UNINTERRUPTIBLE); 159 } 160 161 /* 162 * Get the range of the disksize-grow-pending zeroed EOF block range 163 * which straddles i_disksize if the EXT4_STATE_DISKSIZE_GROW_PENDING 164 * bit is set. 165 * 166 * Return the pending range, or zero if the BIT has already been cleared. 167 */ 168 unsigned int ext4_iomap_get_disksize_pending_range(struct inode *inode, 169 loff_t *start) 170 { 171 unsigned int blocksize = i_blocksize(inode); 172 loff_t disksize; 173 174 if (!ext4_test_inode_state(inode, EXT4_STATE_DISKSIZE_GROW_PENDING)) 175 return 0; 176 177 /* 178 * The pending bit should be set only when i_disksize is not 179 * block-size aligned. While set, i_disksize must not be advanced, 180 * and the bit must be cleared when i_disksize is shrunk. 181 */ 182 down_read(&EXT4_I(inode)->i_data_sem); 183 disksize = READ_ONCE(EXT4_I(inode)->i_disksize); 184 if (!ext4_test_inode_state(inode, EXT4_STATE_DISKSIZE_GROW_PENDING) || 185 WARN_ON_ONCE(IS_ALIGNED(disksize, blocksize))) { 186 up_read(&EXT4_I(inode)->i_data_sem); 187 return 0; 188 } 189 190 up_read(&EXT4_I(inode)->i_data_sem); 191 *start = disksize; 192 return blocksize - (disksize & (blocksize - 1)); 193 } 194 195 static inline int ext4_begin_ordered_truncate(struct inode *inode, 196 loff_t new_size) 197 { 198 struct jbd2_inode *jinode = READ_ONCE(EXT4_I(inode)->jinode); 199 200 trace_ext4_begin_ordered_truncate(inode, new_size); 201 /* 202 * If jinode is zero, then we never opened the file for 203 * writing, so there's no need to call 204 * jbd2_journal_begin_ordered_truncate() since there's no 205 * outstanding writes we need to flush. 206 */ 207 if (!jinode) 208 return 0; 209 return jbd2_journal_begin_ordered_truncate(EXT4_JOURNAL(inode), 210 jinode, 211 new_size); 212 } 213 214 /* 215 * Test whether an inode is a fast symlink. 216 * A fast symlink has its symlink data stored in ext4_inode_info->i_data. 217 */ 218 int ext4_inode_is_fast_symlink(struct inode *inode) 219 { 220 if (!ext4_has_feature_ea_inode(inode->i_sb)) { 221 int ea_blocks = EXT4_I(inode)->i_file_acl ? 222 EXT4_CLUSTER_SIZE(inode->i_sb) >> 9 : 0; 223 224 if (ext4_has_inline_data(inode)) 225 return 0; 226 227 return (S_ISLNK(inode->i_mode) && inode->i_blocks - ea_blocks == 0); 228 } 229 return S_ISLNK(inode->i_mode) && inode->i_size && 230 (inode->i_size < EXT4_N_BLOCKS * 4); 231 } 232 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_inode_is_fast_symlink); 233 234 /* 235 * Called at the last iput() if i_nlink is zero. 236 */ 237 void ext4_evict_inode(struct inode *inode) 238 { 239 handle_t *handle; 240 int err; 241 /* 242 * Credits for final inode cleanup and freeing: 243 * sb + inode (ext4_orphan_del()), block bitmap, group descriptor 244 * (xattr block freeing), bitmap, group descriptor (inode freeing) 245 */ 246 int extra_credits = 6; 247 bool freeze_protected = false; 248 249 trace_ext4_evict_inode(inode); 250 251 dax_break_layout_final(inode); 252 253 if (EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL) 254 ext4_evict_ea_inode(inode); 255 if (inode->i_nlink) { 256 /* 257 * If there's dirty page will lead to data loss, user 258 * could see stale data. 259 */ 260 if (unlikely(!ext4_emergency_state(inode->i_sb) && 261 mapping_tagged(&inode->i_data, PAGECACHE_TAG_DIRTY))) 262 ext4_warning_inode(inode, "data will be lost"); 263 264 truncate_inode_pages_final(&inode->i_data); 265 goto no_delete; 266 } 267 268 if (is_bad_inode(inode)) 269 goto no_delete; 270 dquot_initialize(inode); 271 272 if (ext4_should_order_data(inode)) 273 ext4_begin_ordered_truncate(inode, 0); 274 if (ext4_inode_buffered_iomap(inode)) 275 ext4_iomap_clear_disksize_pending(inode); 276 truncate_inode_pages_final(&inode->i_data); 277 278 /* 279 * For inodes with journalled data, transaction commit could have 280 * dirtied the inode. And for inodes with dioread_nolock, unwritten 281 * extents converting worker could merge extents and also have dirtied 282 * the inode. Flush worker is ignoring it because of I_FREEING flag but 283 * we still need to remove the inode from the writeback lists. 284 */ 285 inode_io_list_del(inode); 286 287 /* 288 * Protect us against freezing - iput() caller didn't have to have any 289 * protection against it. When we are in a running transaction though, 290 * we are already protected against freezing and we cannot grab further 291 * protection due to lock ordering constraints. 292 */ 293 if (!ext4_journal_current_handle()) { 294 sb_start_intwrite(inode->i_sb); 295 freeze_protected = true; 296 } 297 298 if (!IS_NOQUOTA(inode)) 299 extra_credits += EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb); 300 301 /* 302 * Block bitmap, group descriptor, and inode are accounted in both 303 * ext4_blocks_for_truncate() and extra_credits. So subtract 3. 304 */ 305 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, 306 ext4_blocks_for_truncate(inode) + extra_credits - 3); 307 if (IS_ERR(handle)) { 308 ext4_std_error(inode->i_sb, PTR_ERR(handle)); 309 /* 310 * If we're going to skip the normal cleanup, we still need to 311 * make sure that the in-core orphan linked list is properly 312 * cleaned up. 313 */ 314 ext4_orphan_del(NULL, inode); 315 if (freeze_protected) 316 sb_end_intwrite(inode->i_sb); 317 goto no_delete; 318 } 319 320 if (IS_SYNC(inode)) 321 ext4_handle_sync(handle); 322 323 /* 324 * Set inode->i_size to 0 before calling ext4_truncate(). We need 325 * special handling of symlinks here because i_size is used to 326 * determine whether ext4_inode_info->i_data contains symlink data or 327 * block mappings. Setting i_size to 0 will remove its fast symlink 328 * status. Erase i_data so that it becomes a valid empty block map. 329 */ 330 if (ext4_inode_is_fast_symlink(inode)) 331 memset(EXT4_I(inode)->i_data, 0, sizeof(EXT4_I(inode)->i_data)); 332 inode->i_size = 0; 333 ext4_set_inode_state(inode, EXT4_STATE_NO_EXPAND); 334 err = ext4_mark_inode_dirty(handle, inode); 335 if (err) { 336 ext4_warning(inode->i_sb, 337 "couldn't mark inode dirty (err %d)", err); 338 goto stop_handle; 339 } 340 if (inode->i_blocks) { 341 err = ext4_truncate(inode); 342 if (err) { 343 ext4_error_err(inode->i_sb, -err, 344 "couldn't truncate inode %llu (err %d)", 345 inode->i_ino, err); 346 goto stop_handle; 347 } 348 } 349 350 /* Remove xattr references. */ 351 err = ext4_xattr_delete_inode(handle, inode, extra_credits); 352 if (err) { 353 ext4_warning(inode->i_sb, "xattr delete (err %d)", err); 354 stop_handle: 355 ext4_journal_stop(handle); 356 ext4_orphan_del(NULL, inode); 357 if (freeze_protected) 358 sb_end_intwrite(inode->i_sb); 359 goto no_delete; 360 } 361 362 /* 363 * Kill off the orphan record which ext4_truncate created. 364 * AKPM: I think this can be inside the above `if'. 365 * Note that ext4_orphan_del() has to be able to cope with the 366 * deletion of a non-existent orphan - this is because we don't 367 * know if ext4_truncate() actually created an orphan record. 368 * (Well, we could do this if we need to, but heck - it works) 369 */ 370 ext4_orphan_del(handle, inode); 371 EXT4_I(inode)->i_dtime = (__u32)ktime_get_real_seconds(); 372 373 /* 374 * One subtle ordering requirement: if anything has gone wrong 375 * (transaction abort, IO errors, whatever), then we can still 376 * do these next steps (the fs will already have been marked as 377 * having errors), but we can't free the inode if the mark_dirty 378 * fails. 379 */ 380 if (ext4_mark_inode_dirty(handle, inode)) 381 /* If that failed, just do the required in-core inode clear. */ 382 ext4_clear_inode(inode); 383 else 384 ext4_free_inode(handle, inode); 385 ext4_journal_stop(handle); 386 if (freeze_protected) 387 sb_end_intwrite(inode->i_sb); 388 return; 389 no_delete: 390 /* 391 * Check out some where else accidentally dirty the evicting inode, 392 * which may probably cause inode use-after-free issues later. 393 */ 394 WARN_ON_ONCE(!list_empty_careful(&inode->i_io_list)); 395 396 if (!list_empty(&EXT4_I(inode)->i_fc_list)) 397 ext4_fc_mark_ineligible(inode->i_sb, EXT4_FC_REASON_NOMEM, NULL); 398 ext4_clear_inode(inode); /* We must guarantee clearing of inode... */ 399 } 400 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_evict_inode); 401 402 #ifdef CONFIG_QUOTA 403 qsize_t *ext4_get_reserved_space(struct inode *inode) 404 { 405 return &EXT4_I(inode)->i_reserved_quota; 406 } 407 #endif 408 409 /* 410 * Called with i_data_sem down, which is important since we can call 411 * ext4_discard_preallocations() from here. 412 */ 413 void ext4_da_update_reserve_space(struct inode *inode, 414 int used, int quota_claim) 415 { 416 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb); 417 struct ext4_inode_info *ei = EXT4_I(inode); 418 419 KUNIT_STATIC_STUB_REDIRECT(ext4_da_update_reserve_space, 420 inode, used, quota_claim); 421 422 spin_lock(&ei->i_block_reservation_lock); 423 trace_ext4_da_update_reserve_space(inode, used, quota_claim); 424 if (unlikely(used > ei->i_reserved_data_blocks)) { 425 ext4_warning(inode->i_sb, "%s: ino %llu, used %d " 426 "with only %d reserved data blocks", 427 __func__, inode->i_ino, used, 428 ei->i_reserved_data_blocks); 429 WARN_ON(1); 430 used = ei->i_reserved_data_blocks; 431 } 432 433 /* Update per-inode reservations */ 434 ei->i_reserved_data_blocks -= used; 435 percpu_counter_sub(&sbi->s_dirtyclusters_counter, used); 436 437 spin_unlock(&ei->i_block_reservation_lock); 438 439 /* Update quota subsystem for data blocks */ 440 if (quota_claim) 441 dquot_claim_block(inode, EXT4_C2B(sbi, used)); 442 else { 443 /* 444 * We did fallocate with an offset that is already delayed 445 * allocated. So on delayed allocated writeback we should 446 * not re-claim the quota for fallocated blocks. 447 */ 448 dquot_release_reservation_block(inode, EXT4_C2B(sbi, used)); 449 } 450 451 /* 452 * If we have done all the pending block allocations and if 453 * there aren't any writers on the inode, we can discard the 454 * inode's preallocations. 455 */ 456 if ((ei->i_reserved_data_blocks == 0) && 457 !inode_is_open_for_write(inode)) 458 ext4_discard_preallocations(inode); 459 } 460 461 static int __check_block_validity(struct inode *inode, const char *func, 462 unsigned int line, 463 struct ext4_map_blocks *map) 464 { 465 journal_t *journal = EXT4_SB(inode->i_sb)->s_journal; 466 467 if (journal && inode == journal->j_inode) 468 return 0; 469 470 if (!ext4_inode_block_valid(inode, map->m_pblk, map->m_len)) { 471 ext4_error_inode(inode, func, line, map->m_pblk, 472 "lblock %lu mapped to illegal pblock %llu " 473 "(length %d)", (unsigned long) map->m_lblk, 474 map->m_pblk, map->m_len); 475 return -EFSCORRUPTED; 476 } 477 return 0; 478 } 479 480 /* 481 * The zeroes written here are file data. With a @handle the range is tracked 482 * for fast commit, because some callers zero out blocks outside the range that 483 * ext4_map_blocks() tracks and convert them to written. A caller without a 484 * handle must make sure that the conversion tracks the range. 485 */ 486 int ext4_issue_zeroout(handle_t *handle, struct inode *inode, ext4_lblk_t lblk, 487 ext4_fsblk_t pblk, ext4_lblk_t len) 488 { 489 int ret; 490 491 KUNIT_STATIC_STUB_REDIRECT(ext4_issue_zeroout, handle, inode, lblk, pblk, 492 len); 493 494 if (IS_ENCRYPTED(inode) && S_ISREG(inode->i_mode)) 495 ret = fscrypt_zeroout_range(inode, 496 (loff_t)lblk << inode->i_blkbits, 497 pblk << (inode->i_blkbits - SECTOR_SHIFT), 498 (u64)len << inode->i_blkbits); 499 else 500 ret = sb_issue_zeroout(inode->i_sb, pblk, len, GFP_NOFS); 501 if (ret > 0) 502 ret = 0; 503 504 if (!ret && handle) 505 ext4_fc_track_range(handle, inode, lblk, lblk + len - 1); 506 return ret; 507 } 508 509 /* 510 * For generic regular files, when updating the extent tree, Ext4 should 511 * hold the i_rwsem and invalidate_lock exclusively. This ensures 512 * exclusion against concurrent page faults, as well as reads and writes. 513 */ 514 #ifdef CONFIG_EXT4_DEBUG 515 void ext4_check_map_extents_env(struct inode *inode) 516 { 517 if (EXT4_SB(inode->i_sb)->s_mount_state & EXT4_FC_REPLAY) 518 return; 519 520 if (!S_ISREG(inode->i_mode) || 521 IS_NOQUOTA(inode) || IS_VERITY(inode) || 522 is_special_ino(inode->i_sb, inode->i_ino) || 523 (inode_state_read_once(inode) & (I_FREEING | I_WILL_FREE | I_NEW)) || 524 ext4_test_inode_flag(inode, EXT4_INODE_EA_INODE) || 525 ext4_verity_in_progress(inode)) 526 return; 527 528 WARN_ON_ONCE(!inode_is_locked(inode) && 529 !rwsem_is_locked(&inode->i_mapping->invalidate_lock)); 530 } 531 #else 532 void ext4_check_map_extents_env(struct inode *inode) {} 533 #endif 534 535 #define check_block_validity(inode, map) \ 536 __check_block_validity((inode), __func__, __LINE__, (map)) 537 538 #ifdef ES_AGGRESSIVE_TEST 539 static void ext4_map_blocks_es_recheck(handle_t *handle, 540 struct inode *inode, 541 struct ext4_map_blocks *es_map, 542 struct ext4_map_blocks *map, 543 int flags) 544 { 545 int retval; 546 547 map->m_flags = 0; 548 /* 549 * There is a race window that the result is not the same. 550 * e.g. xfstests #223 when dioread_nolock enables. The reason 551 * is that we lookup a block mapping in extent status tree with 552 * out taking i_data_sem. So at the time the unwritten extent 553 * could be converted. 554 */ 555 down_read(&EXT4_I(inode)->i_data_sem); 556 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) { 557 retval = ext4_ext_map_blocks(handle, inode, map, 0); 558 } else { 559 retval = ext4_ind_map_blocks(handle, inode, map, 0); 560 } 561 up_read((&EXT4_I(inode)->i_data_sem)); 562 563 /* 564 * We don't check m_len because extent will be collpased in status 565 * tree. So the m_len might not equal. 566 */ 567 if (es_map->m_lblk != map->m_lblk || 568 es_map->m_flags != map->m_flags || 569 es_map->m_pblk != map->m_pblk) { 570 printk("ES cache assertion failed for inode: %llu " 571 "es_cached ex [%d/%d/%llu/%x] != " 572 "found ex [%d/%d/%llu/%x] retval %d flags %x\n", 573 inode->i_ino, es_map->m_lblk, es_map->m_len, 574 es_map->m_pblk, es_map->m_flags, map->m_lblk, 575 map->m_len, map->m_pblk, map->m_flags, 576 retval, flags); 577 } 578 } 579 #endif /* ES_AGGRESSIVE_TEST */ 580 581 static int ext4_map_query_blocks_next_in_leaf(handle_t *handle, 582 struct inode *inode, struct ext4_map_blocks *map, 583 unsigned int orig_mlen) 584 { 585 struct ext4_map_blocks map2; 586 unsigned int status, status2; 587 int retval; 588 589 status = map->m_flags & EXT4_MAP_UNWRITTEN ? 590 EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN; 591 592 WARN_ON_ONCE(!(map->m_flags & EXT4_MAP_QUERY_LAST_IN_LEAF)); 593 WARN_ON_ONCE(orig_mlen <= map->m_len); 594 595 /* Prepare map2 for lookup in next leaf block */ 596 map2.m_lblk = map->m_lblk + map->m_len; 597 map2.m_len = orig_mlen - map->m_len; 598 map2.m_flags = 0; 599 retval = ext4_ext_map_blocks(handle, inode, &map2, 0); 600 601 if (retval <= 0) { 602 ext4_es_cache_extent(inode, map->m_lblk, map->m_len, 603 map->m_pblk, status); 604 return map->m_len; 605 } 606 607 if (unlikely(retval != map2.m_len)) { 608 ext4_warning(inode->i_sb, 609 "ES len assertion failed for inode " 610 "%llu: retval %d != map->m_len %d", 611 inode->i_ino, retval, map2.m_len); 612 WARN_ON(1); 613 } 614 615 status2 = map2.m_flags & EXT4_MAP_UNWRITTEN ? 616 EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN; 617 618 /* 619 * If map2 is contiguous with map, then let's insert it as a single 620 * extent in es cache and return the combined length of both the maps. 621 */ 622 if (map->m_pblk + map->m_len == map2.m_pblk && 623 status == status2) { 624 ext4_es_cache_extent(inode, map->m_lblk, 625 map->m_len + map2.m_len, map->m_pblk, 626 status); 627 map->m_len += map2.m_len; 628 } else { 629 ext4_es_cache_extent(inode, map->m_lblk, map->m_len, 630 map->m_pblk, status); 631 } 632 633 return map->m_len; 634 } 635 636 int ext4_map_query_blocks(handle_t *handle, struct inode *inode, 637 struct ext4_map_blocks *map, int flags) 638 { 639 unsigned int status; 640 int retval; 641 unsigned int orig_mlen = map->m_len; 642 643 flags &= EXT4_EX_QUERY_FILTER; 644 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) 645 retval = ext4_ext_map_blocks(handle, inode, map, flags); 646 else 647 retval = ext4_ind_map_blocks(handle, inode, map, flags); 648 if (retval < 0) 649 return retval; 650 651 /* A hole? */ 652 if (retval == 0) 653 goto out; 654 655 if (unlikely(retval != map->m_len)) { 656 ext4_warning(inode->i_sb, 657 "ES len assertion failed for inode " 658 "%llu: retval %d != map->m_len %d", 659 inode->i_ino, retval, map->m_len); 660 WARN_ON(1); 661 } 662 663 /* 664 * No need to query next in leaf: 665 * - if returned extent is not last in leaf or 666 * - if the last in leaf is the full requested range 667 */ 668 if (!(map->m_flags & EXT4_MAP_QUERY_LAST_IN_LEAF) || 669 map->m_len == orig_mlen) { 670 status = map->m_flags & EXT4_MAP_UNWRITTEN ? 671 EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN; 672 ext4_es_cache_extent(inode, map->m_lblk, map->m_len, 673 map->m_pblk, status); 674 } else { 675 retval = ext4_map_query_blocks_next_in_leaf(handle, inode, map, 676 orig_mlen); 677 } 678 out: 679 map->m_seq = READ_ONCE(EXT4_I(inode)->i_es_seq); 680 return retval; 681 } 682 683 int ext4_map_create_blocks(handle_t *handle, struct inode *inode, 684 struct ext4_map_blocks *map, int flags) 685 { 686 unsigned int status; 687 int err, retval = 0; 688 689 /* 690 * We pass in the magic EXT4_GET_BLOCKS_DELALLOC_RESERVE 691 * indicates that the blocks and quotas has already been 692 * checked when the data was copied into the page cache. 693 */ 694 if (map->m_flags & EXT4_MAP_DELAYED) 695 flags |= EXT4_GET_BLOCKS_DELALLOC_RESERVE; 696 697 /* 698 * Here we clear m_flags because after allocating an new extent, 699 * it will be set again. 700 */ 701 map->m_flags &= ~EXT4_MAP_FLAGS; 702 703 /* 704 * We need to check for EXT4 here because migrate could have 705 * changed the inode type in between. 706 */ 707 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) { 708 retval = ext4_ext_map_blocks(handle, inode, map, flags); 709 } else { 710 retval = ext4_ind_map_blocks(handle, inode, map, flags); 711 712 /* 713 * We allocated new blocks which will result in i_data's 714 * format changing. Force the migrate to fail by clearing 715 * migrate flags. 716 */ 717 if (retval > 0 && map->m_flags & EXT4_MAP_NEW) 718 ext4_clear_inode_state(inode, EXT4_STATE_EXT_MIGRATE); 719 } 720 if (retval <= 0) 721 return retval; 722 723 if (unlikely(retval != map->m_len)) { 724 ext4_warning(inode->i_sb, 725 "ES len assertion failed for inode %llu: " 726 "retval %d != map->m_len %d", 727 inode->i_ino, retval, map->m_len); 728 WARN_ON(1); 729 } 730 731 /* 732 * We have to zeroout blocks before inserting them into extent 733 * status tree. Otherwise someone could look them up there and 734 * use them before they are really zeroed. We also have to 735 * unmap metadata before zeroing as otherwise writeback can 736 * overwrite zeros with stale data from block device. 737 */ 738 if (flags & EXT4_GET_BLOCKS_ZERO && 739 map->m_flags & EXT4_MAP_MAPPED && map->m_flags & EXT4_MAP_NEW) { 740 err = ext4_issue_zeroout(handle, inode, map->m_lblk, 741 map->m_pblk, map->m_len); 742 if (err) 743 return err; 744 } 745 746 status = map->m_flags & EXT4_MAP_UNWRITTEN ? 747 EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN; 748 ext4_es_insert_extent(inode, map->m_lblk, map->m_len, map->m_pblk, 749 status, flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE); 750 map->m_seq = READ_ONCE(EXT4_I(inode)->i_es_seq); 751 752 return retval; 753 } 754 755 /* 756 * The ext4_map_blocks() function tries to look up the requested blocks, 757 * and returns if the blocks are already mapped. 758 * 759 * Otherwise it takes the write lock of the i_data_sem and allocate blocks 760 * and store the allocated blocks in the result buffer head and mark it 761 * mapped. 762 * 763 * If file type is extents based, it will call ext4_ext_map_blocks(), 764 * Otherwise, call with ext4_ind_map_blocks() to handle indirect mapping 765 * based files 766 * 767 * ext4_map_blocks() may also be called with a NULL @handle. In that case 768 * it starts its own transaction handle only when block allocation is 769 * actually needed, i.e. after the lookup confirms the blocks are not yet 770 * mapped, and stops it before returning. 771 * 772 * On success, it returns the number of blocks being mapped or allocated. 773 * If flags doesn't contain EXT4_GET_BLOCKS_CREATE the blocks are 774 * pre-allocated and unwritten, the resulting @map is marked as unwritten. 775 * If the flags contain EXT4_GET_BLOCKS_CREATE, it will mark @map as mapped. 776 * 777 * It returns 0 if plain look up failed (blocks have not been allocated), in 778 * that case, @map is returned as unmapped but we still do fill map->m_len to 779 * indicate the length of a hole starting at map->m_lblk. 780 * 781 * It returns the error in case of allocation failure. 782 */ 783 int ext4_map_blocks(handle_t *handle, struct inode *inode, 784 struct ext4_map_blocks *map, int flags) 785 { 786 struct extent_status es; 787 int retval; 788 int ret = 0; 789 bool internal_handle = false; 790 unsigned int orig_mlen; 791 #ifdef ES_AGGRESSIVE_TEST 792 struct ext4_map_blocks orig_map; 793 794 memcpy(&orig_map, map, sizeof(*map)); 795 #endif 796 797 KUNIT_STATIC_STUB_REDIRECT(ext4_map_blocks, handle, inode, map, flags); 798 799 map->m_flags = 0; 800 ext_debug(inode, "flag 0x%x, max_blocks %u, logical block %lu\n", 801 flags, map->m_len, (unsigned long) map->m_lblk); 802 803 /* 804 * ext4_map_blocks returns an int, and m_len is an unsigned int 805 */ 806 if (unlikely(map->m_len > INT_MAX)) 807 map->m_len = INT_MAX; 808 orig_mlen = map->m_len; 809 810 /* We can handle the block number less than EXT_MAX_BLOCKS */ 811 if (unlikely(map->m_lblk >= EXT_MAX_BLOCKS)) 812 return -EFSCORRUPTED; 813 814 /* 815 * Callers from the context of data submission are the only exceptions 816 * for regular files that do not hold the i_rwsem or invalidate_lock. 817 * However, caching unrelated ranges is not permitted. 818 */ 819 if (flags & EXT4_GET_BLOCKS_IO_SUBMIT) 820 WARN_ON_ONCE(!(flags & EXT4_EX_NOCACHE)); 821 else 822 ext4_check_map_extents_env(inode); 823 824 create_retry: 825 /* Lookup extent status tree firstly */ 826 if (ext4_es_lookup_extent(inode, map->m_lblk, NULL, &es, &map->m_seq)) { 827 if (ext4_es_is_written(&es) || ext4_es_is_unwritten(&es)) { 828 map->m_pblk = ext4_es_pblock(&es) + 829 map->m_lblk - es.es_lblk; 830 map->m_flags |= ext4_es_is_written(&es) ? 831 EXT4_MAP_MAPPED : EXT4_MAP_UNWRITTEN; 832 retval = es.es_len - (map->m_lblk - es.es_lblk); 833 if (retval > map->m_len) 834 retval = map->m_len; 835 map->m_len = retval; 836 } else if (ext4_es_is_delayed(&es) || ext4_es_is_hole(&es)) { 837 map->m_pblk = 0; 838 map->m_flags |= ext4_es_is_delayed(&es) ? 839 EXT4_MAP_DELAYED : 0; 840 retval = es.es_len - (map->m_lblk - es.es_lblk); 841 if (retval > map->m_len) 842 retval = map->m_len; 843 map->m_len = retval; 844 retval = 0; 845 } else { 846 BUG(); 847 } 848 849 if (flags & EXT4_GET_BLOCKS_CACHED_NOWAIT) 850 return retval; 851 #ifdef ES_AGGRESSIVE_TEST 852 ext4_map_blocks_es_recheck(handle, inode, map, 853 &orig_map, flags); 854 #endif 855 if (!(flags & EXT4_GET_BLOCKS_QUERY_LAST_IN_LEAF) || 856 orig_mlen == map->m_len) 857 goto found; 858 859 map->m_len = orig_mlen; 860 } 861 /* 862 * In the query cache no-wait mode, nothing we can do more if we 863 * cannot find extent in the cache. 864 */ 865 if (flags & EXT4_GET_BLOCKS_CACHED_NOWAIT) 866 return 0; 867 868 /* 869 * Try to see if we can get the block without requesting a new 870 * file system block. 871 */ 872 down_read(&EXT4_I(inode)->i_data_sem); 873 retval = ext4_map_query_blocks(handle, inode, map, flags); 874 up_read((&EXT4_I(inode)->i_data_sem)); 875 if (retval < 0) 876 goto out; 877 878 found: 879 if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) { 880 ret = check_block_validity(inode, map); 881 if (ret != 0) 882 goto out; 883 } 884 885 /* If it is only a block(s) look up */ 886 if ((flags & EXT4_GET_BLOCKS_CREATE) == 0) 887 return retval; 888 889 /* 890 * Returns if the blocks have already allocated 891 * 892 * Note that if blocks have been preallocated 893 * ext4_ext_map_blocks() returns with buffer head unmapped 894 */ 895 if (retval > 0) { 896 /* 897 * If we need to convert written extent to unwritten or 898 * convert unwritten extent to written, continue and do 899 * the actual work in ext4_ext_map_blocks(). 900 */ 901 if (map->m_flags & EXT4_MAP_MAPPED && 902 !(flags & EXT4_GET_BLOCKS_CONVERT_UNWRITTEN)) 903 goto out; 904 if (map->m_flags & EXT4_MAP_UNWRITTEN && 905 (flags & EXT4_GET_BLOCKS_UNWRIT_EXT) && 906 !(flags & EXT4_GET_BLOCKS_CONVERT)) { 907 /* Contains EXT4_GET_BLOCKS_CREATE - mark mapped. */ 908 ret = check_block_validity(inode, map); 909 if (!ret) 910 map->m_flags |= EXT4_MAP_MAPPED; 911 goto out; 912 } 913 } else if (retval == 0) { 914 /* 915 * Do not allocate blocks for holes in the context of 916 * data submission path. 917 */ 918 if (!map->m_flags && (flags & EXT4_GET_BLOCKS_IO_SUBMIT)) 919 goto out; 920 } 921 922 if (!handle) { 923 handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS, 924 ext4_chunk_trans_blocks(inode, orig_mlen)); 925 if (IS_ERR(handle)) { 926 ret = PTR_ERR(handle); 927 goto out; 928 } 929 internal_handle = true; 930 } 931 932 ext4_fc_track_inode(handle, inode); 933 /* 934 * New blocks allocate and/or writing to unwritten extent 935 * will possibly result in updating i_data, so we take 936 * the write lock of i_data_sem, and call get_block() 937 * with create == 1 flag. 938 */ 939 down_write(&EXT4_I(inode)->i_data_sem); 940 941 /* 942 * Check the validity of the mapping found via the extent status 943 * tree or the disk query. A racing truncate may have changed the 944 * extent, since writeback may not hold i_rwsem or the folio locks 945 * covering the full extent(e.g., the iomap writeback path may 946 * allocate an extent that extends beyond the length of the locked 947 * folio in advance). 948 */ 949 if (map->m_seq != READ_ONCE(EXT4_I(inode)->i_es_seq)) { 950 up_write(&EXT4_I(inode)->i_data_sem); 951 map->m_flags = 0; 952 map->m_len = orig_mlen; 953 goto create_retry; 954 } 955 retval = ext4_map_create_blocks(handle, inode, map, flags); 956 up_write((&EXT4_I(inode)->i_data_sem)); 957 958 if (retval < 0) 959 ext_debug(inode, "failed with err %d\n", retval); 960 if (retval <= 0) 961 goto out; 962 963 if (map->m_flags & EXT4_MAP_MAPPED) { 964 ret = check_block_validity(inode, map); 965 if (ret != 0) 966 goto out; 967 968 /* 969 * Inodes with freshly allocated blocks where contents will be 970 * visible after transaction commit must be on transaction's 971 * ordered data list. 972 */ 973 if (map->m_flags & EXT4_MAP_NEW && 974 !(map->m_flags & EXT4_MAP_UNWRITTEN) && 975 !(flags & EXT4_GET_BLOCKS_ZERO) && 976 !ext4_is_quota_file(inode) && 977 ext4_should_order_data(inode)) { 978 loff_t start_byte = EXT4_LBLK_TO_B(inode, map->m_lblk); 979 loff_t length = EXT4_LBLK_TO_B(inode, map->m_len); 980 981 if (flags & EXT4_GET_BLOCKS_IO_SUBMIT) 982 ret = ext4_jbd2_inode_add_wait(handle, inode, 983 start_byte, length); 984 else 985 ret = ext4_jbd2_inode_add_write(handle, inode, 986 start_byte, length); 987 if (ret) 988 goto out; 989 } 990 } 991 ext4_fc_track_range(handle, inode, map->m_lblk, map->m_lblk + 992 map->m_len - 1); 993 out: 994 if (internal_handle) 995 ext4_journal_stop(handle); 996 997 return ret ? ret : retval; 998 } 999 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_map_blocks); 1000 1001 /* 1002 * Update EXT4_MAP_FLAGS in bh->b_state. For buffer heads attached to pages 1003 * we have to be careful as someone else may be manipulating b_state as well. 1004 */ 1005 static void ext4_update_bh_state(struct buffer_head *bh, unsigned long flags) 1006 { 1007 unsigned long old_state; 1008 unsigned long new_state; 1009 1010 flags &= EXT4_MAP_FLAGS; 1011 1012 /* Dummy buffer_head? Set non-atomically. */ 1013 if (!bh->b_folio) { 1014 bh->b_state = (bh->b_state & ~EXT4_MAP_FLAGS) | flags; 1015 return; 1016 } 1017 /* 1018 * Someone else may be modifying b_state. Be careful! This is ugly but 1019 * once we get rid of using bh as a container for mapping information 1020 * to pass to / from get_block functions, this can go away. 1021 */ 1022 old_state = READ_ONCE(bh->b_state); 1023 do { 1024 new_state = (old_state & ~EXT4_MAP_FLAGS) | flags; 1025 } while (unlikely(!try_cmpxchg(&bh->b_state, &old_state, new_state))); 1026 } 1027 1028 /* 1029 * Make sure that the current journal transaction has enough credits to map 1030 * one extent. Return -EAGAIN if it cannot extend the current running 1031 * transaction. 1032 */ 1033 static inline int ext4_journal_ensure_extent_credits(handle_t *handle, 1034 struct inode *inode) 1035 { 1036 int credits; 1037 int ret; 1038 1039 /* Called from ext4_da_write_begin() which has no handle started? */ 1040 if (!handle) 1041 return 0; 1042 1043 credits = ext4_chunk_trans_blocks(inode, 1); 1044 ret = __ext4_journal_ensure_credits(handle, credits, credits, 0); 1045 return ret <= 0 ? ret : -EAGAIN; 1046 } 1047 1048 static int _ext4_get_block(struct inode *inode, sector_t iblock, 1049 struct buffer_head *bh, int flags) 1050 { 1051 struct ext4_map_blocks map; 1052 int ret = 0; 1053 1054 if (ext4_has_inline_data(inode)) 1055 return -ERANGE; 1056 /* inode using the iomap buffered I/O path should not go here. */ 1057 if (WARN_ON_ONCE(ext4_inode_buffered_iomap(inode))) 1058 return -EINVAL; 1059 1060 map.m_lblk = iblock; 1061 map.m_len = bh->b_size >> inode->i_blkbits; 1062 1063 ret = ext4_map_blocks(ext4_journal_current_handle(), inode, &map, 1064 flags); 1065 if (ret > 0) { 1066 map_bh(bh, inode->i_sb, map.m_pblk); 1067 ext4_update_bh_state(bh, map.m_flags); 1068 bh->b_size = inode->i_sb->s_blocksize * map.m_len; 1069 ret = 0; 1070 } else if (ret == 0) { 1071 /* hole case, need to fill in bh->b_size */ 1072 bh->b_size = inode->i_sb->s_blocksize * map.m_len; 1073 } 1074 return ret; 1075 } 1076 1077 int ext4_get_block(struct inode *inode, sector_t iblock, 1078 struct buffer_head *bh, int create) 1079 { 1080 return _ext4_get_block(inode, iblock, bh, 1081 create ? EXT4_GET_BLOCKS_CREATE : 0); 1082 } 1083 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_get_block); 1084 1085 /* 1086 * Get block function used when preparing for buffered write if we require 1087 * creating an unwritten extent if blocks haven't been allocated. The extent 1088 * will be converted to written after the IO is complete. 1089 */ 1090 int ext4_get_block_unwritten(struct inode *inode, sector_t iblock, 1091 struct buffer_head *bh_result, int create) 1092 { 1093 int ret = 0; 1094 1095 ext4_debug("ext4_get_block_unwritten: inode %llu, create flag %d\n", 1096 inode->i_ino, create); 1097 ret = _ext4_get_block(inode, iblock, bh_result, 1098 EXT4_GET_BLOCKS_CREATE_UNWRIT_EXT); 1099 1100 /* 1101 * If the buffer is marked unwritten, mark it as new to make sure it is 1102 * zeroed out correctly in case of partial writes. Otherwise, there is 1103 * a chance of stale data getting exposed. 1104 */ 1105 if (ret == 0 && buffer_unwritten(bh_result)) 1106 set_buffer_new(bh_result); 1107 1108 return ret; 1109 } 1110 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_get_block_unwritten); 1111 1112 /* Maximum number of blocks we map for direct IO at once. */ 1113 #define DIO_MAX_BLOCKS 4096 1114 1115 struct buffer_head *ext4_sb_getblk(struct super_block *sb, ext4_fsblk_t block) 1116 { 1117 KUNIT_STATIC_STUB_REDIRECT(ext4_sb_getblk, sb, block); 1118 return sb_getblk(sb, block); 1119 } 1120 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_sb_getblk); 1121 1122 struct buffer_head *ext4_sb_find_get_block(struct super_block *sb, 1123 ext4_fsblk_t block) 1124 { 1125 KUNIT_STATIC_STUB_REDIRECT(ext4_sb_find_get_block, sb, block); 1126 return sb_find_get_block(sb, block); 1127 } 1128 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_sb_find_get_block); 1129 1130 struct buffer_head *ext4_sb_find_get_block_nonatomic(struct super_block *sb, 1131 ext4_fsblk_t block) 1132 { 1133 KUNIT_STATIC_STUB_REDIRECT(ext4_sb_find_get_block_nonatomic, sb, block); 1134 return sb_find_get_block_nonatomic(sb, block); 1135 } 1136 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_sb_find_get_block_nonatomic); 1137 1138 struct buffer_head *ext4_sb_getblk_unmovable(struct super_block *sb, 1139 ext4_fsblk_t block) 1140 { 1141 KUNIT_STATIC_STUB_REDIRECT(ext4_sb_getblk_unmovable, sb, block); 1142 return getblk_unmovable(sb->s_bdev, block, sb->s_blocksize); 1143 } 1144 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_sb_getblk_unmovable); 1145 1146 /* 1147 * `handle' can be NULL if create is zero 1148 */ 1149 struct buffer_head *ext4_getblk(handle_t *handle, struct inode *inode, 1150 ext4_lblk_t block, int map_flags) 1151 { 1152 struct ext4_map_blocks map; 1153 struct buffer_head *bh; 1154 int create = map_flags & EXT4_GET_BLOCKS_CREATE; 1155 bool nowait = map_flags & EXT4_GET_BLOCKS_CACHED_NOWAIT; 1156 int err; 1157 1158 KUNIT_STATIC_STUB_REDIRECT(ext4_getblk, handle, inode, block, 1159 map_flags); 1160 1161 ASSERT((EXT4_SB(inode->i_sb)->s_mount_state & EXT4_FC_REPLAY) 1162 || handle != NULL || create == 0); 1163 ASSERT(create == 0 || !nowait); 1164 1165 map.m_lblk = block; 1166 map.m_len = 1; 1167 err = ext4_map_blocks(handle, inode, &map, map_flags); 1168 1169 if (err == 0) 1170 return create ? ERR_PTR(-ENOSPC) : NULL; 1171 if (err < 0) 1172 return ERR_PTR(err); 1173 1174 if (nowait) 1175 return ext4_sb_find_get_block(inode->i_sb, map.m_pblk); 1176 1177 /* 1178 * Since bh could introduce extra ref count such as referred by 1179 * journal_head etc. Try to avoid using __GFP_MOVABLE here 1180 * as it may fail the migration when journal_head remains. 1181 */ 1182 bh = ext4_sb_getblk_unmovable(inode->i_sb, map.m_pblk); 1183 1184 if (unlikely(!bh)) 1185 return ERR_PTR(-ENOMEM); 1186 if (map.m_flags & EXT4_MAP_NEW) { 1187 ASSERT(create != 0); 1188 ASSERT((EXT4_SB(inode->i_sb)->s_mount_state & EXT4_FC_REPLAY) 1189 || (handle != NULL)); 1190 1191 /* 1192 * Now that we do not always journal data, we should 1193 * keep in mind whether this should always journal the 1194 * new buffer as metadata. For now, regular file 1195 * writes use ext4_get_block instead, so it's not a 1196 * problem. 1197 */ 1198 lock_buffer(bh); 1199 BUFFER_TRACE(bh, "call get_create_access"); 1200 err = ext4_journal_get_create_access(handle, inode->i_sb, bh, 1201 EXT4_JTR_NONE); 1202 if (unlikely(err)) { 1203 unlock_buffer(bh); 1204 goto errout; 1205 } 1206 if (!buffer_uptodate(bh)) { 1207 memset(bh->b_data, 0, inode->i_sb->s_blocksize); 1208 set_buffer_uptodate(bh); 1209 } 1210 unlock_buffer(bh); 1211 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata"); 1212 err = ext4_handle_dirty_metadata(handle, inode, bh); 1213 if (unlikely(err)) 1214 goto errout; 1215 } else 1216 BUFFER_TRACE(bh, "not a new buffer"); 1217 return bh; 1218 errout: 1219 brelse(bh); 1220 return ERR_PTR(err); 1221 } 1222 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_getblk); 1223 1224 struct buffer_head *ext4_bread(handle_t *handle, struct inode *inode, 1225 ext4_lblk_t block, int map_flags) 1226 { 1227 struct buffer_head *bh; 1228 int ret; 1229 1230 bh = ext4_getblk(handle, inode, block, map_flags); 1231 if (IS_ERR(bh)) 1232 return bh; 1233 if (!bh || ext4_buffer_uptodate(bh)) 1234 return bh; 1235 1236 ret = ext4_read_bh_lock(bh, REQ_META | REQ_PRIO, true); 1237 if (ret) { 1238 put_bh(bh); 1239 return ERR_PTR(ret); 1240 } 1241 return bh; 1242 } 1243 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_bread); 1244 1245 /* Read a contiguous batch of blocks. */ 1246 int ext4_bread_batch(struct inode *inode, ext4_lblk_t block, int bh_count, 1247 bool wait, struct buffer_head **bhs) 1248 { 1249 int i, err; 1250 1251 for (i = 0; i < bh_count; i++) { 1252 bhs[i] = ext4_getblk(NULL, inode, block + i, 0 /* map_flags */); 1253 if (IS_ERR(bhs[i])) { 1254 err = PTR_ERR(bhs[i]); 1255 bh_count = i; 1256 goto out_brelse; 1257 } 1258 } 1259 1260 for (i = 0; i < bh_count; i++) 1261 /* Note that NULL bhs[i] is valid because of holes. */ 1262 if (bhs[i] && !ext4_buffer_uptodate(bhs[i])) 1263 ext4_read_bh_lock(bhs[i], REQ_META | REQ_PRIO, false); 1264 1265 if (!wait) 1266 return 0; 1267 1268 for (i = 0; i < bh_count; i++) 1269 if (bhs[i]) 1270 wait_on_buffer(bhs[i]); 1271 1272 for (i = 0; i < bh_count; i++) { 1273 if (bhs[i] && !buffer_uptodate(bhs[i])) { 1274 err = -EIO; 1275 goto out_brelse; 1276 } 1277 } 1278 return 0; 1279 1280 out_brelse: 1281 for (i = 0; i < bh_count; i++) { 1282 brelse(bhs[i]); 1283 bhs[i] = NULL; 1284 } 1285 return err; 1286 } 1287 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_bread_batch); 1288 1289 int ext4_walk_page_buffers(handle_t *handle, struct inode *inode, 1290 struct buffer_head *head, 1291 unsigned from, 1292 unsigned to, 1293 int *partial, 1294 int (*fn)(handle_t *handle, struct inode *inode, 1295 struct buffer_head *bh)) 1296 { 1297 struct buffer_head *bh; 1298 unsigned block_start, block_end; 1299 unsigned blocksize = head->b_size; 1300 int err, ret = 0; 1301 struct buffer_head *next; 1302 1303 for (bh = head, block_start = 0; 1304 ret == 0 && (bh != head || !block_start); 1305 block_start = block_end, bh = next) { 1306 next = bh->b_this_page; 1307 block_end = block_start + blocksize; 1308 if (block_end <= from || block_start >= to) { 1309 if (partial && !buffer_uptodate(bh)) 1310 *partial = 1; 1311 continue; 1312 } 1313 err = (*fn)(handle, inode, bh); 1314 if (!ret) 1315 ret = err; 1316 } 1317 return ret; 1318 } 1319 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_walk_page_buffers); 1320 1321 /* 1322 * Helper for handling dirtying of journalled data. We also mark the folio as 1323 * dirty so that writeback code knows about this page (and inode) contains 1324 * dirty data. ext4_writepages() then commits appropriate transaction to 1325 * make data stable. 1326 */ 1327 static int ext4_dirty_journalled_data(handle_t *handle, struct buffer_head *bh) 1328 { 1329 struct folio *folio = bh->b_folio; 1330 struct inode *inode = folio->mapping->host; 1331 1332 /* only regular files have a_ops */ 1333 if (S_ISREG(inode->i_mode)) 1334 folio_mark_dirty(folio); 1335 return ext4_handle_dirty_metadata(handle, NULL, bh); 1336 } 1337 1338 int do_journal_get_write_access(handle_t *handle, struct inode *inode, 1339 struct buffer_head *bh) 1340 { 1341 if (!buffer_mapped(bh) || buffer_freed(bh)) 1342 return 0; 1343 BUFFER_TRACE(bh, "get write access"); 1344 return ext4_journal_get_write_access(handle, inode->i_sb, bh, 1345 EXT4_JTR_NONE); 1346 } 1347 1348 int ext4_block_write_begin(handle_t *handle, struct folio *folio, 1349 loff_t pos, unsigned len, 1350 get_block_t *get_block) 1351 { 1352 unsigned int from = offset_in_folio(folio, pos); 1353 unsigned to = from + len; 1354 struct inode *inode = folio->mapping->host; 1355 unsigned block_start, block_end; 1356 sector_t block; 1357 int err = 0; 1358 unsigned int blocksize = i_blocksize(inode); 1359 struct buffer_head *bh, *head, *wait[2]; 1360 int nr_wait = 0; 1361 int i; 1362 bool should_journal_data = ext4_should_journal_data(inode); 1363 bool folio_uptodate = folio_test_uptodate(folio); 1364 1365 BUG_ON(!folio_test_locked(folio)); 1366 BUG_ON(to > folio_size(folio)); 1367 BUG_ON(from > to); 1368 WARN_ON_ONCE(blocksize > folio_size(folio)); 1369 1370 head = folio_buffers(folio); 1371 if (!head) 1372 head = create_empty_buffers(folio, blocksize, 0); 1373 block = EXT4_PG_TO_LBLK(inode, folio->index); 1374 1375 for (bh = head, block_start = 0; 1376 block_start < to || (!folio_uptodate && bh != head); 1377 block++, block_start = block_end, bh = bh->b_this_page) { 1378 block_end = block_start + blocksize; 1379 if (block_end <= from || block_start >= to) { 1380 if (folio_uptodate) 1381 set_buffer_uptodate(bh); 1382 continue; 1383 } 1384 if (WARN_ON_ONCE(buffer_new(bh))) 1385 clear_buffer_new(bh); 1386 if (!buffer_mapped(bh)) { 1387 WARN_ON(bh->b_size != blocksize); 1388 err = ext4_journal_ensure_extent_credits(handle, inode); 1389 if (!err) 1390 err = get_block(inode, block, bh, 1); 1391 if (err) 1392 break; 1393 if (buffer_new(bh)) { 1394 /* 1395 * We may be zeroing partial buffers or all new 1396 * buffers in case of failure. Prepare JBD2 for 1397 * that. 1398 */ 1399 if (should_journal_data) 1400 do_journal_get_write_access(handle, 1401 inode, bh); 1402 if (folio_uptodate) { 1403 /* 1404 * Unlike __block_write_begin() we leave 1405 * dirtying of new uptodate buffers to 1406 * ->write_end() time or 1407 * folio_zero_new_buffers(). 1408 */ 1409 set_buffer_uptodate(bh); 1410 continue; 1411 } 1412 if (block_end > to || block_start < from) 1413 folio_zero_segments(folio, to, 1414 block_end, 1415 block_start, from); 1416 continue; 1417 } 1418 } 1419 if (folio_uptodate) { 1420 set_buffer_uptodate(bh); 1421 continue; 1422 } 1423 if (!buffer_uptodate(bh) && !buffer_delay(bh) && 1424 !buffer_unwritten(bh) && 1425 (block_start < from || block_end > to)) { 1426 ext4_read_bh_lock(bh, 0, false); 1427 wait[nr_wait++] = bh; 1428 } 1429 } 1430 /* 1431 * If we issued read requests, let them complete. 1432 */ 1433 for (i = 0; i < nr_wait; i++) { 1434 wait_on_buffer(wait[i]); 1435 if (!buffer_uptodate(wait[i])) 1436 err = -EIO; 1437 } 1438 if (unlikely(err)) { 1439 if (should_journal_data) 1440 ext4_journalled_zero_new_buffers(handle, inode, folio, 1441 from, to); 1442 else 1443 folio_zero_new_buffers(folio, from, to); 1444 } 1445 1446 return err; 1447 } 1448 1449 /* 1450 * To preserve ordering, it is essential that the hole instantiation and 1451 * the data write be encapsulated in a single transaction. We cannot 1452 * close off a transaction and start a new one between the ext4_get_block() 1453 * and the ext4_write_end(). So doing the jbd2_journal_start at the start of 1454 * ext4_write_begin() is the right place. 1455 */ 1456 static int ext4_write_begin(const struct kiocb *iocb, 1457 struct address_space *mapping, 1458 loff_t pos, unsigned len, 1459 struct folio **foliop, void **fsdata) 1460 { 1461 struct inode *inode = mapping->host; 1462 int ret, needed_blocks; 1463 handle_t *handle; 1464 int retries = 0; 1465 struct folio *folio; 1466 pgoff_t index; 1467 unsigned from, to; 1468 1469 ret = ext4_emergency_state(inode->i_sb); 1470 if (unlikely(ret)) 1471 return ret; 1472 1473 *fsdata = (void *)((unsigned long)*fsdata & ~EXT4_WRITE_DATA_INLINE); 1474 1475 trace_ext4_write_begin(inode, pos, len); 1476 /* 1477 * Reserve one block more for addition to orphan list in case 1478 * we allocate blocks but write fails for some reason 1479 */ 1480 needed_blocks = ext4_chunk_trans_extent(inode, 1481 ext4_journal_blocks_per_folio(inode)) + 1; 1482 index = pos >> PAGE_SHIFT; 1483 1484 if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) { 1485 ret = ext4_try_to_write_inline_data(mapping, inode, pos, len, 1486 foliop); 1487 if (ret < 0) 1488 return ret; 1489 if (ret == 1) { 1490 *fsdata = (void *)((unsigned long)*fsdata | EXT4_WRITE_DATA_INLINE); 1491 return 0; 1492 } 1493 } 1494 1495 /* 1496 * write_begin_get_folio() can take a long time if the 1497 * system is thrashing due to memory pressure, or if the folio 1498 * is being written back. So grab it first before we start 1499 * the transaction handle. This also allows us to allocate 1500 * the folio (if needed) without using GFP_NOFS. 1501 */ 1502 retry_grab: 1503 folio = write_begin_get_folio(iocb, mapping, index, len); 1504 if (IS_ERR(folio)) 1505 return PTR_ERR(folio); 1506 1507 if (len > folio_next_pos(folio) - pos) 1508 len = folio_next_pos(folio) - pos; 1509 1510 from = offset_in_folio(folio, pos); 1511 to = from + len; 1512 1513 /* 1514 * The same as page allocation, we prealloc buffer heads before 1515 * starting the handle. 1516 */ 1517 if (!folio_buffers(folio)) 1518 create_empty_buffers(folio, inode->i_sb->s_blocksize, 0); 1519 1520 folio_unlock(folio); 1521 1522 retry_journal: 1523 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE, needed_blocks); 1524 if (IS_ERR(handle)) { 1525 folio_put(folio); 1526 return PTR_ERR(handle); 1527 } 1528 1529 folio_lock(folio); 1530 if (folio->mapping != mapping) { 1531 /* The folio got truncated from under us */ 1532 folio_unlock(folio); 1533 folio_put(folio); 1534 ext4_journal_stop(handle); 1535 goto retry_grab; 1536 } 1537 /* In case writeback began while the folio was unlocked */ 1538 folio_wait_stable(folio); 1539 1540 if (ext4_should_dioread_nolock(inode)) 1541 ret = ext4_block_write_begin(handle, folio, pos, len, 1542 ext4_get_block_unwritten); 1543 else 1544 ret = ext4_block_write_begin(handle, folio, pos, len, 1545 ext4_get_block); 1546 if (!ret && ext4_should_journal_data(inode)) { 1547 ret = ext4_walk_page_buffers(handle, inode, 1548 folio_buffers(folio), from, to, 1549 NULL, do_journal_get_write_access); 1550 } 1551 1552 if (ret) { 1553 bool extended = (pos + len > inode->i_size) && 1554 !ext4_verity_in_progress(inode); 1555 1556 folio_unlock(folio); 1557 /* 1558 * ext4_block_write_begin may have instantiated a few blocks 1559 * outside i_size. Trim these off again. Don't need 1560 * i_size_read because we hold i_rwsem. 1561 * 1562 * Add inode to orphan list in case we crash before 1563 * truncate finishes 1564 */ 1565 if (extended && ext4_can_truncate(inode)) 1566 ext4_orphan_add(handle, inode); 1567 1568 ext4_journal_stop(handle); 1569 if (extended) { 1570 ext4_truncate_failed_write(inode); 1571 /* 1572 * If truncate failed early the inode might 1573 * still be on the orphan list; we need to 1574 * make sure the inode is removed from the 1575 * orphan list in that case. 1576 */ 1577 if (inode->i_nlink) 1578 ext4_orphan_del(NULL, inode); 1579 } 1580 1581 if (ret == -EAGAIN || 1582 (ret == -ENOSPC && 1583 ext4_should_retry_alloc(inode->i_sb, &retries))) 1584 goto retry_journal; 1585 folio_put(folio); 1586 return ret; 1587 } 1588 *foliop = folio; 1589 return ret; 1590 } 1591 1592 /* For write_end() in data=journal mode */ 1593 static int write_end_fn(handle_t *handle, struct inode *inode, 1594 struct buffer_head *bh) 1595 { 1596 int ret; 1597 if (!buffer_mapped(bh) || buffer_freed(bh)) 1598 return 0; 1599 set_buffer_uptodate(bh); 1600 ret = ext4_dirty_journalled_data(handle, bh); 1601 clear_buffer_meta(bh); 1602 clear_buffer_prio(bh); 1603 clear_buffer_new(bh); 1604 return ret; 1605 } 1606 1607 /* 1608 * We need to pick up the new inode size which generic_commit_write gave us 1609 * `iocb` can be NULL - eg, when called from page_symlink(). 1610 */ 1611 static int ext4_write_end(const struct kiocb *iocb, 1612 struct address_space *mapping, 1613 loff_t pos, unsigned len, unsigned copied, 1614 struct folio *folio, void *fsdata) 1615 { 1616 handle_t *handle = ext4_journal_current_handle(); 1617 struct inode *inode = mapping->host; 1618 loff_t old_size = inode->i_size; 1619 int ret = 0, ret2; 1620 int i_size_changed = 0; 1621 bool verity = ext4_verity_in_progress(inode); 1622 1623 trace_ext4_write_end(inode, pos, len, copied); 1624 1625 if ((unsigned long)fsdata & EXT4_WRITE_DATA_INLINE) 1626 return ext4_write_inline_data_end(inode, pos, len, copied, 1627 folio); 1628 1629 copied = block_write_end(pos, len, copied, folio); 1630 /* 1631 * it's important to update i_size while still holding folio lock: 1632 * page writeout could otherwise come in and zero beyond i_size. 1633 * 1634 * If nothing was copied (e.g. the source buffer was unreadable), do 1635 * not move i_size up to pos. 1636 * 1637 * If FS_IOC_ENABLE_VERITY is running on this inode, then Merkle tree 1638 * blocks are being written past EOF, so skip the i_size update. 1639 */ 1640 if (copied && !verity) 1641 i_size_changed = ext4_update_inode_size(inode, pos + copied); 1642 folio_unlock(folio); 1643 folio_put(folio); 1644 1645 if (copied && old_size < pos && !verity) 1646 pagecache_isize_extended(inode, old_size, pos); 1647 1648 /* 1649 * Don't mark the inode dirty under folio lock. First, it unnecessarily 1650 * makes the holding time of folio lock longer. Second, it forces lock 1651 * ordering of folio lock and transaction start for journaling 1652 * filesystems. 1653 */ 1654 if (i_size_changed) 1655 ret = ext4_mark_inode_dirty(handle, inode); 1656 1657 if (pos + len > inode->i_size && !verity && ext4_can_truncate(inode)) 1658 /* if we have allocated more blocks and copied 1659 * less. We will have blocks allocated outside 1660 * inode->i_size. So truncate them 1661 */ 1662 ext4_orphan_add(handle, inode); 1663 1664 ret2 = ext4_journal_stop(handle); 1665 if (!ret) 1666 ret = ret2; 1667 1668 if (pos + len > inode->i_size && !verity) { 1669 ext4_truncate_failed_write(inode); 1670 /* 1671 * If truncate failed early the inode might still be 1672 * on the orphan list; we need to make sure the inode 1673 * is removed from the orphan list in that case. 1674 */ 1675 if (inode->i_nlink) 1676 ext4_orphan_del(NULL, inode); 1677 } 1678 1679 return ret ? ret : copied; 1680 } 1681 1682 /* 1683 * This is a private version of folio_zero_new_buffers() which doesn't 1684 * set the buffer to be dirty, since in data=journalled mode we need 1685 * to call ext4_dirty_journalled_data() instead. 1686 */ 1687 static void ext4_journalled_zero_new_buffers(handle_t *handle, 1688 struct inode *inode, 1689 struct folio *folio, 1690 unsigned from, unsigned to) 1691 { 1692 unsigned int block_start = 0, block_end; 1693 struct buffer_head *head, *bh; 1694 1695 bh = head = folio_buffers(folio); 1696 do { 1697 block_end = block_start + bh->b_size; 1698 if (buffer_new(bh)) { 1699 if (block_end > from && block_start < to) { 1700 if (!folio_test_uptodate(folio)) { 1701 unsigned start, size; 1702 1703 start = max(from, block_start); 1704 size = min(to, block_end) - start; 1705 1706 folio_zero_range(folio, start, size); 1707 } 1708 clear_buffer_new(bh); 1709 write_end_fn(handle, inode, bh); 1710 } 1711 } 1712 block_start = block_end; 1713 bh = bh->b_this_page; 1714 } while (bh != head); 1715 } 1716 1717 static int ext4_journalled_write_end(const struct kiocb *iocb, 1718 struct address_space *mapping, 1719 loff_t pos, unsigned len, unsigned copied, 1720 struct folio *folio, void *fsdata) 1721 { 1722 handle_t *handle = ext4_journal_current_handle(); 1723 struct inode *inode = mapping->host; 1724 loff_t old_size = inode->i_size; 1725 int ret = 0, ret2; 1726 int partial = 0; 1727 unsigned from, to; 1728 int size_changed = 0; 1729 bool verity = ext4_verity_in_progress(inode); 1730 1731 trace_ext4_journalled_write_end(inode, pos, len, copied); 1732 from = pos & (PAGE_SIZE - 1); 1733 to = from + len; 1734 1735 BUG_ON(!ext4_handle_valid(handle)); 1736 1737 if ((unsigned long)fsdata & EXT4_WRITE_DATA_INLINE) 1738 return ext4_write_inline_data_end(inode, pos, len, copied, 1739 folio); 1740 1741 if (unlikely(copied < len) && !folio_test_uptodate(folio)) { 1742 copied = 0; 1743 ext4_journalled_zero_new_buffers(handle, inode, folio, 1744 from, to); 1745 } else { 1746 if (unlikely(copied < len)) 1747 ext4_journalled_zero_new_buffers(handle, inode, folio, 1748 from + copied, to); 1749 ret = ext4_walk_page_buffers(handle, inode, 1750 folio_buffers(folio), 1751 from, from + copied, &partial, 1752 write_end_fn); 1753 if (!partial) 1754 folio_mark_uptodate(folio); 1755 } 1756 if (copied && !verity) 1757 size_changed = ext4_update_inode_size(inode, pos + copied); 1758 EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid; 1759 folio_unlock(folio); 1760 folio_put(folio); 1761 1762 if (copied && old_size < pos && !verity) 1763 pagecache_isize_extended(inode, old_size, pos); 1764 1765 if (size_changed) { 1766 ret2 = ext4_mark_inode_dirty(handle, inode); 1767 if (!ret) 1768 ret = ret2; 1769 } 1770 1771 if (pos + len > inode->i_size && !verity && ext4_can_truncate(inode)) 1772 /* if we have allocated more blocks and copied 1773 * less. We will have blocks allocated outside 1774 * inode->i_size. So truncate them 1775 */ 1776 ext4_orphan_add(handle, inode); 1777 1778 ret2 = ext4_journal_stop(handle); 1779 if (!ret) 1780 ret = ret2; 1781 if (pos + len > inode->i_size && !verity) { 1782 ext4_wait_for_tail_page_commit(inode); 1783 ext4_truncate_failed_write(inode); 1784 /* 1785 * If truncate failed early the inode might still be 1786 * on the orphan list; we need to make sure the inode 1787 * is removed from the orphan list in that case. 1788 */ 1789 if (inode->i_nlink) 1790 ext4_orphan_del(NULL, inode); 1791 } 1792 1793 return ret ? ret : copied; 1794 } 1795 1796 /* 1797 * Reserve space for 'nr_resv' clusters 1798 */ 1799 static int ext4_da_reserve_space(struct inode *inode, int nr_resv) 1800 { 1801 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb); 1802 struct ext4_inode_info *ei = EXT4_I(inode); 1803 int ret; 1804 1805 /* 1806 * We will charge metadata quota at writeout time; this saves 1807 * us from metadata over-estimation, though we may go over by 1808 * a small amount in the end. Here we just reserve for data. 1809 */ 1810 ret = dquot_reserve_block(inode, EXT4_C2B(sbi, nr_resv)); 1811 if (ret) 1812 return ret; 1813 1814 spin_lock(&ei->i_block_reservation_lock); 1815 if (ext4_claim_free_clusters(sbi, nr_resv, 0)) { 1816 spin_unlock(&ei->i_block_reservation_lock); 1817 dquot_release_reservation_block(inode, EXT4_C2B(sbi, nr_resv)); 1818 return -ENOSPC; 1819 } 1820 ei->i_reserved_data_blocks += nr_resv; 1821 trace_ext4_da_reserve_space(inode, nr_resv); 1822 spin_unlock(&ei->i_block_reservation_lock); 1823 1824 return 0; /* success */ 1825 } 1826 1827 void ext4_da_release_space(struct inode *inode, int to_free) 1828 { 1829 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb); 1830 struct ext4_inode_info *ei = EXT4_I(inode); 1831 1832 KUNIT_STATIC_STUB_REDIRECT(ext4_da_release_space, inode, to_free); 1833 1834 if (!to_free) 1835 return; /* Nothing to release, exit */ 1836 1837 spin_lock(&EXT4_I(inode)->i_block_reservation_lock); 1838 1839 trace_ext4_da_release_space(inode, to_free); 1840 if (unlikely(to_free > ei->i_reserved_data_blocks)) { 1841 /* 1842 * if there aren't enough reserved blocks, then the 1843 * counter is messed up somewhere. Since this 1844 * function is called from invalidate page, it's 1845 * harmless to return without any action. 1846 */ 1847 ext4_warning(inode->i_sb, "ext4_da_release_space: " 1848 "ino %llu, to_free %d with only %d reserved " 1849 "data blocks", inode->i_ino, to_free, 1850 ei->i_reserved_data_blocks); 1851 WARN_ON(1); 1852 to_free = ei->i_reserved_data_blocks; 1853 } 1854 ei->i_reserved_data_blocks -= to_free; 1855 1856 /* update fs dirty data blocks counter */ 1857 percpu_counter_sub(&sbi->s_dirtyclusters_counter, to_free); 1858 1859 spin_unlock(&EXT4_I(inode)->i_block_reservation_lock); 1860 1861 dquot_release_reservation_block(inode, EXT4_C2B(sbi, to_free)); 1862 } 1863 1864 /* 1865 * Delayed allocation stuff 1866 */ 1867 1868 struct mpage_da_data { 1869 /* These are input fields for ext4_do_writepages() */ 1870 struct inode *inode; 1871 struct writeback_control *wbc; 1872 unsigned int can_map:1; /* Can writepages call map blocks? */ 1873 1874 /* These are internal state of ext4_do_writepages() */ 1875 loff_t start_pos; /* The start pos to write */ 1876 loff_t next_pos; /* Current pos to examine */ 1877 loff_t end_pos; /* Last pos to examine */ 1878 1879 /* 1880 * Extent to map - this can be after start_pos because that can be 1881 * fully mapped. We somewhat abuse m_flags to store whether the extent 1882 * is delalloc or unwritten. 1883 */ 1884 struct ext4_map_blocks map; 1885 struct ext4_io_submit io_submit; /* IO submission data */ 1886 unsigned int do_map:1; 1887 unsigned int scanned_until_end:1; 1888 unsigned int journalled_more_data:1; 1889 }; 1890 1891 static void mpage_release_unused_pages(struct mpage_da_data *mpd, 1892 bool invalidate) 1893 { 1894 unsigned nr, i; 1895 pgoff_t index, end; 1896 struct folio_batch fbatch; 1897 struct inode *inode = mpd->inode; 1898 struct address_space *mapping = inode->i_mapping; 1899 1900 /* This is necessary when next_pos == 0. */ 1901 if (mpd->start_pos >= mpd->next_pos) 1902 return; 1903 1904 mpd->scanned_until_end = 0; 1905 if (invalidate) { 1906 ext4_lblk_t start, last; 1907 start = EXT4_B_TO_LBLK(inode, mpd->start_pos); 1908 last = mpd->next_pos >> inode->i_blkbits; 1909 1910 /* 1911 * avoid racing with extent status tree scans made by 1912 * ext4_insert_delayed_block() 1913 */ 1914 down_write(&EXT4_I(inode)->i_data_sem); 1915 ext4_es_remove_extent(inode, start, last - start); 1916 up_write(&EXT4_I(inode)->i_data_sem); 1917 } 1918 1919 folio_batch_init(&fbatch); 1920 index = mpd->start_pos >> PAGE_SHIFT; 1921 end = mpd->next_pos >> PAGE_SHIFT; 1922 while (index < end) { 1923 nr = filemap_get_folios(mapping, &index, end - 1, &fbatch); 1924 if (nr == 0) 1925 break; 1926 for (i = 0; i < nr; i++) { 1927 struct folio *folio = fbatch.folios[i]; 1928 1929 if (folio_pos(folio) < mpd->start_pos) 1930 continue; 1931 if (folio_next_index(folio) > end) 1932 continue; 1933 BUG_ON(!folio_test_locked(folio)); 1934 BUG_ON(folio_test_writeback(folio)); 1935 if (invalidate) { 1936 if (folio_mapped(folio)) { 1937 folio_clear_dirty_for_io(folio); 1938 /* 1939 * Unmap folio from page 1940 * tables to prevent 1941 * subsequent accesses through 1942 * stale PTEs. This ensures 1943 * future accesses trigger new 1944 * page faults rather than 1945 * reusing the invalidated 1946 * folio. 1947 */ 1948 unmap_mapping_pages(folio->mapping, 1949 folio->index, 1950 folio_nr_pages(folio), false); 1951 } 1952 block_invalidate_folio(folio, 0, 1953 folio_size(folio)); 1954 folio_clear_uptodate(folio); 1955 } 1956 folio_unlock(folio); 1957 } 1958 folio_batch_release(&fbatch); 1959 } 1960 } 1961 1962 static void ext4_print_free_blocks(struct inode *inode) 1963 { 1964 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb); 1965 struct super_block *sb = inode->i_sb; 1966 struct ext4_inode_info *ei = EXT4_I(inode); 1967 1968 ext4_msg(sb, KERN_CRIT, "Total free blocks count %lld", 1969 EXT4_C2B(EXT4_SB(inode->i_sb), 1970 ext4_count_free_clusters(sb))); 1971 ext4_msg(sb, KERN_CRIT, "Free/Dirty block details"); 1972 ext4_msg(sb, KERN_CRIT, "free_blocks=%lld", 1973 (long long) EXT4_C2B(EXT4_SB(sb), 1974 percpu_counter_sum(&sbi->s_freeclusters_counter))); 1975 ext4_msg(sb, KERN_CRIT, "dirty_blocks=%lld", 1976 (long long) EXT4_C2B(EXT4_SB(sb), 1977 percpu_counter_sum(&sbi->s_dirtyclusters_counter))); 1978 ext4_msg(sb, KERN_CRIT, "Block reservation details"); 1979 ext4_msg(sb, KERN_CRIT, "i_reserved_data_blocks=%u", 1980 ei->i_reserved_data_blocks); 1981 return; 1982 } 1983 1984 /* 1985 * Check whether the cluster containing lblk has been allocated or has 1986 * delalloc reservation. 1987 * 1988 * Returns 0 if the cluster doesn't have either, 1 if it has delalloc 1989 * reservation, 2 if it's already been allocated, negative error code on 1990 * failure. 1991 */ 1992 static int ext4_clu_alloc_state(struct inode *inode, ext4_lblk_t lblk) 1993 { 1994 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb); 1995 int ret; 1996 1997 /* Has delalloc reservation? */ 1998 if (ext4_es_scan_clu(inode, &ext4_es_is_delayed, lblk)) 1999 return 1; 2000 2001 /* Already been allocated? */ 2002 if (ext4_es_scan_clu(inode, &ext4_es_is_mapped, lblk)) 2003 return 2; 2004 ret = ext4_clu_mapped(inode, EXT4_B2C(sbi, lblk)); 2005 if (ret < 0) 2006 return ret; 2007 if (ret > 0) 2008 return 2; 2009 2010 return 0; 2011 } 2012 2013 /* 2014 * ext4_insert_delayed_blocks - adds a multiple delayed blocks to the extents 2015 * status tree, incrementing the reserved 2016 * cluster/block count or making pending 2017 * reservations where needed 2018 * 2019 * @inode - file containing the newly added block 2020 * @lblk - start logical block to be added 2021 * @len - length of blocks to be added 2022 * 2023 * Returns 0 on success, negative error code on failure. 2024 */ 2025 static int ext4_insert_delayed_blocks(struct inode *inode, ext4_lblk_t lblk, 2026 ext4_lblk_t len) 2027 { 2028 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb); 2029 int ret; 2030 bool lclu_allocated = false; 2031 bool end_allocated = false; 2032 ext4_lblk_t resv_clu; 2033 ext4_lblk_t end = lblk + len - 1; 2034 2035 /* 2036 * If the cluster containing lblk or end is shared with a delayed, 2037 * written, or unwritten extent in a bigalloc file system, it's 2038 * already been accounted for and does not need to be reserved. 2039 * A pending reservation must be made for the cluster if it's 2040 * shared with a written or unwritten extent and doesn't already 2041 * have one. Written and unwritten extents can be purged from the 2042 * extents status tree if the system is under memory pressure, so 2043 * it's necessary to examine the extent tree if a search of the 2044 * extents status tree doesn't get a match. 2045 */ 2046 if (sbi->s_cluster_ratio == 1) { 2047 ret = ext4_da_reserve_space(inode, len); 2048 if (ret != 0) /* ENOSPC */ 2049 return ret; 2050 } else { /* bigalloc */ 2051 resv_clu = EXT4_B2C(sbi, end) - EXT4_B2C(sbi, lblk) + 1; 2052 2053 ret = ext4_clu_alloc_state(inode, lblk); 2054 if (ret < 0) 2055 return ret; 2056 if (ret > 0) { 2057 resv_clu--; 2058 lclu_allocated = (ret == 2); 2059 } 2060 2061 if (EXT4_B2C(sbi, lblk) != EXT4_B2C(sbi, end)) { 2062 ret = ext4_clu_alloc_state(inode, end); 2063 if (ret < 0) 2064 return ret; 2065 if (ret > 0) { 2066 resv_clu--; 2067 end_allocated = (ret == 2); 2068 } 2069 } 2070 2071 if (resv_clu) { 2072 ret = ext4_da_reserve_space(inode, resv_clu); 2073 if (ret != 0) /* ENOSPC */ 2074 return ret; 2075 } 2076 } 2077 2078 ext4_es_insert_delayed_extent(inode, lblk, len, lclu_allocated, 2079 end_allocated); 2080 return 0; 2081 } 2082 2083 /* 2084 * Looks up the requested blocks and sets the delalloc extent map. 2085 * First try to look up for the extent entry that contains the requested 2086 * blocks in the extent status tree without i_data_sem, then try to look 2087 * up for the ondisk extent mapping with i_data_sem in read mode, 2088 * finally hold i_data_sem in write mode, looks up again and add a 2089 * delalloc extent entry if it still couldn't find any extent. Pass out 2090 * the mapped extent through @map and return 0 on success. 2091 */ 2092 static int ext4_da_map_blocks(struct inode *inode, struct ext4_map_blocks *map) 2093 { 2094 struct extent_status es; 2095 int retval; 2096 #ifdef ES_AGGRESSIVE_TEST 2097 struct ext4_map_blocks orig_map; 2098 2099 memcpy(&orig_map, map, sizeof(*map)); 2100 #endif 2101 2102 map->m_flags = 0; 2103 map->m_pblk = 0; 2104 ext_debug(inode, "max_blocks %u, logical block %lu\n", map->m_len, 2105 (unsigned long) map->m_lblk); 2106 2107 ext4_check_map_extents_env(inode); 2108 2109 /* Lookup extent status tree firstly */ 2110 if (ext4_es_lookup_extent(inode, map->m_lblk, NULL, &es, &map->m_seq)) { 2111 map->m_len = min_t(unsigned int, map->m_len, 2112 es.es_len - (map->m_lblk - es.es_lblk)); 2113 2114 if (ext4_es_is_hole(&es)) 2115 goto add_delayed; 2116 2117 found: 2118 /* 2119 * Delayed extent could be allocated by fallocate. 2120 * So we need to check it. 2121 */ 2122 if (ext4_es_is_delayed(&es)) { 2123 map->m_flags |= EXT4_MAP_DELAYED; 2124 return 0; 2125 } 2126 2127 map->m_pblk = ext4_es_pblock(&es) + map->m_lblk - es.es_lblk; 2128 if (ext4_es_is_written(&es)) 2129 map->m_flags |= EXT4_MAP_MAPPED; 2130 else if (ext4_es_is_unwritten(&es)) 2131 map->m_flags |= EXT4_MAP_UNWRITTEN; 2132 else 2133 BUG(); 2134 2135 #ifdef ES_AGGRESSIVE_TEST 2136 ext4_map_blocks_es_recheck(NULL, inode, map, &orig_map, 0); 2137 #endif 2138 return 0; 2139 } 2140 2141 /* 2142 * Try to see if we can get the block without requesting a new 2143 * file system block. 2144 */ 2145 down_read(&EXT4_I(inode)->i_data_sem); 2146 if (ext4_has_inline_data(inode)) 2147 retval = 0; 2148 else 2149 retval = ext4_map_query_blocks(NULL, inode, map, 0); 2150 up_read(&EXT4_I(inode)->i_data_sem); 2151 if (retval) 2152 return retval < 0 ? retval : 0; 2153 2154 add_delayed: 2155 down_write(&EXT4_I(inode)->i_data_sem); 2156 /* 2157 * Page fault path (ext4_page_mkwrite does not take i_rwsem) 2158 * and fallocate path (no folio lock) can race. Make sure we 2159 * lookup the extent status tree here again while i_data_sem 2160 * is held in write mode, before inserting a new da entry in 2161 * the extent status tree. 2162 */ 2163 if (ext4_es_lookup_extent(inode, map->m_lblk, NULL, &es, &map->m_seq)) { 2164 map->m_len = min_t(unsigned int, map->m_len, 2165 es.es_len - (map->m_lblk - es.es_lblk)); 2166 2167 if (!ext4_es_is_hole(&es)) { 2168 up_write(&EXT4_I(inode)->i_data_sem); 2169 goto found; 2170 } 2171 } else if (!ext4_has_inline_data(inode)) { 2172 retval = ext4_map_query_blocks(NULL, inode, map, 0); 2173 if (retval) { 2174 up_write(&EXT4_I(inode)->i_data_sem); 2175 return retval < 0 ? retval : 0; 2176 } 2177 } 2178 2179 map->m_flags |= EXT4_MAP_DELAYED | EXT4_MAP_NEW; 2180 retval = ext4_insert_delayed_blocks(inode, map->m_lblk, map->m_len); 2181 if (!retval) 2182 map->m_seq = READ_ONCE(EXT4_I(inode)->i_es_seq); 2183 up_write(&EXT4_I(inode)->i_data_sem); 2184 2185 return retval; 2186 } 2187 2188 /* 2189 * This is a special get_block_t callback which is used by 2190 * ext4_da_write_begin(). It will either return mapped block or 2191 * reserve space for a single block. 2192 * 2193 * For delayed buffer_head we have BH_Mapped, BH_New, BH_Delay set. 2194 * We also have b_blocknr = -1 and b_bdev initialized properly 2195 * 2196 * For unwritten buffer_head we have BH_Mapped, BH_New, BH_Unwritten set. 2197 * We also have b_blocknr = physicalblock mapping unwritten extent and b_bdev 2198 * initialized properly. 2199 */ 2200 int ext4_da_get_block_prep(struct inode *inode, sector_t iblock, 2201 struct buffer_head *bh, int create) 2202 { 2203 struct ext4_map_blocks map; 2204 sector_t invalid_block = ~((sector_t) 0xffff); 2205 int ret = 0; 2206 2207 KUNIT_STATIC_STUB_REDIRECT(ext4_da_get_block_prep, inode, iblock, bh, 2208 create); 2209 2210 BUG_ON(create == 0); 2211 BUG_ON(bh->b_size != inode->i_sb->s_blocksize); 2212 2213 if (invalid_block < ext4_blocks_count(EXT4_SB(inode->i_sb)->s_es)) 2214 invalid_block = ~0; 2215 2216 map.m_lblk = iblock; 2217 map.m_len = 1; 2218 2219 /* 2220 * first, we need to know whether the block is allocated already 2221 * preallocated blocks are unmapped but should treated 2222 * the same as allocated blocks. 2223 */ 2224 ret = ext4_da_map_blocks(inode, &map); 2225 if (ret < 0) 2226 return ret; 2227 2228 if (map.m_flags & EXT4_MAP_DELAYED) { 2229 map_bh(bh, inode->i_sb, invalid_block); 2230 set_buffer_new(bh); 2231 set_buffer_delay(bh); 2232 return 0; 2233 } 2234 2235 map_bh(bh, inode->i_sb, map.m_pblk); 2236 ext4_update_bh_state(bh, map.m_flags); 2237 2238 if (buffer_unwritten(bh)) { 2239 /* A delayed write to unwritten bh should be marked 2240 * new and mapped. Mapped ensures that we don't do 2241 * get_block multiple times when we write to the same 2242 * offset and new ensures that we do proper zero out 2243 * for partial write. 2244 */ 2245 set_buffer_new(bh); 2246 set_buffer_mapped(bh); 2247 } 2248 return 0; 2249 } 2250 2251 static void mpage_folio_done(struct mpage_da_data *mpd, struct folio *folio) 2252 { 2253 mpd->start_pos += folio_size(folio); 2254 mpd->wbc->nr_to_write -= folio_nr_pages(folio); 2255 folio_unlock(folio); 2256 } 2257 2258 static void mpage_submit_folio(struct mpage_da_data *mpd, struct folio *folio) 2259 { 2260 size_t len; 2261 loff_t size; 2262 2263 WARN_ON_ONCE(folio_pos(folio) != mpd->start_pos); 2264 folio_clear_dirty_for_io(folio); 2265 /* 2266 * We have to be very careful here! Nothing protects writeback path 2267 * against i_size changes and the page can be writeably mapped into 2268 * page tables. So an application can be growing i_size and writing 2269 * data through mmap while writeback runs. folio_clear_dirty_for_io() 2270 * write-protects our page in page tables and the page cannot get 2271 * written to again until we release folio lock. So only after 2272 * folio_clear_dirty_for_io() we are safe to sample i_size for 2273 * ext4_bio_write_folio() to zero-out tail of the written page. We rely 2274 * on the barrier provided by folio_test_clear_dirty() in 2275 * folio_clear_dirty_for_io() to make sure i_size is really sampled only 2276 * after page tables are updated. 2277 */ 2278 size = i_size_read(mpd->inode); 2279 len = folio_size(folio); 2280 if (folio_pos(folio) + len > size && 2281 !ext4_verity_in_progress(mpd->inode)) 2282 len = size & (len - 1); 2283 ext4_bio_write_folio(&mpd->io_submit, folio, len); 2284 } 2285 2286 #define BH_FLAGS (BIT(BH_Unwritten) | BIT(BH_Delay)) 2287 2288 /* 2289 * mballoc gives us at most this number of blocks... 2290 * XXX: That seems to be only a limitation of ext4_mb_normalize_request(). 2291 * The rest of mballoc seems to handle chunks up to full group size. 2292 */ 2293 #define MAX_WRITEPAGES_EXTENT_LEN 2048 2294 2295 /* 2296 * mpage_add_bh_to_extent - try to add bh to extent of blocks to map 2297 * 2298 * @mpd - extent of blocks 2299 * @lblk - logical number of the block in the file 2300 * @bh - buffer head we want to add to the extent 2301 * 2302 * The function is used to collect contig. blocks in the same state. If the 2303 * buffer doesn't require mapping for writeback and we haven't started the 2304 * extent of buffers to map yet, the function returns 'true' immediately - the 2305 * caller can write the buffer right away. Otherwise the function returns true 2306 * if the block has been added to the extent, false if the block couldn't be 2307 * added. 2308 */ 2309 static bool mpage_add_bh_to_extent(struct mpage_da_data *mpd, ext4_lblk_t lblk, 2310 struct buffer_head *bh) 2311 { 2312 struct ext4_map_blocks *map = &mpd->map; 2313 2314 /* Buffer that doesn't need mapping for writeback? */ 2315 if (!buffer_dirty(bh) || !buffer_mapped(bh) || 2316 (!buffer_delay(bh) && !buffer_unwritten(bh))) { 2317 /* So far no extent to map => we write the buffer right away */ 2318 if (map->m_len == 0) 2319 return true; 2320 return false; 2321 } 2322 2323 /* First block in the extent? */ 2324 if (map->m_len == 0) { 2325 /* We cannot map unless handle is started... */ 2326 if (!mpd->do_map) 2327 return false; 2328 map->m_lblk = lblk; 2329 map->m_len = 1; 2330 map->m_flags = bh->b_state & BH_FLAGS; 2331 return true; 2332 } 2333 2334 /* Don't go larger than mballoc is willing to allocate */ 2335 if (map->m_len >= MAX_WRITEPAGES_EXTENT_LEN) 2336 return false; 2337 2338 /* Can we merge the block to our big extent? */ 2339 if (lblk == map->m_lblk + map->m_len && 2340 (bh->b_state & BH_FLAGS) == map->m_flags) { 2341 map->m_len++; 2342 return true; 2343 } 2344 return false; 2345 } 2346 2347 /* 2348 * mpage_process_page_bufs - submit page buffers for IO or add them to extent 2349 * 2350 * @mpd - extent of blocks for mapping 2351 * @head - the first buffer in the page 2352 * @bh - buffer we should start processing from 2353 * @lblk - logical number of the block in the file corresponding to @bh 2354 * 2355 * Walk through page buffers from @bh up to @head (exclusive) and either submit 2356 * the page for IO if all buffers in this page were mapped and there's no 2357 * accumulated extent of buffers to map or add buffers in the page to the 2358 * extent of buffers to map. The function returns 1 if the caller can continue 2359 * by processing the next page, 0 if it should stop adding buffers to the 2360 * extent to map because we cannot extend it anymore. 2361 */ 2362 static int mpage_process_page_bufs(struct mpage_da_data *mpd, 2363 struct buffer_head *head, 2364 struct buffer_head *bh, 2365 ext4_lblk_t lblk) 2366 { 2367 struct inode *inode = mpd->inode; 2368 ext4_lblk_t blocks = (i_size_read(inode) + i_blocksize(inode) - 1) 2369 >> inode->i_blkbits; 2370 2371 if (ext4_verity_in_progress(inode)) 2372 blocks = EXT_MAX_BLOCKS; 2373 2374 do { 2375 BUG_ON(buffer_locked(bh)); 2376 2377 if (lblk >= blocks || !mpage_add_bh_to_extent(mpd, lblk, bh)) { 2378 /* Found extent to map? */ 2379 if (mpd->map.m_len) 2380 return 0; 2381 /* Buffer needs mapping and handle is not started? */ 2382 if (!mpd->do_map) 2383 return 0; 2384 /* Everything mapped so far and we hit EOF */ 2385 break; 2386 } 2387 } while (lblk++, (bh = bh->b_this_page) != head); 2388 /* So far everything mapped? Submit the page for IO. */ 2389 if (mpd->map.m_len == 0) { 2390 mpage_submit_folio(mpd, head->b_folio); 2391 mpage_folio_done(mpd, head->b_folio); 2392 } 2393 if (lblk >= blocks) { 2394 mpd->scanned_until_end = 1; 2395 return 0; 2396 } 2397 return 1; 2398 } 2399 2400 /* 2401 * mpage_process_folio - update folio buffers corresponding to changed extent 2402 * and may submit fully mapped page for IO 2403 * @mpd: description of extent to map, on return next extent to map 2404 * @folio: Contains these buffers. 2405 * @m_lblk: logical block mapping. 2406 * @m_pblk: corresponding physical mapping. 2407 * @map_bh: determines on return whether this page requires any further 2408 * mapping or not. 2409 * 2410 * Scan given folio buffers corresponding to changed extent and update buffer 2411 * state according to new extent state. 2412 * We map delalloc buffers to their physical location, clear unwritten bits. 2413 * If the given folio is not fully mapped, we update @mpd to the next extent in 2414 * the given folio that needs mapping & return @map_bh as true. 2415 */ 2416 static int mpage_process_folio(struct mpage_da_data *mpd, struct folio *folio, 2417 ext4_lblk_t *m_lblk, ext4_fsblk_t *m_pblk, 2418 bool *map_bh) 2419 { 2420 struct buffer_head *head, *bh; 2421 ext4_io_end_t *io_end = mpd->io_submit.io_end; 2422 ext4_lblk_t lblk = *m_lblk; 2423 ext4_fsblk_t pblock = *m_pblk; 2424 int err = 0; 2425 ssize_t io_end_size = 0; 2426 struct ext4_io_end_vec *io_end_vec = ext4_last_io_end_vec(io_end); 2427 2428 bh = head = folio_buffers(folio); 2429 do { 2430 if (lblk < mpd->map.m_lblk) 2431 continue; 2432 if (lblk >= mpd->map.m_lblk + mpd->map.m_len) { 2433 /* 2434 * Buffer after end of mapped extent. 2435 * Find next buffer in the folio to map. 2436 */ 2437 mpd->map.m_len = 0; 2438 mpd->map.m_flags = 0; 2439 io_end_vec->size += io_end_size; 2440 2441 err = mpage_process_page_bufs(mpd, head, bh, lblk); 2442 if (err > 0) 2443 err = 0; 2444 if (!err && mpd->map.m_len && mpd->map.m_lblk > lblk) { 2445 io_end_vec = ext4_alloc_io_end_vec(io_end); 2446 if (IS_ERR(io_end_vec)) { 2447 err = PTR_ERR(io_end_vec); 2448 goto out; 2449 } 2450 io_end_vec->offset = EXT4_LBLK_TO_B(mpd->inode, 2451 mpd->map.m_lblk); 2452 } 2453 *map_bh = true; 2454 goto out; 2455 } 2456 if (buffer_delay(bh)) { 2457 clear_buffer_delay(bh); 2458 bh->b_blocknr = pblock++; 2459 } 2460 clear_buffer_unwritten(bh); 2461 io_end_size += i_blocksize(mpd->inode); 2462 } while (lblk++, (bh = bh->b_this_page) != head); 2463 2464 io_end_vec->size += io_end_size; 2465 *map_bh = false; 2466 out: 2467 *m_lblk = lblk; 2468 *m_pblk = pblock; 2469 return err; 2470 } 2471 2472 /* 2473 * mpage_map_buffers - update buffers corresponding to changed extent and 2474 * submit fully mapped pages for IO 2475 * 2476 * @mpd - description of extent to map, on return next extent to map 2477 * 2478 * Scan buffers corresponding to changed extent (we expect corresponding pages 2479 * to be already locked) and update buffer state according to new extent state. 2480 * We map delalloc buffers to their physical location, clear unwritten bits, 2481 * and mark buffers as uninit when we perform writes to unwritten extents 2482 * and do extent conversion after IO is finished. If the last page is not fully 2483 * mapped, we update @map to the next extent in the last page that needs 2484 * mapping. Otherwise we submit the page for IO. 2485 */ 2486 static int mpage_map_and_submit_buffers(struct mpage_da_data *mpd) 2487 { 2488 struct folio_batch fbatch; 2489 unsigned nr, i; 2490 struct inode *inode = mpd->inode; 2491 pgoff_t start, end; 2492 ext4_lblk_t lblk; 2493 ext4_fsblk_t pblock; 2494 int err; 2495 bool map_bh = false; 2496 2497 start = EXT4_LBLK_TO_PG(inode, mpd->map.m_lblk); 2498 end = EXT4_LBLK_TO_PG(inode, mpd->map.m_lblk + mpd->map.m_len - 1); 2499 pblock = mpd->map.m_pblk; 2500 2501 folio_batch_init(&fbatch); 2502 while (start <= end) { 2503 nr = filemap_get_folios(inode->i_mapping, &start, end, &fbatch); 2504 if (nr == 0) 2505 break; 2506 for (i = 0; i < nr; i++) { 2507 struct folio *folio = fbatch.folios[i]; 2508 2509 lblk = EXT4_PG_TO_LBLK(inode, folio->index); 2510 err = mpage_process_folio(mpd, folio, &lblk, &pblock, 2511 &map_bh); 2512 /* 2513 * If map_bh is true, means page may require further bh 2514 * mapping, or maybe the page was submitted for IO. 2515 * So we return to call further extent mapping. 2516 */ 2517 if (err < 0 || map_bh) 2518 goto out; 2519 /* Page fully mapped - let IO run! */ 2520 mpage_submit_folio(mpd, folio); 2521 mpage_folio_done(mpd, folio); 2522 } 2523 folio_batch_release(&fbatch); 2524 } 2525 /* Extent fully mapped and matches with page boundary. We are done. */ 2526 mpd->map.m_len = 0; 2527 mpd->map.m_flags = 0; 2528 return 0; 2529 out: 2530 folio_batch_release(&fbatch); 2531 return err; 2532 } 2533 2534 static int mpage_map_one_extent(handle_t *handle, struct mpage_da_data *mpd) 2535 { 2536 struct inode *inode = mpd->inode; 2537 struct ext4_map_blocks *map = &mpd->map; 2538 int get_blocks_flags; 2539 int err, dioread_nolock; 2540 2541 /* Make sure transaction has enough credits for this extent */ 2542 err = ext4_journal_ensure_extent_credits(handle, inode); 2543 if (err < 0) 2544 return err; 2545 2546 trace_ext4_da_write_pages_extent(inode, map); 2547 /* 2548 * Call ext4_map_blocks() to allocate any delayed allocation blocks, or 2549 * to convert an unwritten extent to be initialized (in the case 2550 * where we have written into one or more preallocated blocks). It is 2551 * possible that we're going to need more metadata blocks than 2552 * previously reserved. However we must not fail because we're in 2553 * writeback and there is nothing we can do about it so it might result 2554 * in data loss. So use reserved blocks to allocate metadata if 2555 * possible. In addition, do not cache any unrelated extents, as it 2556 * only holds the folio lock but does not hold the i_rwsem or 2557 * invalidate_lock, which could corrupt the extent status tree. 2558 */ 2559 get_blocks_flags = EXT4_GET_BLOCKS_CREATE | 2560 EXT4_GET_BLOCKS_METADATA_NOFAIL | 2561 EXT4_GET_BLOCKS_IO_SUBMIT | 2562 EXT4_EX_NOCACHE; 2563 2564 dioread_nolock = ext4_should_dioread_nolock(inode); 2565 if (dioread_nolock) 2566 get_blocks_flags |= EXT4_GET_BLOCKS_UNWRIT_EXT; 2567 2568 err = ext4_map_blocks(handle, inode, map, get_blocks_flags); 2569 if (err < 0) 2570 return err; 2571 /* 2572 * A hole? This should never happen since mpage_add_bh_to_extent() 2573 * has filtered it out. 2574 */ 2575 if (WARN_ON_ONCE(!err)) 2576 return -EINVAL; 2577 if (dioread_nolock && (map->m_flags & EXT4_MAP_UNWRITTEN)) { 2578 if (!mpd->io_submit.io_end->handle && 2579 ext4_handle_valid(handle)) { 2580 mpd->io_submit.io_end->handle = handle->h_rsv_handle; 2581 handle->h_rsv_handle = NULL; 2582 } 2583 ext4_set_io_unwritten_flag(mpd->io_submit.io_end); 2584 } 2585 2586 BUG_ON(map->m_len == 0); 2587 return 0; 2588 } 2589 2590 /* 2591 * This is used to submit mapped buffers in a single folio that is not fully 2592 * mapped for various reasons, such as insufficient space or journal credits. 2593 */ 2594 static int mpage_submit_partial_folio(struct mpage_da_data *mpd) 2595 { 2596 struct inode *inode = mpd->inode; 2597 struct folio *folio; 2598 loff_t pos; 2599 2600 folio = filemap_get_folio(inode->i_mapping, 2601 mpd->start_pos >> PAGE_SHIFT); 2602 if (IS_ERR(folio)) 2603 return PTR_ERR(folio); 2604 /* 2605 * The mapped position should be within the current processing folio 2606 * but must not be the folio start position. 2607 */ 2608 pos = ((loff_t)mpd->map.m_lblk) << inode->i_blkbits; 2609 if (WARN_ON_ONCE((folio_pos(folio) == pos) || 2610 !folio_contains(folio, pos >> PAGE_SHIFT))) { 2611 /* 2612 * Leave the folio locked so that the caller can invalidate 2613 * and unlock it through mpage_release_unused_pages(). 2614 */ 2615 folio_put(folio); 2616 return -EINVAL; 2617 } 2618 2619 mpage_submit_folio(mpd, folio); 2620 /* 2621 * Update start_pos to prevent this folio from being released in 2622 * mpage_release_unused_pages(), it will be reset to the aligned folio 2623 * pos when this folio is written again in the next round. Additionally, 2624 * do not update wbc->nr_to_write here, as it will be updated once the 2625 * entire folio has finished processing. 2626 */ 2627 mpd->start_pos = pos; 2628 folio_unlock(folio); 2629 folio_put(folio); 2630 return 0; 2631 } 2632 2633 /* 2634 * mpage_map_and_submit_extent - map extent starting at mpd->lblk of length 2635 * mpd->len and submit pages underlying it for IO 2636 * 2637 * @handle - handle for journal operations 2638 * @mpd - extent to map 2639 * @give_up_on_write - we set this to true iff there is a fatal error and there 2640 * is no hope of writing the data. The caller should discard 2641 * dirty pages to avoid infinite loops. 2642 * 2643 * The function maps extent starting at mpd->lblk of length mpd->len. If it is 2644 * delayed, blocks are allocated, if it is unwritten, we may need to convert 2645 * them to initialized or split the described range from larger unwritten 2646 * extent. Note that we need not map all the described range since allocation 2647 * can return less blocks or the range is covered by more unwritten extents. We 2648 * cannot map more because we are limited by reserved transaction credits. On 2649 * the other hand we always make sure that the last touched page is fully 2650 * mapped so that it can be written out (and thus forward progress is 2651 * guaranteed). After mapping we submit all mapped pages for IO. 2652 */ 2653 static int mpage_map_and_submit_extent(handle_t *handle, 2654 struct mpage_da_data *mpd, 2655 bool *give_up_on_write) 2656 { 2657 struct inode *inode = mpd->inode; 2658 struct ext4_map_blocks *map = &mpd->map; 2659 int err; 2660 loff_t disksize; 2661 int progress = 0; 2662 ext4_io_end_t *io_end = mpd->io_submit.io_end; 2663 struct ext4_io_end_vec *io_end_vec; 2664 2665 io_end_vec = ext4_alloc_io_end_vec(io_end); 2666 if (IS_ERR(io_end_vec)) 2667 return PTR_ERR(io_end_vec); 2668 io_end_vec->offset = EXT4_LBLK_TO_B(inode, map->m_lblk); 2669 do { 2670 err = mpage_map_one_extent(handle, mpd); 2671 if (err < 0) { 2672 struct super_block *sb = inode->i_sb; 2673 2674 if (ext4_emergency_state(sb)) 2675 goto invalidate_dirty_pages; 2676 /* 2677 * Let the uper layers retry transient errors. 2678 * In the case of ENOSPC, if ext4_count_free_blocks() 2679 * is non-zero, a commit should free up blocks. 2680 */ 2681 if ((err == -ENOMEM) || (err == -EAGAIN) || 2682 (err == -ENOSPC && ext4_count_free_clusters(sb))) { 2683 /* 2684 * We may have already allocated extents for 2685 * some bhs inside the folio, issue the 2686 * corresponding data to prevent stale data. 2687 */ 2688 if (progress) { 2689 if (mpage_submit_partial_folio(mpd)) 2690 goto invalidate_dirty_pages; 2691 goto update_disksize; 2692 } 2693 return err; 2694 } 2695 ext4_msg(sb, KERN_CRIT, 2696 "Delayed block allocation failed for " 2697 "inode %llu at logical offset %llu with" 2698 " max blocks %u with error %d", 2699 inode->i_ino, 2700 (unsigned long long)map->m_lblk, 2701 (unsigned)map->m_len, -err); 2702 ext4_msg(sb, KERN_CRIT, 2703 "This should not happen!! Data will " 2704 "be lost\n"); 2705 if (err == -ENOSPC) 2706 ext4_print_free_blocks(inode); 2707 invalidate_dirty_pages: 2708 *give_up_on_write = true; 2709 /* 2710 * Record the error so that a subsequent fsync() 2711 * / errseq check can observe the data loss that 2712 * discarding these dirty pages implies. 2713 */ 2714 mapping_set_error(inode->i_mapping, err); 2715 return err; 2716 } 2717 progress = 1; 2718 /* 2719 * Update buffer state, submit mapped pages, and get us new 2720 * extent to map 2721 */ 2722 err = mpage_map_and_submit_buffers(mpd); 2723 if (err < 0) 2724 goto update_disksize; 2725 } while (map->m_len); 2726 2727 update_disksize: 2728 /* 2729 * Update on-disk size after IO is submitted. Races with 2730 * truncate are avoided by checking i_size under i_data_sem. 2731 */ 2732 disksize = mpd->start_pos; 2733 if (disksize > READ_ONCE(EXT4_I(inode)->i_disksize)) { 2734 int err2; 2735 loff_t i_size; 2736 2737 down_write(&EXT4_I(inode)->i_data_sem); 2738 i_size = i_size_read(inode); 2739 if (disksize > i_size) 2740 disksize = i_size; 2741 if (disksize > EXT4_I(inode)->i_disksize) 2742 EXT4_I(inode)->i_disksize = disksize; 2743 up_write(&EXT4_I(inode)->i_data_sem); 2744 err2 = ext4_mark_inode_dirty(handle, inode); 2745 if (err2) { 2746 ext4_error_err(inode->i_sb, -err2, 2747 "Failed to mark inode %llu dirty", 2748 inode->i_ino); 2749 } 2750 if (!err) 2751 err = err2; 2752 } 2753 return err; 2754 } 2755 2756 static int ext4_journal_folio_buffers(handle_t *handle, struct folio *folio, 2757 size_t len) 2758 { 2759 struct buffer_head *page_bufs = folio_buffers(folio); 2760 struct inode *inode = folio->mapping->host; 2761 int ret, err; 2762 2763 ret = ext4_walk_page_buffers(handle, inode, page_bufs, 0, len, 2764 NULL, do_journal_get_write_access); 2765 err = ext4_walk_page_buffers(handle, inode, page_bufs, 0, len, 2766 NULL, write_end_fn); 2767 if (ret == 0) 2768 ret = err; 2769 err = ext4_jbd2_inode_add_write(handle, inode, folio_pos(folio), len); 2770 if (ret == 0) 2771 ret = err; 2772 EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid; 2773 2774 return ret; 2775 } 2776 2777 static int mpage_journal_page_buffers(handle_t *handle, 2778 struct mpage_da_data *mpd, 2779 struct folio *folio) 2780 { 2781 struct inode *inode = mpd->inode; 2782 loff_t size = i_size_read(inode); 2783 size_t len = folio_size(folio); 2784 2785 folio_clear_checked(folio); 2786 mpd->wbc->nr_to_write -= folio_nr_pages(folio); 2787 2788 if (folio_pos(folio) + len > size && 2789 !ext4_verity_in_progress(inode)) 2790 len = size & (len - 1); 2791 2792 return ext4_journal_folio_buffers(handle, folio, len); 2793 } 2794 2795 /* 2796 * mpage_prepare_extent_to_map - find & lock contiguous range of dirty pages 2797 * needing mapping, submit mapped pages 2798 * 2799 * @mpd - where to look for pages 2800 * 2801 * Walk dirty pages in the mapping. If they are fully mapped, submit them for 2802 * IO immediately. If we cannot map blocks, we submit just already mapped 2803 * buffers in the page for IO and keep page dirty. When we can map blocks and 2804 * we find a page which isn't mapped we start accumulating extent of buffers 2805 * underlying these pages that needs mapping (formed by either delayed or 2806 * unwritten buffers). We also lock the pages containing these buffers. The 2807 * extent found is returned in @mpd structure (starting at mpd->lblk with 2808 * length mpd->len blocks). 2809 * 2810 * Note that this function can attach bios to one io_end structure which are 2811 * neither logically nor physically contiguous. Although it may seem as an 2812 * unnecessary complication, it is actually inevitable in blocksize < pagesize 2813 * case as we need to track IO to all buffers underlying a page in one io_end. 2814 */ 2815 static int mpage_prepare_extent_to_map(struct mpage_da_data *mpd) 2816 { 2817 struct address_space *mapping = mpd->inode->i_mapping; 2818 struct folio_batch fbatch; 2819 unsigned int nr_folios; 2820 pgoff_t index = mpd->start_pos >> PAGE_SHIFT; 2821 pgoff_t end = mpd->end_pos >> PAGE_SHIFT; 2822 xa_mark_t tag; 2823 int i, err = 0; 2824 ext4_lblk_t lblk; 2825 struct buffer_head *head; 2826 handle_t *handle = NULL; 2827 int bpp = ext4_journal_blocks_per_folio(mpd->inode); 2828 2829 tag = wbc_to_tag(mpd->wbc); 2830 2831 mpd->map.m_len = 0; 2832 mpd->next_pos = mpd->start_pos; 2833 if (ext4_should_journal_data(mpd->inode)) { 2834 handle = ext4_journal_start(mpd->inode, EXT4_HT_WRITE_PAGE, 2835 bpp); 2836 if (IS_ERR(handle)) 2837 return PTR_ERR(handle); 2838 } 2839 folio_batch_init(&fbatch); 2840 while (index <= end) { 2841 nr_folios = filemap_get_folios_tag(mapping, &index, end, 2842 tag, &fbatch); 2843 if (nr_folios == 0) 2844 break; 2845 2846 for (i = 0; i < nr_folios; i++) { 2847 struct folio *folio = fbatch.folios[i]; 2848 2849 /* 2850 * Accumulated enough dirty pages? This doesn't apply 2851 * to WB_SYNC_ALL mode. For integrity sync we have to 2852 * keep going because someone may be concurrently 2853 * dirtying pages, and we might have synced a lot of 2854 * newly appeared dirty pages, but have not synced all 2855 * of the old dirty pages. 2856 */ 2857 if (mpd->wbc->sync_mode == WB_SYNC_NONE && 2858 mpd->wbc->nr_to_write <= 2859 EXT4_LBLK_TO_PG(mpd->inode, mpd->map.m_len)) 2860 goto out; 2861 2862 /* If we can't merge this page, we are done. */ 2863 if (mpd->map.m_len > 0 && 2864 mpd->next_pos != folio_pos(folio)) 2865 goto out; 2866 2867 if (handle) { 2868 err = ext4_journal_ensure_credits(handle, bpp, 2869 0); 2870 if (err < 0) 2871 goto out; 2872 } 2873 2874 folio_lock(folio); 2875 /* 2876 * If the page is no longer dirty, or its mapping no 2877 * longer corresponds to inode we are writing (which 2878 * means it has been truncated or invalidated), or the 2879 * page is already under writeback and we are not doing 2880 * a data integrity writeback, skip the page 2881 */ 2882 if ((folio_test_writeback(folio) && 2883 mpd->wbc->sync_mode == WB_SYNC_NONE) || 2884 unlikely(folio->mapping != mapping)) { 2885 folio_unlock(folio); 2886 continue; 2887 } 2888 /* 2889 * If the folio is clean, skip writing it back. 2890 * Cycle the folio through the writeback state 2891 * though, to clear stale xarray tags. 2892 */ 2893 if (!folio_test_dirty(folio)) { 2894 if (!folio_test_writeback(folio)) { 2895 __folio_start_writeback(folio, false); 2896 folio_end_writeback(folio); 2897 } 2898 folio_unlock(folio); 2899 continue; 2900 } 2901 2902 folio_wait_writeback(folio); 2903 BUG_ON(folio_test_writeback(folio)); 2904 2905 /* 2906 * Should never happen but for buggy code in 2907 * other subsystems that call 2908 * set_page_dirty() without properly warning 2909 * the file system first. See [1] for more 2910 * information. 2911 * 2912 * [1] https://lore.kernel.org/linux-mm/20180103100430.GE4911@quack2.suse.cz 2913 */ 2914 if (!folio_buffers(folio)) { 2915 ext4_warning_inode(mpd->inode, "page %lu does not have buffers attached", folio->index); 2916 folio_clear_dirty(folio); 2917 folio_unlock(folio); 2918 continue; 2919 } 2920 2921 if (mpd->map.m_len == 0) 2922 mpd->start_pos = folio_pos(folio); 2923 mpd->next_pos = folio_next_pos(folio); 2924 /* 2925 * Writeout when we cannot modify metadata is simple. 2926 * Just submit the page. For data=journal mode we 2927 * first handle writeout of the page for checkpoint and 2928 * only after that handle delayed page dirtying. This 2929 * makes sure current data is checkpointed to the final 2930 * location before possibly journalling it again which 2931 * is desirable when the page is frequently dirtied 2932 * through a pin. 2933 */ 2934 if (!mpd->can_map) { 2935 mpage_submit_folio(mpd, folio); 2936 err = 0; 2937 /* Pending dirtying of journalled data? */ 2938 if (folio_test_checked(folio)) { 2939 err = mpage_journal_page_buffers(handle, 2940 mpd, folio); 2941 if (err < 0) 2942 goto out; 2943 mpd->journalled_more_data = 1; 2944 } 2945 mpage_folio_done(mpd, folio); 2946 } else { 2947 /* Add all dirty buffers to mpd */ 2948 lblk = EXT4_PG_TO_LBLK(mpd->inode, folio->index); 2949 head = folio_buffers(folio); 2950 err = mpage_process_page_bufs(mpd, head, head, 2951 lblk); 2952 if (err <= 0) 2953 goto out; 2954 err = 0; 2955 } 2956 } 2957 folio_batch_release(&fbatch); 2958 cond_resched(); 2959 } 2960 mpd->scanned_until_end = 1; 2961 if (handle) 2962 ext4_journal_stop(handle); 2963 return 0; 2964 out: 2965 folio_batch_release(&fbatch); 2966 if (handle) 2967 ext4_journal_stop(handle); 2968 return err; 2969 } 2970 2971 static int ext4_do_writepages(struct mpage_da_data *mpd) 2972 { 2973 struct writeback_control *wbc = mpd->wbc; 2974 pgoff_t writeback_index = 0; 2975 long nr_to_write = wbc->nr_to_write; 2976 int range_whole = 0; 2977 int cycled = 1; 2978 handle_t *handle = NULL; 2979 struct inode *inode = mpd->inode; 2980 struct address_space *mapping = inode->i_mapping; 2981 int needed_blocks, rsv_blocks = 0, ret = 0; 2982 struct ext4_sb_info *sbi = EXT4_SB(mapping->host->i_sb); 2983 struct blk_plug plug; 2984 2985 trace_ext4_writepages(inode, wbc); 2986 2987 /* 2988 * No pages to write? This is mainly a kludge to avoid starting 2989 * a transaction for special inodes like journal inode on last iput() 2990 * because that could violate lock ordering on umount 2991 */ 2992 if (!mapping->nrpages || !mapping_tagged(mapping, PAGECACHE_TAG_DIRTY)) 2993 goto out_writepages; 2994 2995 /* 2996 * Does ext4_change_inode_journal_flag() change the inode's 2997 * buffered I/O path? 2998 */ 2999 if (ext4_inode_buffered_iomap(inode)) 3000 goto out_writepages; 3001 3002 /* 3003 * If the filesystem has aborted, it is read-only, so return 3004 * right away instead of dumping stack traces later on that 3005 * will obscure the real source of the problem. We test 3006 * fs shutdown state instead of sb->s_flag's SB_RDONLY because 3007 * the latter could be true if the filesystem is mounted 3008 * read-only, and in that case, ext4_writepages should 3009 * *never* be called, so if that ever happens, we would want 3010 * the stack trace. 3011 */ 3012 ret = ext4_emergency_state(mapping->host->i_sb); 3013 if (unlikely(ret)) 3014 goto out_writepages; 3015 3016 /* 3017 * If we have inline data and arrive here, it means that 3018 * we will soon create the block for the 1st page, so 3019 * we'd better clear the inline data here. 3020 */ 3021 if (ext4_has_inline_data(inode)) { 3022 /* Just inode will be modified... */ 3023 handle = ext4_journal_start(inode, EXT4_HT_INODE, 1); 3024 if (IS_ERR(handle)) { 3025 ret = PTR_ERR(handle); 3026 goto out_writepages; 3027 } 3028 BUG_ON(ext4_test_inode_state(inode, 3029 EXT4_STATE_MAY_INLINE_DATA)); 3030 ext4_destroy_inline_data(handle, inode); 3031 ext4_journal_stop(handle); 3032 } 3033 3034 /* 3035 * data=journal mode does not do delalloc so we just need to writeout / 3036 * journal already mapped buffers. On the other hand we need to commit 3037 * transaction to make data stable. We expect all the data to be 3038 * already in the journal (the only exception are DMA pinned pages 3039 * dirtied behind our back) so we commit transaction here and run the 3040 * writeback loop to checkpoint them. The checkpointing is not actually 3041 * necessary to make data persistent *but* quite a few places (extent 3042 * shifting operations, fsverity, ...) depend on being able to drop 3043 * pagecache pages after calling filemap_write_and_wait() and for that 3044 * checkpointing needs to happen. 3045 */ 3046 if (ext4_should_journal_data(inode)) { 3047 mpd->can_map = 0; 3048 if (wbc->sync_mode == WB_SYNC_ALL) 3049 ext4_fc_commit(sbi->s_journal, 3050 EXT4_I(inode)->i_datasync_tid); 3051 } 3052 mpd->journalled_more_data = 0; 3053 3054 if (ext4_should_dioread_nolock(inode)) { 3055 int bpf = ext4_journal_blocks_per_folio(inode); 3056 /* 3057 * We may need to convert up to one extent per block in the 3058 * folio. 3059 */ 3060 rsv_blocks = ext4_meta_trans_blocks(inode, bpf, bpf, 0); 3061 } 3062 3063 if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX) 3064 range_whole = 1; 3065 3066 if (wbc->range_cyclic) { 3067 writeback_index = mapping->writeback_index; 3068 if (writeback_index) 3069 cycled = 0; 3070 mpd->start_pos = writeback_index << PAGE_SHIFT; 3071 mpd->end_pos = LLONG_MAX; 3072 } else { 3073 mpd->start_pos = wbc->range_start; 3074 mpd->end_pos = wbc->range_end; 3075 } 3076 3077 ext4_io_submit_init(&mpd->io_submit, wbc); 3078 retry: 3079 if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages) 3080 tag_pages_for_writeback(mapping, mpd->start_pos >> PAGE_SHIFT, 3081 mpd->end_pos >> PAGE_SHIFT); 3082 blk_start_plug(&plug); 3083 3084 /* 3085 * First writeback pages that don't need mapping - we can avoid 3086 * starting a transaction unnecessarily and also avoid being blocked 3087 * in the block layer on device congestion while having transaction 3088 * started. 3089 */ 3090 mpd->do_map = 0; 3091 mpd->scanned_until_end = 0; 3092 mpd->io_submit.io_end = ext4_init_io_end(inode, GFP_KERNEL); 3093 if (!mpd->io_submit.io_end) { 3094 ret = -ENOMEM; 3095 goto unplug; 3096 } 3097 ret = mpage_prepare_extent_to_map(mpd); 3098 /* Unlock pages we didn't use */ 3099 mpage_release_unused_pages(mpd, false); 3100 /* Submit prepared bio */ 3101 ext4_io_submit(&mpd->io_submit); 3102 ext4_put_io_end_defer(mpd->io_submit.io_end); 3103 mpd->io_submit.io_end = NULL; 3104 if (ret < 0) 3105 goto unplug; 3106 3107 while (!mpd->scanned_until_end && wbc->nr_to_write > 0) { 3108 bool give_up_on_write = false; 3109 3110 /* For each extent of pages we use new io_end */ 3111 mpd->io_submit.io_end = ext4_init_io_end(inode, GFP_KERNEL); 3112 if (!mpd->io_submit.io_end) { 3113 ret = -ENOMEM; 3114 break; 3115 } 3116 3117 WARN_ON_ONCE(!mpd->can_map); 3118 /* 3119 * We have two constraints: We find one extent to map and we 3120 * must always write out whole page (makes a difference when 3121 * blocksize < pagesize) so that we don't block on IO when we 3122 * try to write out the rest of the page. Journalled mode is 3123 * not supported by delalloc. 3124 */ 3125 BUG_ON(ext4_should_journal_data(inode)); 3126 /* 3127 * Calculate the number of credits needed to reserve for one 3128 * extent of up to MAX_WRITEPAGES_EXTENT_LEN blocks. It will 3129 * attempt to extend the transaction or start a new iteration 3130 * if the reserved credits are insufficient. 3131 */ 3132 needed_blocks = ext4_chunk_trans_blocks(inode, 3133 MAX_WRITEPAGES_EXTENT_LEN); 3134 /* start a new transaction */ 3135 handle = ext4_journal_start_with_reserve(inode, 3136 EXT4_HT_WRITE_PAGE, needed_blocks, rsv_blocks); 3137 if (IS_ERR(handle)) { 3138 ret = PTR_ERR(handle); 3139 ext4_msg(inode->i_sb, KERN_CRIT, "%s: jbd2_start: " 3140 "%ld pages, ino %llu; err %d", __func__, 3141 wbc->nr_to_write, inode->i_ino, ret); 3142 /* Release allocated io_end */ 3143 ext4_put_io_end(mpd->io_submit.io_end); 3144 mpd->io_submit.io_end = NULL; 3145 break; 3146 } 3147 mpd->do_map = 1; 3148 3149 trace_ext4_da_write_folios_start(inode, mpd->start_pos, 3150 mpd->next_pos, wbc); 3151 ret = mpage_prepare_extent_to_map(mpd); 3152 if (!ret && mpd->map.m_len) 3153 ret = mpage_map_and_submit_extent(handle, mpd, 3154 &give_up_on_write); 3155 /* 3156 * Caution: If the handle is synchronous, 3157 * ext4_journal_stop() can wait for transaction commit 3158 * to finish which may depend on writeback of pages to 3159 * complete or on page lock to be released. In that 3160 * case, we have to wait until after we have 3161 * submitted all the IO, released page locks we hold, 3162 * and dropped io_end reference (for extent conversion 3163 * to be able to complete) before stopping the handle. 3164 */ 3165 if (!ext4_handle_valid(handle) || handle->h_sync == 0) { 3166 ext4_journal_stop(handle); 3167 handle = NULL; 3168 mpd->do_map = 0; 3169 } 3170 /* Unlock pages we didn't use */ 3171 mpage_release_unused_pages(mpd, give_up_on_write); 3172 /* Submit prepared bio */ 3173 ext4_io_submit(&mpd->io_submit); 3174 3175 /* 3176 * Drop our io_end reference we got from init. We have 3177 * to be careful and use deferred io_end finishing if 3178 * we are still holding the transaction as we can 3179 * release the last reference to io_end which may end 3180 * up doing unwritten extent conversion. 3181 */ 3182 if (handle) { 3183 ext4_put_io_end_defer(mpd->io_submit.io_end); 3184 ext4_journal_stop(handle); 3185 } else 3186 ext4_put_io_end(mpd->io_submit.io_end); 3187 mpd->io_submit.io_end = NULL; 3188 trace_ext4_da_write_folios_end(inode, mpd->start_pos, 3189 mpd->next_pos, wbc, ret); 3190 3191 if (ret == -ENOSPC && sbi->s_journal) { 3192 /* 3193 * Commit the transaction which would 3194 * free blocks released in the transaction 3195 * and try again 3196 */ 3197 jbd2_journal_force_commit_nested(sbi->s_journal); 3198 ret = 0; 3199 continue; 3200 } 3201 if (ret == -EAGAIN) 3202 ret = 0; 3203 /* Fatal error - ENOMEM, EIO... */ 3204 if (ret) 3205 break; 3206 } 3207 unplug: 3208 blk_finish_plug(&plug); 3209 if (!ret && !cycled && wbc->nr_to_write > 0) { 3210 cycled = 1; 3211 mpd->end_pos = (writeback_index << PAGE_SHIFT) - 1; 3212 mpd->start_pos = 0; 3213 goto retry; 3214 } 3215 3216 /* Update index */ 3217 if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0)) 3218 /* 3219 * Set the writeback_index so that range_cyclic 3220 * mode will write it back later 3221 */ 3222 mapping->writeback_index = mpd->start_pos >> PAGE_SHIFT; 3223 3224 out_writepages: 3225 trace_ext4_writepages_result(inode, wbc, ret, 3226 nr_to_write - wbc->nr_to_write); 3227 return ret; 3228 } 3229 3230 static int ext4_writepages(struct address_space *mapping, 3231 struct writeback_control *wbc) 3232 { 3233 struct super_block *sb = mapping->host->i_sb; 3234 struct mpage_da_data mpd = { 3235 .inode = mapping->host, 3236 .wbc = wbc, 3237 .can_map = 1, 3238 }; 3239 int ret; 3240 int alloc_ctx; 3241 3242 ret = ext4_emergency_state(sb); 3243 if (unlikely(ret)) 3244 return ret; 3245 3246 alloc_ctx = ext4_writepages_down_read(sb); 3247 ret = ext4_do_writepages(&mpd); 3248 /* 3249 * For data=journal writeback we could have come across pages marked 3250 * for delayed dirtying (PageChecked) which were just added to the 3251 * running transaction. Try once more to get them to stable storage. 3252 */ 3253 if (!ret && mpd.journalled_more_data) 3254 ret = ext4_do_writepages(&mpd); 3255 ext4_writepages_up_read(sb, alloc_ctx); 3256 3257 return ret; 3258 } 3259 3260 int ext4_normal_submit_inode_data_buffers(struct jbd2_inode *jinode) 3261 { 3262 loff_t range_start, range_end; 3263 struct writeback_control wbc = { 3264 .sync_mode = WB_SYNC_ALL, 3265 .nr_to_write = LONG_MAX, 3266 }; 3267 struct mpage_da_data mpd = { 3268 .inode = jinode->i_vfs_inode, 3269 .wbc = &wbc, 3270 .can_map = 0, 3271 }; 3272 3273 if (!jbd2_jinode_get_dirty_range(jinode, &range_start, &range_end)) 3274 return 0; 3275 3276 wbc.range_start = range_start; 3277 wbc.range_end = range_end; 3278 3279 return ext4_do_writepages(&mpd); 3280 } 3281 3282 static int ext4_dax_writepages(struct address_space *mapping, 3283 struct writeback_control *wbc) 3284 { 3285 int ret; 3286 long nr_to_write = wbc->nr_to_write; 3287 struct inode *inode = mapping->host; 3288 int alloc_ctx; 3289 3290 ret = ext4_emergency_state(inode->i_sb); 3291 if (unlikely(ret)) 3292 return ret; 3293 3294 alloc_ctx = ext4_writepages_down_read(inode->i_sb); 3295 trace_ext4_writepages(inode, wbc); 3296 3297 ret = dax_writeback_mapping_range(mapping, 3298 EXT4_SB(inode->i_sb)->s_daxdev, wbc); 3299 trace_ext4_writepages_result(inode, wbc, ret, 3300 nr_to_write - wbc->nr_to_write); 3301 ext4_writepages_up_read(inode->i_sb, alloc_ctx); 3302 return ret; 3303 } 3304 3305 int ext4_nonda_switch(struct super_block *sb) 3306 { 3307 s64 free_clusters, dirty_clusters; 3308 struct ext4_sb_info *sbi = EXT4_SB(sb); 3309 3310 /* 3311 * switch to non delalloc mode if we are running low 3312 * on free block. The free block accounting via percpu 3313 * counters can get slightly wrong with percpu_counter_batch getting 3314 * accumulated on each CPU without updating global counters 3315 * Delalloc need an accurate free block accounting. So switch 3316 * to non delalloc when we are near to error range. 3317 */ 3318 free_clusters = 3319 percpu_counter_read_positive(&sbi->s_freeclusters_counter); 3320 dirty_clusters = 3321 percpu_counter_read_positive(&sbi->s_dirtyclusters_counter); 3322 /* 3323 * Start pushing delalloc when 1/2 of free blocks are dirty. 3324 */ 3325 if (dirty_clusters && (free_clusters < 2 * dirty_clusters)) 3326 try_to_writeback_inodes_sb(sb, WB_REASON_FS_FREE_SPACE); 3327 3328 if (2 * free_clusters < 3 * dirty_clusters || 3329 free_clusters < (dirty_clusters + EXT4_FREECLUSTERS_WATERMARK)) { 3330 /* 3331 * free block count is less than 150% of dirty blocks 3332 * or free blocks is less than watermark 3333 */ 3334 return 1; 3335 } 3336 return 0; 3337 } 3338 3339 static int ext4_da_write_begin(const struct kiocb *iocb, 3340 struct address_space *mapping, 3341 loff_t pos, unsigned len, 3342 struct folio **foliop, void **fsdata) 3343 { 3344 int ret, retries = 0; 3345 struct folio *folio; 3346 pgoff_t index; 3347 struct inode *inode = mapping->host; 3348 3349 ret = ext4_emergency_state(inode->i_sb); 3350 if (unlikely(ret)) 3351 return ret; 3352 3353 index = pos >> PAGE_SHIFT; 3354 3355 if (ext4_nonda_switch(inode->i_sb) || ext4_verity_in_progress(inode)) { 3356 *fsdata = (void *)FALL_BACK_TO_NONDELALLOC; 3357 return ext4_write_begin(iocb, mapping, pos, 3358 len, foliop, fsdata); 3359 } 3360 *fsdata = (void *)0; 3361 trace_ext4_da_write_begin(inode, pos, len); 3362 3363 if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) { 3364 ret = ext4_generic_write_inline_data(mapping, inode, pos, len, 3365 foliop, true); 3366 if (ret < 0) 3367 return ret; 3368 if (ret == 1) { 3369 *fsdata = (void *)((unsigned long)*fsdata | EXT4_WRITE_DATA_INLINE); 3370 return 0; 3371 } 3372 } 3373 3374 retry: 3375 folio = write_begin_get_folio(iocb, mapping, index, len); 3376 if (IS_ERR(folio)) 3377 return PTR_ERR(folio); 3378 3379 if (len > folio_next_pos(folio) - pos) 3380 len = folio_next_pos(folio) - pos; 3381 3382 ret = ext4_block_write_begin(NULL, folio, pos, len, 3383 ext4_da_get_block_prep); 3384 if (ret < 0) { 3385 folio_unlock(folio); 3386 folio_put(folio); 3387 /* 3388 * ext4_block_write_begin may have instantiated a few blocks 3389 * outside i_size. Trim these off again. Don't need 3390 * i_size_read because we hold inode lock. 3391 */ 3392 if (pos + len > inode->i_size) 3393 ext4_truncate_failed_write(inode); 3394 3395 if (ret == -ENOSPC && 3396 ext4_should_retry_alloc(inode->i_sb, &retries)) 3397 goto retry; 3398 return ret; 3399 } 3400 3401 *foliop = folio; 3402 return ret; 3403 } 3404 3405 /* 3406 * Check if we should update i_disksize 3407 * when write to the end of file but not require block allocation 3408 */ 3409 static int ext4_da_should_update_i_disksize(struct folio *folio, 3410 unsigned long offset) 3411 { 3412 struct buffer_head *bh; 3413 struct inode *inode = folio->mapping->host; 3414 unsigned int idx; 3415 int i; 3416 3417 bh = folio_buffers(folio); 3418 idx = offset >> inode->i_blkbits; 3419 3420 for (i = 0; i < idx; i++) 3421 bh = bh->b_this_page; 3422 3423 if (!buffer_mapped(bh) || (buffer_delay(bh)) || buffer_unwritten(bh)) 3424 return 0; 3425 return 1; 3426 } 3427 3428 /* 3429 * Delalloc counterpart of ext4_truncate_failed_write(): ->write_begin() only 3430 * reserved delayed blocks, so drop the page cache and the delayed extents 3431 * beyond i_size and leave the blocks that are allocated there alone. 3432 */ 3433 static void ext4_da_truncate_failed_write(struct inode *inode) 3434 { 3435 struct address_space *mapping = inode->i_mapping; 3436 ext4_lblk_t lblk = EXT4_B_TO_LBLK(inode, inode->i_size); 3437 3438 filemap_invalidate_lock(mapping); 3439 truncate_inode_pages(mapping, inode->i_size); 3440 down_write(&EXT4_I(inode)->i_data_sem); 3441 ext4_es_remove_extent(inode, lblk, EXT_MAX_BLOCKS - lblk); 3442 up_write(&EXT4_I(inode)->i_data_sem); 3443 filemap_invalidate_unlock(mapping); 3444 } 3445 3446 static int ext4_da_do_write_end(struct address_space *mapping, 3447 loff_t pos, unsigned len, unsigned copied, 3448 struct folio *folio) 3449 { 3450 struct inode *inode = mapping->host; 3451 loff_t old_size = inode->i_size; 3452 bool disksize_changed = false; 3453 loff_t new_i_size; 3454 handle_t *handle; 3455 3456 if (unlikely(!folio_buffers(folio))) { 3457 folio_unlock(folio); 3458 folio_put(folio); 3459 return -EIO; 3460 } 3461 /* 3462 * block_write_end() will mark the inode as dirty with I_DIRTY_PAGES 3463 * flag, which all that's needed to trigger page writeback. 3464 */ 3465 copied = block_write_end(pos, len, copied, folio); 3466 new_i_size = pos + copied; 3467 3468 /* 3469 * It's important to update i_size while still holding folio lock, 3470 * because folio writeout could otherwise come in and zero beyond 3471 * i_size. 3472 * 3473 * Since we are holding inode lock, we are sure i_disksize <= 3474 * i_size. We also know that if i_disksize < i_size, there are 3475 * delalloc writes pending in the range up to i_size. If the end of 3476 * the current write is <= i_size, there's no need to touch 3477 * i_disksize since writeback will push i_disksize up to i_size 3478 * eventually. If the end of the current write is > i_size and 3479 * inside an allocated block which ext4_da_should_update_i_disksize() 3480 * checked, we need to update i_disksize here as certain 3481 * ext4_writepages() paths not allocating blocks and update i_disksize. 3482 */ 3483 if (copied && new_i_size > inode->i_size) { 3484 unsigned long end; 3485 3486 i_size_write(inode, new_i_size); 3487 end = offset_in_folio(folio, new_i_size - 1); 3488 if (ext4_da_should_update_i_disksize(folio, end)) { 3489 ext4_update_i_disksize(inode, new_i_size); 3490 disksize_changed = true; 3491 } 3492 } 3493 3494 folio_unlock(folio); 3495 folio_put(folio); 3496 3497 if (copied && pos > old_size) 3498 pagecache_isize_extended(inode, old_size, pos); 3499 3500 /* Drop what ->write_begin() prepared beyond the resulting i_size. */ 3501 if (pos + len > inode->i_size) 3502 ext4_da_truncate_failed_write(inode); 3503 3504 if (!disksize_changed) 3505 return copied; 3506 3507 handle = ext4_journal_start(inode, EXT4_HT_INODE, 1); 3508 if (IS_ERR(handle)) 3509 return PTR_ERR(handle); 3510 ext4_mark_inode_dirty(handle, inode); 3511 ext4_journal_stop(handle); 3512 3513 return copied; 3514 } 3515 3516 static int ext4_da_write_end(const struct kiocb *iocb, 3517 struct address_space *mapping, 3518 loff_t pos, unsigned len, unsigned copied, 3519 struct folio *folio, void *fsdata) 3520 { 3521 struct inode *inode = mapping->host; 3522 unsigned long write_mode = (unsigned long)fsdata; 3523 3524 if (write_mode & FALL_BACK_TO_NONDELALLOC) 3525 return ext4_write_end(iocb, mapping, pos, 3526 len, copied, folio, fsdata); 3527 3528 trace_ext4_da_write_end(inode, pos, len, copied); 3529 3530 if (write_mode & EXT4_WRITE_DATA_INLINE) 3531 return ext4_write_inline_data_end(inode, pos, len, copied, 3532 folio); 3533 3534 if (unlikely(copied < len) && !folio_test_uptodate(folio)) 3535 copied = 0; 3536 3537 return ext4_da_do_write_end(mapping, pos, len, copied, folio); 3538 } 3539 3540 /* 3541 * Force all delayed allocation blocks to be allocated for a given inode. 3542 */ 3543 int ext4_alloc_da_blocks(struct inode *inode) 3544 { 3545 trace_ext4_alloc_da_blocks(inode); 3546 3547 if (!EXT4_I(inode)->i_reserved_data_blocks) 3548 return 0; 3549 3550 /* 3551 * We do something simple for now. The filemap_flush() will 3552 * also start triggering a write of the data blocks, which is 3553 * not strictly speaking necessary. However, to do otherwise 3554 * would require replicating code paths in: 3555 * 3556 * ext4_writepages() -> 3557 * write_cache_pages() ---> (via passed in callback function) 3558 * __mpage_da_writepage() --> 3559 * mpage_add_bh_to_extent() 3560 * mpage_da_map_blocks() 3561 * 3562 * The problem is that write_cache_pages(), located in 3563 * mm/page-writeback.c, marks pages clean in preparation for 3564 * doing I/O, which is not desirable if we're not planning on 3565 * doing I/O at all. 3566 * 3567 * We could call write_cache_pages(), and then redirty all of 3568 * the pages by calling redirty_page_for_writepage() but that 3569 * would be ugly in the extreme. So instead we would need to 3570 * replicate parts of the code in the above functions, 3571 * simplifying them because we wouldn't actually intend to 3572 * write out the pages, but rather only collect contiguous 3573 * logical block extents, call the multi-block allocator, and 3574 * then update the buffer heads with the block allocations. 3575 * 3576 * For now, though, we'll cheat by calling filemap_flush(), 3577 * which will map the blocks, and start the I/O, but not 3578 * actually wait for the I/O to complete. 3579 */ 3580 return filemap_flush(inode->i_mapping); 3581 } 3582 3583 /* 3584 * bmap() is special. It gets used by applications such as lilo and by 3585 * the swapper to find the on-disk block of a specific piece of data. 3586 * 3587 * Naturally, this is dangerous if the block concerned is still in the 3588 * journal. If somebody makes a swapfile on an ext4 data-journaling 3589 * filesystem and enables swap, then they may get a nasty shock when the 3590 * data getting swapped to that swapfile suddenly gets overwritten by 3591 * the original zero's written out previously to the journal and 3592 * awaiting writeback in the kernel's buffer cache. 3593 * 3594 * So, if we see any bmap calls here on a modified, data-journaled file, 3595 * take extra steps to flush any blocks which might be in the cache. 3596 */ 3597 static sector_t ext4_bmap(struct address_space *mapping, sector_t block) 3598 { 3599 struct inode *inode = mapping->host; 3600 sector_t ret = 0; 3601 3602 inode_lock_shared(inode); 3603 /* 3604 * We can get here for an inline file via the FIBMAP ioctl 3605 */ 3606 if (ext4_has_inline_data(inode)) 3607 goto out; 3608 3609 if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY) && 3610 (test_opt(inode->i_sb, DELALLOC) || 3611 ext4_should_journal_data(inode))) { 3612 /* 3613 * With delalloc or journalled data we want to sync the file so 3614 * that we can make sure we allocate blocks for file and data 3615 * is in place for the user to see it 3616 */ 3617 filemap_write_and_wait(mapping); 3618 } 3619 3620 ret = iomap_bmap(mapping, block, ext4_iomap_next); 3621 3622 out: 3623 inode_unlock_shared(inode); 3624 return ret; 3625 } 3626 3627 static void ext4_invalidate_folio(struct folio *folio, size_t offset, 3628 size_t length) 3629 { 3630 trace_ext4_invalidate_folio(folio, offset, length); 3631 3632 /* No journalling happens on data buffers when this function is used */ 3633 WARN_ON(folio_buffers(folio) && buffer_jbd(folio_buffers(folio))); 3634 3635 block_invalidate_folio(folio, offset, length); 3636 } 3637 3638 static int __ext4_journalled_invalidate_folio(struct folio *folio, 3639 size_t offset, size_t length) 3640 { 3641 journal_t *journal = EXT4_JOURNAL(folio->mapping->host); 3642 3643 trace_ext4_journalled_invalidate_folio(folio, offset, length); 3644 3645 /* 3646 * If it's a full truncate we just forget about the pending dirtying 3647 */ 3648 if (offset == 0 && length == folio_size(folio)) 3649 folio_clear_checked(folio); 3650 3651 return jbd2_journal_invalidate_folio(journal, folio, offset, length); 3652 } 3653 3654 /* Wrapper for aops... */ 3655 static void ext4_journalled_invalidate_folio(struct folio *folio, 3656 size_t offset, 3657 size_t length) 3658 { 3659 WARN_ON(__ext4_journalled_invalidate_folio(folio, offset, length) < 0); 3660 } 3661 3662 static bool ext4_release_folio(struct folio *folio, gfp_t wait) 3663 { 3664 struct inode *inode = folio->mapping->host; 3665 journal_t *journal = EXT4_JOURNAL(inode); 3666 3667 trace_ext4_release_folio(inode, folio); 3668 3669 /* Page has dirty journalled data -> cannot release */ 3670 if (folio_test_checked(folio)) 3671 return false; 3672 if (journal) 3673 return jbd2_journal_try_to_free_buffers(journal, folio); 3674 else 3675 return try_to_free_buffers(folio); 3676 } 3677 3678 static bool ext4_inode_datasync_dirty(struct inode *inode) 3679 { 3680 journal_t *journal = EXT4_SB(inode->i_sb)->s_journal; 3681 struct mapping_metadata_bhs *mmb; 3682 3683 if (journal) { 3684 if (jbd2_transaction_committed(journal, 3685 EXT4_I(inode)->i_datasync_tid)) 3686 return false; 3687 if (test_opt2(inode->i_sb, JOURNAL_FAST_COMMIT)) 3688 return !list_empty(&EXT4_I(inode)->i_fc_list); 3689 return true; 3690 } 3691 3692 mmb = ext4_i_metadata_bhs(inode); 3693 /* Any metadata buffers to write? */ 3694 if (mmb && mmb_has_buffers(mmb)) 3695 return true; 3696 return inode_state_read_once(inode) & I_DIRTY_DATASYNC; 3697 } 3698 3699 static bool ext4_iomap_valid(struct inode *inode, const struct iomap *iomap) 3700 { 3701 return iomap->validity_cookie == READ_ONCE(EXT4_I(inode)->i_es_seq); 3702 } 3703 3704 const struct iomap_write_ops ext4_iomap_write_ops = { 3705 .iomap_valid = ext4_iomap_valid, 3706 }; 3707 3708 static void ext4_set_iomap(struct inode *inode, struct iomap *iomap, 3709 struct ext4_map_blocks *map, loff_t offset, 3710 loff_t length, unsigned int flags) 3711 { 3712 u8 blkbits = inode->i_blkbits; 3713 3714 /* 3715 * Writes that span EOF might trigger an I/O size update on completion, 3716 * so consider them to be dirty for the purpose of O_DSYNC, even if 3717 * there is no other metadata changes being made or are pending. 3718 */ 3719 iomap->flags = 0; 3720 if (ext4_inode_datasync_dirty(inode) || 3721 offset + length > i_size_read(inode)) 3722 iomap->flags |= IOMAP_F_DIRTY; 3723 3724 if (map->m_flags & EXT4_MAP_NEW) 3725 iomap->flags |= IOMAP_F_NEW; 3726 3727 /* HW-offload atomics are always used */ 3728 if (flags & IOMAP_ATOMIC) 3729 iomap->flags |= IOMAP_F_ATOMIC_BIO; 3730 3731 if (flags & IOMAP_DAX) 3732 iomap->dax_dev = EXT4_SB(inode->i_sb)->s_daxdev; 3733 else 3734 iomap->bdev = inode->i_sb->s_bdev; 3735 iomap->offset = EXT4_LBLK_TO_B(inode, map->m_lblk); 3736 iomap->length = EXT4_LBLK_TO_B(inode, map->m_len); 3737 3738 if ((map->m_flags & EXT4_MAP_MAPPED) && 3739 !ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) 3740 iomap->flags |= IOMAP_F_MERGED; 3741 3742 iomap->validity_cookie = map->m_seq; 3743 3744 /* 3745 * Flags passed to ext4_map_blocks() for direct I/O writes can result 3746 * in m_flags having both EXT4_MAP_MAPPED and EXT4_MAP_UNWRITTEN bits 3747 * set. In order for any allocated unwritten extents to be converted 3748 * into written extents correctly within the ->end_io() handler, we 3749 * need to ensure that the iomap->type is set appropriately. Hence, the 3750 * reason why we need to check whether the EXT4_MAP_UNWRITTEN bit has 3751 * been set first. 3752 */ 3753 if (map->m_flags & EXT4_MAP_UNWRITTEN) { 3754 iomap->type = IOMAP_UNWRITTEN; 3755 iomap->addr = (u64) map->m_pblk << blkbits; 3756 if (flags & IOMAP_DAX) 3757 iomap->addr += EXT4_SB(inode->i_sb)->s_dax_part_off; 3758 } else if (map->m_flags & EXT4_MAP_MAPPED) { 3759 iomap->type = IOMAP_MAPPED; 3760 iomap->addr = (u64) map->m_pblk << blkbits; 3761 if (flags & IOMAP_DAX) 3762 iomap->addr += EXT4_SB(inode->i_sb)->s_dax_part_off; 3763 } else if (map->m_flags & EXT4_MAP_DELAYED) { 3764 iomap->type = IOMAP_DELALLOC; 3765 iomap->addr = IOMAP_NULL_ADDR; 3766 } else { 3767 iomap->type = IOMAP_HOLE; 3768 iomap->addr = IOMAP_NULL_ADDR; 3769 } 3770 } 3771 3772 static int ext4_map_blocks_atomic_write_slow(handle_t *handle, 3773 struct inode *inode, struct ext4_map_blocks *map) 3774 { 3775 ext4_lblk_t m_lblk = map->m_lblk; 3776 unsigned int m_len = map->m_len; 3777 unsigned int mapped_len = 0, m_flags = 0; 3778 ext4_fsblk_t next_pblk = 0; 3779 bool check_next_pblk = false; 3780 int ret = 0; 3781 3782 WARN_ON_ONCE(!ext4_has_feature_bigalloc(inode->i_sb)); 3783 3784 /* 3785 * This is a slow path in case of mixed mapping. We use 3786 * EXT4_GET_BLOCKS_CREATE_ZERO flag here to make sure we get a single 3787 * contiguous mapped mapping. This will ensure any unwritten or hole 3788 * regions within the requested range is zeroed out and we return 3789 * a single contiguous mapped extent. 3790 */ 3791 m_flags = EXT4_GET_BLOCKS_CREATE_ZERO; 3792 3793 do { 3794 ret = ext4_map_blocks(handle, inode, map, m_flags); 3795 if (ret < 0 && ret != -ENOSPC) 3796 goto out_err; 3797 /* 3798 * This should never happen, but let's return an error code to 3799 * avoid an infinite loop in here. 3800 */ 3801 if (ret == 0) { 3802 ret = -EFSCORRUPTED; 3803 ext4_warning_inode(inode, 3804 "ext4_map_blocks() couldn't allocate blocks m_flags: 0x%x, ret:%d", 3805 m_flags, ret); 3806 goto out_err; 3807 } 3808 /* 3809 * With bigalloc we should never get ENOSPC nor discontiguous 3810 * physical extents. 3811 */ 3812 if ((check_next_pblk && next_pblk != map->m_pblk) || 3813 ret == -ENOSPC) { 3814 ext4_warning_inode(inode, 3815 "Non-contiguous allocation detected: expected %llu, got %llu, " 3816 "or ext4_map_blocks() returned out of space ret: %d", 3817 next_pblk, map->m_pblk, ret); 3818 ret = -EFSCORRUPTED; 3819 goto out_err; 3820 } 3821 next_pblk = map->m_pblk + map->m_len; 3822 check_next_pblk = true; 3823 3824 mapped_len += map->m_len; 3825 map->m_lblk += map->m_len; 3826 map->m_len = m_len - mapped_len; 3827 } while (mapped_len < m_len); 3828 3829 /* 3830 * We might have done some work in above loop, so we need to query the 3831 * start of the physical extent, based on the origin m_lblk and m_len. 3832 * Let's also ensure we were able to allocate the required range for 3833 * mixed mapping case. 3834 */ 3835 map->m_lblk = m_lblk; 3836 map->m_len = m_len; 3837 map->m_flags = 0; 3838 3839 ret = ext4_map_blocks(handle, inode, map, 3840 EXT4_GET_BLOCKS_QUERY_LAST_IN_LEAF); 3841 if (ret != m_len) { 3842 ext4_warning_inode(inode, 3843 "allocation failed for atomic write request m_lblk:%u, m_len:%u, ret:%d\n", 3844 m_lblk, m_len, ret); 3845 ret = -EINVAL; 3846 } 3847 return ret; 3848 3849 out_err: 3850 /* reset map before returning an error */ 3851 map->m_lblk = m_lblk; 3852 map->m_len = m_len; 3853 map->m_flags = 0; 3854 return ret; 3855 } 3856 3857 /* 3858 * ext4_map_blocks_atomic: Helper routine to ensure the entire requested 3859 * range in @map [lblk, lblk + len) is one single contiguous extent with no 3860 * mixed mappings. 3861 * 3862 * We first use m_flags passed to us by our caller (ext4_iomap_alloc()). 3863 * We only call EXT4_GET_BLOCKS_ZERO in the slow path, when the underlying 3864 * physical extent for the requested range does not have a single contiguous 3865 * mapping type i.e. (Hole, Mapped, or Unwritten) throughout. 3866 * In that case we will loop over the requested range to allocate and zero out 3867 * the unwritten / holes in between, to get a single mapped extent from 3868 * [m_lblk, m_lblk + m_len). Note that this is only possible because we know 3869 * this can be called only with bigalloc enabled filesystem where the underlying 3870 * cluster is already allocated. This avoids allocating discontiguous extents 3871 * in the slow path due to multiple calls to ext4_map_blocks(). 3872 * The slow path is mostly non-performance critical path, so it should be ok to 3873 * loop using ext4_map_blocks() with appropriate flags to allocate & zero the 3874 * underlying short holes/unwritten extents within the requested range. 3875 */ 3876 static int ext4_map_blocks_atomic_write(handle_t *handle, struct inode *inode, 3877 struct ext4_map_blocks *map, int m_flags, 3878 bool *force_commit) 3879 { 3880 ext4_lblk_t m_lblk = map->m_lblk; 3881 unsigned int m_len = map->m_len; 3882 int ret = 0; 3883 3884 WARN_ON_ONCE(m_len > 1 && !ext4_has_feature_bigalloc(inode->i_sb)); 3885 3886 ret = ext4_map_blocks(handle, inode, map, m_flags); 3887 if (ret < 0 || ret == m_len) 3888 goto out; 3889 /* 3890 * This is a mixed mapping case where we were not able to allocate 3891 * a single contiguous extent. In that case let's reset requested 3892 * mapping and call the slow path. 3893 */ 3894 map->m_lblk = m_lblk; 3895 map->m_len = m_len; 3896 map->m_flags = 0; 3897 3898 /* 3899 * slow path means we have mixed mapping, that means we will need 3900 * to force txn commit. 3901 */ 3902 *force_commit = true; 3903 return ext4_map_blocks_atomic_write_slow(handle, inode, map); 3904 out: 3905 return ret; 3906 } 3907 3908 static int ext4_iomap_alloc(struct inode *inode, struct ext4_map_blocks *map, 3909 unsigned int flags) 3910 { 3911 handle_t *handle; 3912 int ret, dio_credits, m_flags = 0, retries = 0; 3913 bool force_commit = false; 3914 3915 if (flags & IOMAP_NOWAIT) 3916 return -EAGAIN; 3917 3918 /* 3919 * Trim the mapping request to the maximum value that we can map at 3920 * once for direct I/O. 3921 */ 3922 if (map->m_len > DIO_MAX_BLOCKS) 3923 map->m_len = DIO_MAX_BLOCKS; 3924 3925 /* 3926 * journal credits estimation for atomic writes. We call 3927 * ext4_map_blocks(), to find if there could be a mixed mapping. If yes, 3928 * then let's assume the no. of pextents required can be m_len i.e. 3929 * every alternate block can be unwritten and hole. 3930 */ 3931 if (flags & IOMAP_ATOMIC) { 3932 unsigned int orig_mlen = map->m_len; 3933 3934 ret = ext4_map_blocks(NULL, inode, map, 0); 3935 if (ret < 0) 3936 return ret; 3937 if (map->m_len < orig_mlen) { 3938 map->m_len = orig_mlen; 3939 dio_credits = ext4_meta_trans_blocks(inode, map->m_len, 3940 map->m_len, 0); 3941 } else { 3942 dio_credits = ext4_chunk_trans_blocks(inode, 3943 map->m_len); 3944 } 3945 } else { 3946 dio_credits = ext4_chunk_trans_blocks(inode, map->m_len); 3947 } 3948 3949 retry: 3950 /* 3951 * Either we allocate blocks and then don't get an unwritten extent, so 3952 * in that case we have reserved enough credits. Or, the blocks are 3953 * already allocated and unwritten. In that case, the extent conversion 3954 * fits into the credits as well. 3955 */ 3956 handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS, dio_credits); 3957 if (IS_ERR(handle)) 3958 return PTR_ERR(handle); 3959 3960 /* 3961 * DAX and direct I/O are the only two operations that are currently 3962 * supported with IOMAP_WRITE. 3963 */ 3964 WARN_ON(!(flags & (IOMAP_DAX | IOMAP_DIRECT))); 3965 if (flags & IOMAP_DAX) 3966 m_flags = EXT4_GET_BLOCKS_CREATE_ZERO; 3967 /* 3968 * We use i_size instead of i_disksize here because delalloc writeback 3969 * can complete at any point during the I/O and subsequently push the 3970 * i_disksize out to i_size. This could be beyond where direct I/O is 3971 * happening and thus expose allocated blocks to direct I/O reads. 3972 */ 3973 else if (EXT4_LBLK_TO_B(inode, map->m_lblk) >= i_size_read(inode)) 3974 m_flags = EXT4_GET_BLOCKS_CREATE; 3975 else if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) 3976 m_flags = EXT4_GET_BLOCKS_CREATE_UNWRIT_EXT; 3977 3978 if (flags & IOMAP_ATOMIC) 3979 ret = ext4_map_blocks_atomic_write(handle, inode, map, m_flags, 3980 &force_commit); 3981 else 3982 ret = ext4_map_blocks(handle, inode, map, m_flags); 3983 3984 /* 3985 * We cannot fill holes in indirect tree based inodes as that could 3986 * expose stale data in the case of a crash. Use the magic error code 3987 * to fallback to buffered I/O. 3988 */ 3989 if (!m_flags && !ret) 3990 ret = -ENOTBLK; 3991 3992 ext4_journal_stop(handle); 3993 if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries)) 3994 goto retry; 3995 3996 /* 3997 * Force commit the current transaction if the allocation spans a mixed 3998 * mapping range. This ensures any pending metadata updates (like 3999 * unwritten to written extents conversion) in this range are in 4000 * consistent state with the file data blocks, before performing the 4001 * actual write I/O. If the commit fails, the whole I/O must be aborted 4002 * to prevent any possible torn writes. 4003 */ 4004 if (ret > 0 && force_commit) { 4005 int ret2; 4006 4007 ret2 = ext4_force_commit(inode->i_sb); 4008 if (ret2) 4009 return ret2; 4010 } 4011 4012 return ret; 4013 } 4014 4015 4016 int ext4_iomap_begin(struct inode *inode, loff_t offset, loff_t length, 4017 unsigned flags, struct iomap *iomap, struct iomap *srcmap) 4018 { 4019 int ret; 4020 struct ext4_map_blocks map; 4021 u8 blkbits = inode->i_blkbits; 4022 unsigned int orig_mlen; 4023 4024 if ((offset >> blkbits) > EXT4_MAX_LOGICAL_BLOCK) 4025 return -EINVAL; 4026 4027 if (WARN_ON_ONCE(ext4_has_inline_data(inode))) 4028 return -ERANGE; 4029 4030 /* 4031 * Calculate the first and last logical blocks respectively. 4032 */ 4033 map.m_lblk = offset >> blkbits; 4034 map.m_len = min_t(loff_t, (offset + length - 1) >> blkbits, 4035 EXT4_MAX_LOGICAL_BLOCK) - map.m_lblk + 1; 4036 orig_mlen = map.m_len; 4037 4038 if (flags & IOMAP_WRITE) { 4039 /* 4040 * We check here if the blocks are already allocated, then we 4041 * don't need to start a journal txn and we can directly return 4042 * the mapping information. This could boost performance 4043 * especially in multi-threaded overwrite requests. 4044 */ 4045 if (offset + length <= i_size_read(inode)) { 4046 ret = ext4_map_blocks(NULL, inode, &map, 0); 4047 /* 4048 * For DAX we convert extents to initialized ones before 4049 * copying the data, otherwise we do it after I/O so 4050 * there's no need to call into ext4_iomap_alloc(). 4051 */ 4052 if ((map.m_flags & EXT4_MAP_MAPPED) || 4053 (!(flags & IOMAP_DAX) && 4054 (map.m_flags & EXT4_MAP_UNWRITTEN))) { 4055 /* 4056 * For atomic writes the entire requested 4057 * length should be mapped. 4058 */ 4059 if (ret == orig_mlen || 4060 (!(flags & IOMAP_ATOMIC) && ret > 0)) 4061 goto out; 4062 } 4063 map.m_len = orig_mlen; 4064 } 4065 ret = ext4_iomap_alloc(inode, &map, flags); 4066 } else { 4067 ret = ext4_map_blocks(NULL, inode, &map, 0); 4068 } 4069 4070 if (ret < 0) 4071 return ret; 4072 out: 4073 /* 4074 * Sometimes I/O to an encrypted file has to be broken up to guarantee 4075 * DUN contiguity. Handle this by limiting the length of the mapping 4076 * returned. 4077 */ 4078 map.m_len = fscrypt_limit_io_blocks(inode, map.m_lblk, map.m_len); 4079 4080 /* 4081 * Before returning to iomap, let's ensure the allocated mapping 4082 * covers the entire requested length for atomic writes. 4083 */ 4084 if (flags & IOMAP_ATOMIC) { 4085 if (map.m_len < (length >> blkbits)) { 4086 WARN_ON_ONCE(1); 4087 return -EINVAL; 4088 } 4089 } 4090 ext4_set_iomap(inode, iomap, &map, offset, length, flags); 4091 4092 return 0; 4093 } 4094 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_iomap_begin); 4095 4096 DEFINE_IOMAP_ITER_NEXT(ext4_iomap_next, ext4_iomap_begin); 4097 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_iomap_next); 4098 4099 static int ext4_iomap_begin_report(struct inode *inode, loff_t offset, 4100 loff_t length, unsigned int flags, 4101 struct iomap *iomap, struct iomap *srcmap) 4102 { 4103 int ret; 4104 struct ext4_map_blocks map; 4105 u8 blkbits = inode->i_blkbits; 4106 4107 if ((offset >> blkbits) > EXT4_MAX_LOGICAL_BLOCK) 4108 return -EINVAL; 4109 4110 if (ext4_has_inline_data(inode)) { 4111 ret = ext4_inline_data_iomap(inode, iomap); 4112 if (ret != -EAGAIN) { 4113 if (ret == 0 && offset >= iomap->length) 4114 ret = -ENOENT; 4115 return ret; 4116 } 4117 } 4118 4119 /* 4120 * Calculate the first and last logical block respectively. 4121 */ 4122 map.m_lblk = offset >> blkbits; 4123 map.m_len = min_t(loff_t, (offset + length - 1) >> blkbits, 4124 EXT4_MAX_LOGICAL_BLOCK) - map.m_lblk + 1; 4125 4126 /* 4127 * Fiemap callers may call for offset beyond s_bitmap_maxbytes. 4128 * So handle it here itself instead of querying ext4_map_blocks(). 4129 * Since ext4_map_blocks() will warn about it and will return 4130 * -EIO error. 4131 */ 4132 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) { 4133 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb); 4134 4135 if (offset >= sbi->s_bitmap_maxbytes) { 4136 map.m_flags = 0; 4137 goto set_iomap; 4138 } 4139 } 4140 4141 ret = ext4_map_blocks(NULL, inode, &map, 0); 4142 if (ret < 0) 4143 return ret; 4144 set_iomap: 4145 ext4_set_iomap(inode, iomap, &map, offset, length, flags); 4146 4147 return 0; 4148 } 4149 4150 DEFINE_IOMAP_ITER_NEXT(ext4_iomap_next_report, ext4_iomap_begin_report); 4151 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_iomap_next_report); 4152 4153 static int ext4_iomap_map_blocks(struct inode *inode, loff_t offset, 4154 loff_t length, struct ext4_map_blocks *map, 4155 int flags) 4156 { 4157 u8 blkbits = inode->i_blkbits; 4158 4159 /* inode using the buffer_head buffered I/O path should not go here. */ 4160 if (WARN_ON_ONCE(!ext4_inode_buffered_iomap(inode))) 4161 return -EINVAL; 4162 if ((offset >> blkbits) > EXT4_MAX_LOGICAL_BLOCK) 4163 return -EINVAL; 4164 4165 /* Calculate the first and last logical blocks respectively. */ 4166 map->m_lblk = offset >> blkbits; 4167 map->m_len = min_t(loff_t, (offset + length - 1) >> blkbits, 4168 EXT4_MAX_LOGICAL_BLOCK) - map->m_lblk + 1; 4169 4170 if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) 4171 return ext4_da_map_blocks(inode, map); 4172 4173 return ext4_map_blocks(NULL, inode, map, flags); 4174 } 4175 4176 static int ext4_iomap_buffered_read_begin(struct inode *inode, loff_t offset, 4177 loff_t length, unsigned int flags, struct iomap *iomap, 4178 struct iomap *srcmap) 4179 { 4180 struct ext4_map_blocks map; 4181 int ret; 4182 4183 if (unlikely(ext4_forced_shutdown(inode->i_sb))) 4184 return -EIO; 4185 4186 /* Inline data support is not yet available. */ 4187 if (WARN_ON_ONCE(ext4_has_inline_data(inode))) 4188 return -ERANGE; 4189 4190 ret = ext4_iomap_map_blocks(inode, offset, length, &map, 0); 4191 if (ret < 0) 4192 return ret; 4193 4194 trace_ext4_iomap_buffered_read_begin(inode, &map, offset, length, 4195 flags); 4196 ext4_set_iomap(inode, iomap, &map, offset, length, flags); 4197 return 0; 4198 } 4199 4200 static int ext4_iomap_buffered_do_write_begin(struct inode *inode, 4201 loff_t offset, loff_t length, unsigned int flags, 4202 struct iomap *iomap, struct iomap *srcmap, bool delalloc) 4203 { 4204 int ret, retries = 0; 4205 struct ext4_map_blocks map; 4206 int map_flags; 4207 4208 ret = ext4_emergency_state(inode->i_sb); 4209 if (unlikely(ret)) 4210 return ret; 4211 4212 /* Inline data and non-extent are not supported. */ 4213 if (WARN_ON_ONCE(ext4_has_inline_data(inode))) 4214 return -ERANGE; 4215 if (WARN_ON_ONCE(!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) 4216 return -EINVAL; 4217 if (WARN_ON_ONCE(!(flags & (IOMAP_WRITE | IOMAP_FAULT)))) 4218 return -EINVAL; 4219 4220 map_flags = delalloc ? EXT4_GET_BLOCKS_DELALLOC_RESERVE : 4221 EXT4_GET_BLOCKS_CREATE_UNWRIT_EXT; 4222 retry: 4223 ret = ext4_iomap_map_blocks(inode, offset, length, &map, map_flags); 4224 if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries)) 4225 goto retry; 4226 if (ret < 0) 4227 return ret; 4228 4229 trace_ext4_iomap_buffered_write_begin(inode, &map, offset, length, 4230 flags); 4231 ext4_set_iomap(inode, iomap, &map, offset, length, flags); 4232 return 0; 4233 } 4234 4235 static int ext4_iomap_buffered_write_begin(struct inode *inode, 4236 loff_t offset, loff_t length, unsigned int flags, 4237 struct iomap *iomap, struct iomap *srcmap) 4238 { 4239 return ext4_iomap_buffered_do_write_begin(inode, offset, length, flags, 4240 iomap, srcmap, false); 4241 } 4242 4243 static int ext4_iomap_buffered_da_write_begin(struct inode *inode, 4244 loff_t offset, loff_t length, unsigned int flags, 4245 struct iomap *iomap, struct iomap *srcmap) 4246 { 4247 return ext4_iomap_buffered_do_write_begin(inode, offset, length, flags, 4248 iomap, srcmap, true); 4249 } 4250 4251 /* 4252 * On write failure, drop the stale delayed allocation range and release 4253 * its reserved space for both start and end blocks. Otherwise, we may 4254 * leave a range of delayed extents covered by a clean folio, which can 4255 * result in inaccurate space reservation accounting. 4256 */ 4257 static void ext4_iomap_punch_delalloc(struct inode *inode, loff_t offset, 4258 loff_t length, struct iomap *iomap) 4259 { 4260 down_write(&EXT4_I(inode)->i_data_sem); 4261 ext4_es_remove_extent(inode, offset >> inode->i_blkbits, 4262 DIV_ROUND_UP_ULL(length, EXT4_BLOCK_SIZE(inode->i_sb))); 4263 up_write(&EXT4_I(inode)->i_data_sem); 4264 } 4265 4266 static int ext4_iomap_buffered_da_write_end(struct inode *inode, loff_t offset, 4267 loff_t length, ssize_t written, 4268 unsigned int flags, 4269 struct iomap *iomap) 4270 { 4271 loff_t start_byte, end_byte; 4272 4273 /* If we didn't reserve the blocks, we're not allowed to punch them. */ 4274 if (iomap->type != IOMAP_DELALLOC || !(iomap->flags & IOMAP_F_NEW)) 4275 return 0; 4276 4277 /* 4278 * iomap_page_mkwrite() will never fail in a way that requires delalloc 4279 * extents that it allocated to be revoked. Hence never try to release 4280 * them here. 4281 */ 4282 if (flags & IOMAP_FAULT) 4283 return 0; 4284 4285 /* Nothing to do if we've written the entire delalloc extent */ 4286 start_byte = iomap_last_written_block(inode, offset, written); 4287 end_byte = round_up(offset + length, i_blocksize(inode)); 4288 if (start_byte >= end_byte) 4289 return 0; 4290 4291 filemap_invalidate_lock(inode->i_mapping); 4292 iomap_write_delalloc_release(inode, start_byte, end_byte, flags, 4293 iomap, ext4_iomap_punch_delalloc); 4294 filemap_invalidate_unlock(inode->i_mapping); 4295 return 0; 4296 } 4297 4298 static int ext4_iomap_zero_begin(struct inode *inode, 4299 loff_t offset, loff_t length, unsigned int flags, 4300 struct iomap *iomap, struct iomap *srcmap) 4301 { 4302 struct iomap_iter *iter = container_of(iomap, struct iomap_iter, iomap); 4303 struct ext4_map_blocks map; 4304 u8 blkbits = inode->i_blkbits; 4305 unsigned int iomap_flags; 4306 int ret; 4307 4308 ret = ext4_emergency_state(inode->i_sb); 4309 if (unlikely(ret)) 4310 return ret; 4311 4312 if (WARN_ON_ONCE(!(flags & IOMAP_ZERO))) 4313 return -EINVAL; 4314 4315 again: 4316 ret = ext4_iomap_map_blocks(inode, offset, length, &map, 0); 4317 if (ret < 0) 4318 return ret; 4319 4320 /* 4321 * Look up dirty folios for unwritten mappings within EOF. Providing 4322 * this bypasses the flush iomap uses to trigger extent conversion 4323 * when unwritten mappings have dirty pagecache in need of zeroing. 4324 */ 4325 iomap_flags = 0; 4326 if (map.m_flags & EXT4_MAP_UNWRITTEN) { 4327 loff_t start = ((loff_t)map.m_lblk) << blkbits; 4328 loff_t end = ((loff_t)map.m_lblk + map.m_len) << blkbits; 4329 unsigned int count; 4330 4331 count = iomap_fill_dirty_folios(iter, &start, end, 4332 &iomap_flags); 4333 if ((start >> blkbits) < map.m_lblk + map.m_len) 4334 map.m_len = (start >> blkbits) - map.m_lblk; 4335 4336 /* 4337 * This can be raced by a concurrent writeback that cleans 4338 * the folio and converts the unwritten extent to written. 4339 * Recheck the mapping after a folio lock round in 4340 * iomap_fill_dirty_folios(). 4341 */ 4342 if (count == 0 && 4343 map.m_seq != READ_ONCE(EXT4_I(inode)->i_es_seq)) 4344 goto again; 4345 } 4346 4347 trace_ext4_iomap_zero_begin(inode, &map, offset, length, flags); 4348 ext4_set_iomap(inode, iomap, &map, offset, length, flags); 4349 iomap->flags |= iomap_flags; 4350 4351 return 0; 4352 } 4353 4354 static DEFINE_IOMAP_ITER_NEXT(ext4_iomap_zero_next, ext4_iomap_zero_begin); 4355 4356 /* 4357 * Since we always allocate unwritten extents, there is no need for 4358 * iomap_end to clean up allocated blocks on a short write. 4359 */ 4360 DEFINE_IOMAP_ITER_NEXT(ext4_iomap_buffered_write_next, 4361 ext4_iomap_buffered_write_begin); 4362 4363 DEFINE_IOMAP_ITER_NEXT_END(ext4_iomap_buffered_da_write_next, 4364 ext4_iomap_buffered_da_write_begin, 4365 ext4_iomap_buffered_da_write_end); 4366 4367 static DEFINE_IOMAP_ITER_NEXT(ext4_iomap_buffered_read_next, 4368 ext4_iomap_buffered_read_begin); 4369 4370 static int ext4_iomap_read_folio(struct file *file, struct folio *folio) 4371 { 4372 iomap_bio_read_folio(folio, ext4_iomap_buffered_read_next); 4373 return 0; 4374 } 4375 4376 static void ext4_iomap_readahead(struct readahead_control *rac) 4377 { 4378 iomap_bio_readahead(rac, ext4_iomap_buffered_read_next); 4379 } 4380 4381 4382 static int ext4_iomap_map_writeback_range(struct iomap_writepage_ctx *wpc, 4383 loff_t offset, unsigned int dirty_len) 4384 { 4385 struct inode *inode = wpc->inode; 4386 struct super_block *sb = inode->i_sb; 4387 struct journal_s *journal = EXT4_SB(sb)->s_journal; 4388 struct ext4_map_blocks map; 4389 ext4_lblk_t index = offset >> inode->i_blkbits; 4390 unsigned int blk_len, blk_end; 4391 int retries = 0; 4392 int ret; 4393 4394 ret = ext4_emergency_state(sb); 4395 if (unlikely(ret)) 4396 return ret; 4397 4398 /* Check validity of the cached writeback mapping. */ 4399 if (offset >= wpc->iomap.offset && 4400 offset < wpc->iomap.offset + wpc->iomap.length && 4401 ext4_iomap_valid(inode, &wpc->iomap)) 4402 return 0; 4403 4404 blk_len = dirty_len >> inode->i_blkbits; 4405 blk_end = umin(wpc->wbc->range_end >> inode->i_blkbits, UINT_MAX - 1); 4406 if (blk_end > index + blk_len) 4407 blk_len = blk_end - index + 1; 4408 4409 retry: 4410 map.m_lblk = index; 4411 map.m_len = min_t(unsigned int, MAX_WRITEPAGES_EXTENT_LEN, blk_len); 4412 ret = ext4_map_blocks(NULL, inode, &map, 4413 EXT4_GET_BLOCKS_CREATE_UNWRIT_EXT | 4414 EXT4_GET_BLOCKS_METADATA_NOFAIL | 4415 EXT4_GET_BLOCKS_IO_SUBMIT | 4416 EXT4_EX_NOCACHE); 4417 if (ret < 0) { 4418 if (ext4_emergency_state(sb)) 4419 return ret; 4420 4421 /* 4422 * Retry transient ENOSPC errors, if 4423 * ext4_count_free_blocks() is non-zero, a commit 4424 * should free up blocks. 4425 */ 4426 if (ret == -ENOSPC && journal && ext4_count_free_clusters(sb) && 4427 ++retries <= 3) { 4428 jbd2_journal_force_commit_nested(journal); 4429 goto retry; 4430 } 4431 4432 ext4_msg(sb, KERN_CRIT, 4433 "Delayed block allocation failed for inode %llu at logical offset %llu with max blocks %u with error %d", 4434 inode->i_ino, (unsigned long long)map.m_lblk, 4435 (unsigned int)map.m_len, -ret); 4436 ext4_msg(sb, KERN_CRIT, 4437 "This should not happen!! Data will be lost\n"); 4438 if (ret == -ENOSPC) 4439 ext4_print_free_blocks(inode); 4440 return ret; 4441 } 4442 4443 trace_ext4_iomap_map_writeback_range(inode, &map, offset, dirty_len, 0); 4444 ext4_set_iomap(inode, &wpc->iomap, &map, offset, dirty_len, 0); 4445 return 0; 4446 } 4447 4448 static void ext4_iomap_discard_folio(struct folio *folio, loff_t pos) 4449 { 4450 struct inode *inode = folio->mapping->host; 4451 loff_t length = folio_pos(folio) + folio_size(folio) - pos; 4452 loff_t pstart, plen; 4453 4454 ext4_iomap_punch_delalloc(inode, pos, length, NULL); 4455 4456 /* 4457 * Clear the disksize-grow-pending state if the zeroed EOF block 4458 * fails to write back and is discarded. 4459 */ 4460 plen = ext4_iomap_get_disksize_pending_range(inode, &pstart); 4461 if (plen && pos <= pstart && folio_next_pos(folio) >= pstart + plen) 4462 ext4_iomap_clear_disksize_pending(inode); 4463 } 4464 4465 static ssize_t ext4_iomap_writeback_range(struct iomap_writepage_ctx *wpc, 4466 struct folio *folio, u64 offset, 4467 unsigned int len, u64 end_pos) 4468 { 4469 ssize_t ret; 4470 4471 ret = ext4_iomap_map_writeback_range(wpc, offset, len); 4472 if (!ret) 4473 ret = iomap_add_to_ioend(wpc, folio, offset, end_pos, len); 4474 if (ret < 0) 4475 ext4_iomap_discard_folio(folio, offset); 4476 return ret; 4477 } 4478 4479 static int ext4_iomap_writeback_submit(struct iomap_writepage_ctx *wpc, 4480 int error) 4481 { 4482 struct iomap_ioend *ioend = wpc->wb_ctx; 4483 struct inode *inode = ioend->io_inode; 4484 struct ext4_inode_info *ei = EXT4_I(inode); 4485 unsigned int blocksize = i_blocksize(inode); 4486 loff_t pstart, plen; 4487 4488 /* 4489 * After I/O completion, a worker needs to be scheduled when: 4490 * 1) Unwritten extents require conversion. 4491 * 2) The file size needs to be extended. 4492 * 3) The journal needs to be aborted due to an I/O error. 4493 */ 4494 if ((ioend->io_flags & IOMAP_IOEND_UNWRITTEN) || 4495 (ioend->io_offset + ioend->io_size > READ_ONCE(ei->i_disksize)) || 4496 test_opt(ioend->io_inode->i_sb, DATA_ERR_ABORT)) 4497 ioend->io_bio.bi_end_io = ext4_iomap_end_bio; 4498 4499 /* 4500 * Mark the I/O as DISKSIZE_GROW_IO by setting io_private to 4501 * EXT4_IOMAP_IOEND_DISKSIZE_GROW_IO if it covers the pending range. 4502 * Such I/O will allow or trigger i_disksize advancement in the 4503 * ioend worker. 4504 */ 4505 plen = ext4_iomap_get_disksize_pending_range(inode, &pstart); 4506 if (plen && 4507 round_down(ioend->io_offset, blocksize) <= pstart && 4508 round_up(ioend->io_offset + ioend->io_size, blocksize) >= 4509 pstart + plen) { 4510 trace_ext4_iomap_wb_disksize_pending_submit(inode, 4511 ioend->io_offset, ioend->io_size); 4512 ioend->io_bio.bi_end_io = ext4_iomap_end_bio; 4513 ioend->io_private = (void *)EXT4_IOMAP_IOEND_DISKSIZE_GROW_IO; 4514 } 4515 4516 /* 4517 * ext4_iomap_end_bio() always defers endio processing, disable 4518 * generic BIO in task to avoid double deferral since we will use 4519 * a private defer endio handler in process context. 4520 * 4521 * TODO: Switch all defer handlers to the generic bio complete 4522 * in task framework. 4523 */ 4524 if (ioend->io_bio.bi_end_io) 4525 bio_clear_flag(&ioend->io_bio, BIO_COMPLETE_IN_TASK); 4526 4527 return iomap_ioend_writeback_submit(wpc, error); 4528 } 4529 4530 static const struct iomap_writeback_ops ext4_writeback_ops = { 4531 .writeback_range = ext4_iomap_writeback_range, 4532 .writeback_submit = ext4_iomap_writeback_submit, 4533 }; 4534 4535 /* 4536 * If the current writeback range begins after the pending zeroed EOF 4537 * block range which straddles i_disksize, issue a separate writeback to 4538 * flush it first, so as to avoid prolonged waiting. 4539 */ 4540 static void ext4_iomap_wb_submit_zeroed_eof(struct inode *inode, 4541 struct writeback_control *wbc) 4542 { 4543 struct address_space *mapping = inode->i_mapping; 4544 loff_t pstart, plen, range_start; 4545 4546 if (wbc->range_cyclic) 4547 range_start = (loff_t)mapping->writeback_index << PAGE_SHIFT; 4548 else 4549 range_start = wbc->range_start; 4550 4551 plen = ext4_iomap_get_disksize_pending_range(inode, &pstart); 4552 if (!plen) 4553 return; 4554 if (round_down(range_start, mapping_min_folio_nrbytes(mapping)) < 4555 pstart + plen) 4556 return; 4557 4558 /* Keep the caller's sync mode to avoid stalling the background flusher. */ 4559 if (wbc->sync_mode == WB_SYNC_ALL) 4560 filemap_fdatawrite_range(mapping, pstart, pstart + plen - 1); 4561 else 4562 filemap_flush_range(mapping, pstart, pstart + plen - 1); 4563 } 4564 4565 static int ext4_iomap_writepages(struct address_space *mapping, 4566 struct writeback_control *wbc) 4567 { 4568 struct inode *inode = mapping->host; 4569 struct super_block *sb = inode->i_sb; 4570 long nr = wbc->nr_to_write; 4571 int alloc_ctx, ret; 4572 struct iomap_writepage_ctx wpc = { 4573 .inode = inode, 4574 .wbc = wbc, 4575 .ops = &ext4_writeback_ops, 4576 }; 4577 4578 ret = ext4_emergency_state(sb); 4579 if (unlikely(ret)) 4580 return ret; 4581 4582 /* 4583 * Submit the pending zeroed EOF block range if the entire 4584 * writeback range lies beyond it. 4585 */ 4586 ext4_iomap_wb_submit_zeroed_eof(inode, wbc); 4587 4588 alloc_ctx = ext4_writepages_down_read(sb); 4589 /* 4590 * Does ext4_change_inode_journal_flag() change the inode's 4591 * buffered I/O path? 4592 */ 4593 if (!ext4_inode_buffered_iomap(inode)) { 4594 ext4_writepages_up_read(sb, alloc_ctx); 4595 return 0; 4596 } 4597 4598 trace_ext4_writepages(inode, wbc); 4599 ret = iomap_writepages(&wpc); 4600 trace_ext4_writepages_result(inode, wbc, ret, nr - wbc->nr_to_write); 4601 ext4_writepages_up_read(sb, alloc_ctx); 4602 4603 return ret; 4604 } 4605 4606 /* 4607 * For data=journal mode, folio should be marked dirty only when it was 4608 * writeably mapped. When that happens, it was already attached to the 4609 * transaction and marked as jbddirty (we take care of this in 4610 * ext4_page_mkwrite()). On transaction commit, we writeprotect page mappings 4611 * so we should have nothing to do here, except for the case when someone 4612 * had the page pinned and dirtied the page through this pin (e.g. by doing 4613 * direct IO to it). In that case we'd need to attach buffers here to the 4614 * transaction but we cannot due to lock ordering. We cannot just dirty the 4615 * folio and leave attached buffers clean, because the buffers' dirty state is 4616 * "definitive". We cannot just set the buffers dirty or jbddirty because all 4617 * the journalling code will explode. So what we do is to mark the folio 4618 * "pending dirty" and next time ext4_writepages() is called, attach buffers 4619 * to the transaction appropriately. 4620 */ 4621 static bool ext4_journalled_dirty_folio(struct address_space *mapping, 4622 struct folio *folio) 4623 { 4624 WARN_ON_ONCE(!folio_buffers(folio)); 4625 if (folio_maybe_dma_pinned(folio)) 4626 folio_set_checked(folio); 4627 return filemap_dirty_folio(mapping, folio); 4628 } 4629 4630 static bool ext4_dirty_folio(struct address_space *mapping, struct folio *folio) 4631 { 4632 WARN_ON_ONCE(!folio_test_locked(folio) && !folio_test_dirty(folio)); 4633 WARN_ON_ONCE(!folio_buffers(folio)); 4634 return block_dirty_folio(mapping, folio); 4635 } 4636 4637 static int ext4_iomap_swap_activate(struct swap_info_struct *sis, 4638 struct file *file, sector_t *span) 4639 { 4640 return iomap_swapfile_activate(sis, file, span, 4641 ext4_iomap_next_report); 4642 } 4643 4644 static const struct address_space_operations ext4_aops = { 4645 .read_folio = ext4_read_folio, 4646 .readahead = ext4_readahead, 4647 .writepages = ext4_writepages, 4648 .write_begin = ext4_write_begin, 4649 .write_end = ext4_write_end, 4650 .dirty_folio = ext4_dirty_folio, 4651 .bmap = ext4_bmap, 4652 .invalidate_folio = ext4_invalidate_folio, 4653 .release_folio = ext4_release_folio, 4654 .migrate_folio = buffer_migrate_folio, 4655 .is_partially_uptodate = block_is_partially_uptodate, 4656 .error_remove_folio = generic_error_remove_folio, 4657 .swap_activate = ext4_iomap_swap_activate, 4658 }; 4659 4660 static const struct address_space_operations ext4_journalled_aops = { 4661 .read_folio = ext4_read_folio, 4662 .readahead = ext4_readahead, 4663 .writepages = ext4_writepages, 4664 .write_begin = ext4_write_begin, 4665 .write_end = ext4_journalled_write_end, 4666 .dirty_folio = ext4_journalled_dirty_folio, 4667 .bmap = ext4_bmap, 4668 .invalidate_folio = ext4_journalled_invalidate_folio, 4669 .release_folio = ext4_release_folio, 4670 .migrate_folio = buffer_migrate_folio_norefs, 4671 .is_partially_uptodate = block_is_partially_uptodate, 4672 .error_remove_folio = generic_error_remove_folio, 4673 .swap_activate = ext4_iomap_swap_activate, 4674 }; 4675 4676 static const struct address_space_operations ext4_da_aops = { 4677 .read_folio = ext4_read_folio, 4678 .readahead = ext4_readahead, 4679 .writepages = ext4_writepages, 4680 .write_begin = ext4_da_write_begin, 4681 .write_end = ext4_da_write_end, 4682 .dirty_folio = ext4_dirty_folio, 4683 .bmap = ext4_bmap, 4684 .invalidate_folio = ext4_invalidate_folio, 4685 .release_folio = ext4_release_folio, 4686 .migrate_folio = buffer_migrate_folio, 4687 .is_partially_uptodate = block_is_partially_uptodate, 4688 .error_remove_folio = generic_error_remove_folio, 4689 .swap_activate = ext4_iomap_swap_activate, 4690 }; 4691 4692 static const struct address_space_operations ext4_iomap_aops = { 4693 .read_folio = ext4_iomap_read_folio, 4694 .readahead = ext4_iomap_readahead, 4695 .writepages = ext4_iomap_writepages, 4696 .dirty_folio = iomap_dirty_folio, 4697 .bmap = ext4_bmap, 4698 .invalidate_folio = iomap_invalidate_folio, 4699 .release_folio = iomap_release_folio, 4700 .migrate_folio = filemap_migrate_folio, 4701 .is_partially_uptodate = iomap_is_partially_uptodate, 4702 .error_remove_folio = generic_error_remove_folio, 4703 .swap_activate = ext4_iomap_swap_activate, 4704 }; 4705 4706 static const struct address_space_operations ext4_dax_aops = { 4707 .writepages = ext4_dax_writepages, 4708 .dirty_folio = noop_dirty_folio, 4709 .bmap = ext4_bmap, 4710 .swap_activate = ext4_iomap_swap_activate, 4711 }; 4712 4713 void ext4_set_aops(struct inode *inode) 4714 { 4715 switch (ext4_inode_journal_mode(inode)) { 4716 case EXT4_INODE_ORDERED_DATA_MODE: 4717 case EXT4_INODE_WRITEBACK_DATA_MODE: 4718 break; 4719 case EXT4_INODE_JOURNAL_DATA_MODE: 4720 inode->i_mapping->a_ops = &ext4_journalled_aops; 4721 return; 4722 default: 4723 BUG(); 4724 } 4725 if (IS_DAX(inode)) 4726 inode->i_mapping->a_ops = &ext4_dax_aops; 4727 else if (ext4_inode_buffered_iomap(inode)) 4728 inode->i_mapping->a_ops = &ext4_iomap_aops; 4729 else if (test_opt(inode->i_sb, DELALLOC)) 4730 inode->i_mapping->a_ops = &ext4_da_aops; 4731 else 4732 inode->i_mapping->a_ops = &ext4_aops; 4733 } 4734 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_set_aops); 4735 4736 /* 4737 * Here we can't skip an unwritten buffer even though it usually reads zero 4738 * because it might have data in pagecache (eg, if called from ext4_zero_range, 4739 * ext4_punch_hole, etc) which needs to be properly zeroed out. Otherwise a 4740 * racing writeback can come later and flush the stale pagecache to disk. 4741 * 4742 * Return the loaded bh if it actually needs zeroing - in written, dirty 4743 * unwritten, or delalloc state. Return NULL if it's clean (i.e., a hole or 4744 * a clean unwritten block). 4745 */ 4746 static struct buffer_head *ext4_load_tail_bh(struct inode *inode, loff_t from) 4747 { 4748 unsigned int offset, blocksize, pos; 4749 ext4_lblk_t iblock; 4750 struct address_space *mapping = inode->i_mapping; 4751 struct buffer_head *bh; 4752 struct folio *folio; 4753 int err = 0; 4754 4755 folio = __filemap_get_folio(mapping, from >> PAGE_SHIFT, 4756 FGP_WRITEBEGIN | FGP_ACCESSED, 4757 mapping_gfp_constraint(mapping, ~__GFP_FS)); 4758 if (IS_ERR(folio)) 4759 return ERR_CAST(folio); 4760 4761 blocksize = inode->i_sb->s_blocksize; 4762 4763 iblock = EXT4_PG_TO_LBLK(inode, folio->index); 4764 4765 bh = folio_buffers(folio); 4766 if (!bh) 4767 bh = create_empty_buffers(folio, blocksize, 0); 4768 4769 /* Find the buffer that contains "offset" */ 4770 offset = offset_in_folio(folio, from); 4771 pos = blocksize; 4772 while (offset >= pos) { 4773 bh = bh->b_this_page; 4774 iblock++; 4775 pos += blocksize; 4776 } 4777 if (buffer_freed(bh)) { 4778 BUFFER_TRACE(bh, "freed: skip"); 4779 goto unlock; 4780 } 4781 if (!buffer_mapped(bh)) { 4782 BUFFER_TRACE(bh, "unmapped"); 4783 err = ext4_get_block(inode, iblock, bh, 0); 4784 if (err < 0) 4785 goto unlock; 4786 /* 4787 * It's a hole or a clean unwritten block - nothing to do. 4788 * Note that a lookup-only get_block (without 4789 * EXT4_GET_BLOCKS_CREATE) never sets BH_Mapped for clean 4790 * unwritten extents. 4791 */ 4792 if (!buffer_mapped(bh)) { 4793 BUFFER_TRACE(bh, "still unmapped"); 4794 goto unlock; 4795 } 4796 } 4797 4798 /* Ok, it's mapped. Make sure it's up-to-date */ 4799 if (folio_test_uptodate(folio)) 4800 set_buffer_uptodate(bh); 4801 4802 if (!buffer_uptodate(bh)) { 4803 err = ext4_read_bh_lock(bh, 0, true); 4804 if (err) 4805 goto unlock; 4806 } 4807 return bh; 4808 4809 unlock: 4810 folio_unlock(folio); 4811 folio_put(folio); 4812 return err ? ERR_PTR(err) : NULL; 4813 } 4814 4815 static int ext4_block_do_zero_range(struct inode *inode, loff_t from, 4816 loff_t length, bool *did_zero, 4817 bool *zero_written) 4818 { 4819 struct buffer_head *bh; 4820 struct folio *folio; 4821 4822 bh = ext4_load_tail_bh(inode, from); 4823 if (IS_ERR_OR_NULL(bh)) 4824 return PTR_ERR_OR_ZERO(bh); 4825 4826 folio = bh->b_folio; 4827 folio_zero_range(folio, offset_in_folio(folio, from), length); 4828 BUFFER_TRACE(bh, "zeroed end of block"); 4829 4830 mark_buffer_dirty(bh); 4831 if (did_zero) 4832 *did_zero = true; 4833 if (zero_written && !buffer_unwritten(bh) && !buffer_delay(bh)) 4834 *zero_written = true; 4835 4836 folio_unlock(folio); 4837 folio_put(folio); 4838 return 0; 4839 } 4840 4841 static int ext4_block_journalled_zero_range(struct inode *inode, loff_t from, 4842 loff_t length, bool *did_zero) 4843 { 4844 struct buffer_head *bh; 4845 struct folio *folio; 4846 handle_t *handle; 4847 int err; 4848 4849 handle = ext4_journal_start(inode, EXT4_HT_MISC, 1); 4850 if (IS_ERR(handle)) 4851 return PTR_ERR(handle); 4852 4853 bh = ext4_load_tail_bh(inode, from); 4854 if (IS_ERR_OR_NULL(bh)) { 4855 err = PTR_ERR_OR_ZERO(bh); 4856 goto out_handle; 4857 } 4858 folio = bh->b_folio; 4859 4860 BUFFER_TRACE(bh, "get write access"); 4861 err = ext4_journal_get_write_access(handle, inode->i_sb, bh, 4862 EXT4_JTR_NONE); 4863 if (err) 4864 goto out; 4865 4866 folio_zero_range(folio, offset_in_folio(folio, from), length); 4867 BUFFER_TRACE(bh, "zeroed end of block"); 4868 4869 err = ext4_dirty_journalled_data(handle, bh); 4870 if (err) 4871 goto out; 4872 4873 if (did_zero) 4874 *did_zero = true; 4875 out: 4876 folio_unlock(folio); 4877 folio_put(folio); 4878 out_handle: 4879 ext4_journal_stop(handle); 4880 return err; 4881 } 4882 4883 static int ext4_block_iomap_zero_range(struct inode *inode, loff_t from, 4884 loff_t length, bool *did_zero, 4885 bool *zero_written) 4886 { 4887 int ret; 4888 4889 /* 4890 * Zeroing out under an active handle can cause deadlock since 4891 * the order of acquiring the folio lock and starting a handle is 4892 * inconsistent with the iomap writeback procedure. 4893 */ 4894 if (WARN_ON_ONCE(ext4_handle_valid(journal_current_handle()))) 4895 return -EINVAL; 4896 4897 /* The zeroing scope should not extend across a block. */ 4898 if (WARN_ON_ONCE((from >> inode->i_blkbits) != 4899 ((from + length - 1) >> inode->i_blkbits))) 4900 return -EINVAL; 4901 4902 if (!(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_ORPHAN_FS) && 4903 !(inode_state_read_once(inode) & (I_NEW | I_FREEING))) 4904 WARN_ON_ONCE(!inode_is_locked(inode) && 4905 !rwsem_is_locked(&inode->i_mapping->invalidate_lock)); 4906 4907 ret = iomap_zero_range(inode, from, length, did_zero, 4908 ext4_iomap_zero_next, &ext4_iomap_write_ops, 4909 NULL); 4910 if (ret) 4911 return ret; 4912 4913 /* 4914 * TODO: The iomap does not distinguish between different types 4915 * of zeroing operations. So we always set zero_written whenever 4916 * zeroing is performed, which may cause unnecessary folio 4917 * flushing when zeroing occurs on delayed-allocated blocks. 4918 */ 4919 if (did_zero && zero_written) 4920 *zero_written = *did_zero; 4921 4922 return 0; 4923 } 4924 4925 /* 4926 * Zeros out a mapping of length 'length' starting from file offset 4927 * 'from'. The range to be zero'd must be contained with in one block. 4928 * If the specified range exceeds the end of the block it will be 4929 * shortened to end of the block that corresponds to 'from'. 4930 */ 4931 static int ext4_block_zero_range(struct inode *inode, 4932 loff_t from, loff_t length, bool *did_zero, 4933 bool *zero_written) 4934 { 4935 unsigned blocksize = inode->i_sb->s_blocksize; 4936 unsigned int max = blocksize - (from & (blocksize - 1)); 4937 4938 /* 4939 * correct length if it does not fall between 4940 * 'from' and the end of the block 4941 */ 4942 if (length > max || length < 0) 4943 length = max; 4944 4945 if (IS_DAX(inode)) { 4946 return dax_zero_range(inode, from, length, did_zero, 4947 ext4_iomap_next); 4948 } else if (ext4_should_journal_data(inode)) { 4949 return ext4_block_journalled_zero_range(inode, from, length, 4950 did_zero); 4951 } else if (ext4_inode_buffered_iomap(inode)) { 4952 return ext4_block_iomap_zero_range(inode, from, length, 4953 did_zero, zero_written); 4954 } 4955 return ext4_block_do_zero_range(inode, from, length, did_zero, 4956 zero_written); 4957 } 4958 4959 /* 4960 * Inodes using the iomap buffered I/O path do not use data=ordered mode. 4961 * Therefore, we mark the inode as disksize-grow-pending after zeroing the 4962 * EOF block. The zeroed block will be submitted before any subsequent 4963 * data. 4964 * 4965 * In the I/O completion path, ext4_iomap_wb_disksize_pending_wait() will 4966 * wait for I/O completion before advancing i_disksize if the write 4967 * extends beyond the zeroed boundary. 4968 * 4969 * When zeroed I/O is in progress, operations that extend i_disksize are 4970 * handled as follows: 4971 * 4972 * - Truncate up, append fallocate and zero_range: 4973 * Defer the update. The file size will be updated to i_size by the 4974 * end_io handler once the ongoing pending I/O completes. 4975 * 4976 * - Insert range and collapse range operations: 4977 * Wait synchronously for the relevant I/O to complete before updating 4978 * i_disksize. 4979 */ 4980 static int ext4_iomap_mark_disksize_pending(struct inode *inode, loff_t from) 4981 { 4982 struct folio *folio; 4983 4984 folio = filemap_lock_folio(inode->i_mapping, from >> PAGE_SHIFT); 4985 if (IS_ERR(folio)) 4986 /* Already in writeback and cleared? */ 4987 return PTR_ERR(folio) == -ENOENT ? 0 : PTR_ERR(folio); 4988 4989 /* 4990 * Ensure that in-flight writeback, possibly started after 4991 * iomap_zero_range() unlocked the folio, has completed. Without 4992 * this wait folio_test_dirty() below may miss the zeroed data 4993 * (writeback clears PG_dirty), causing us to skip the 4994 * disksize-grow-pending tracking and potentially expose stale 4995 * on-disk data. 4996 */ 4997 folio_wait_writeback(folio); 4998 WARN_ON_ONCE(folio_test_writeback(folio)); 4999 5000 /* 5001 * If the zeroed range does not overlap the existing on-disk tail 5002 * block, the zeroed data lies beyond the currently on-disk data 5003 * and will be written back before i_disksize is advanced past it, 5004 * so no stale data can be exposed. 5005 * 5006 * Checking i_disksize here (after folio_wait_writeback()) is 5007 * necessary and safe. If a delalloc writeback of this folio was 5008 * in-flight, it could be raced by a concurrent mmap write which 5009 * corrupts the tail block beyond i_size but the i_disksize is not 5010 * advanced. folio_wait_writeback() has waited for its completion 5011 * and the ioend has advanced i_disksize accordingly. If writeback 5012 * had not started, we don't need to mark any pending state because 5013 * any future writeback will carry the pagecache content that now 5014 * includes the zeroed data, so no stale data can appear on disk 5015 * even without the pending tracking. 5016 */ 5017 if (from >= round_up(READ_ONCE(EXT4_I(inode)->i_disksize), 5018 i_blocksize(inode))) 5019 goto out; 5020 5021 /* 5022 * Mark the inode as disksize-grow-pending. The zeroed block will 5023 * be written out by the generic writepages cycle or any other 5024 * syncing operation. 5025 * 5026 * Multiple overlapping unaligned EOF writes should not happen, 5027 * because we only mark the pending state after zeroing the on-disk 5028 * EOF block, and i_disksize can only be updated after the previous 5029 * zeroed pending block has been written back or the dirty folio 5030 * has been discarded. 5031 */ 5032 if (likely(folio_test_dirty(folio) && 5033 !ext4_test_inode_state(inode, 5034 EXT4_STATE_DISKSIZE_GROW_PENDING))) { 5035 trace_ext4_iomap_mark_disksize_pending(inode); 5036 ext4_set_inode_state(inode, EXT4_STATE_DISKSIZE_GROW_PENDING); 5037 } 5038 out: 5039 folio_unlock(folio); 5040 folio_put(folio); 5041 return 0; 5042 } 5043 5044 /* 5045 * Submit and wait for the pending zeroed EOF block range to complete 5046 * if the given range [@offset, @end) fully covers it. Must be called 5047 * outside the context of an active journal handle and hold the i_rwsem. 5048 */ 5049 int ext4_iomap_sync_zeroed_eof(struct inode *inode, loff_t offset, loff_t end) 5050 { 5051 loff_t pstart, plen; 5052 int ret; 5053 5054 if (!ext4_inode_buffered_iomap(inode)) 5055 return 0; 5056 5057 plen = ext4_iomap_get_disksize_pending_range(inode, &pstart); 5058 if (!plen || offset > pstart || end < pstart + plen) 5059 return 0; 5060 5061 ret = filemap_write_and_wait_range(inode->i_mapping, pstart, 5062 pstart + plen - 1); 5063 if (ret) 5064 return ret; 5065 5066 /* 5067 * The pending bit should have been cleared by the ioend worker, 5068 * which runs before the folio writeback flag is cleared. The 5069 * caller holds i_rwsem, so no concurrent ext4_block_zero_eof() 5070 * can re-set it. 5071 */ 5072 WARN_ON_ONCE(ext4_test_inode_state(inode, 5073 EXT4_STATE_DISKSIZE_GROW_PENDING)); 5074 return 0; 5075 } 5076 5077 /* 5078 * Zero out a mapping from file offset 'from' up to the end of the block 5079 * which corresponds to 'from' or to the given 'end' inside this block. 5080 * This required during truncate up and performing append writes. We need 5081 * to physically zero the tail end of that block so it doesn't yield old 5082 * data if the file is grown. 5083 */ 5084 int ext4_block_zero_eof(struct inode *inode, loff_t from, loff_t end) 5085 { 5086 unsigned int blocksize = i_blocksize(inode); 5087 unsigned int offset; 5088 loff_t length = end - from; 5089 bool did_zero = false; 5090 bool zero_written = false; 5091 int err; 5092 5093 offset = from & (blocksize - 1); 5094 if (!offset || from >= end) 5095 return 0; 5096 /* 5097 * Inline data has no tail block to zero out. Note that a race with 5098 * ext4_page_mkwrite() converting inline data to an extent without 5099 * holding i_rwsem is safe, as that path zeroes the full block before 5100 * copying in the inline data. 5101 */ 5102 if (ext4_has_inline_data(inode)) 5103 return 0; 5104 /* If we are processing an encrypted inode during orphan list handling */ 5105 if (IS_ENCRYPTED(inode) && !fscrypt_has_encryption_key(inode)) 5106 return 0; 5107 5108 if (length > blocksize - offset) 5109 length = blocksize - offset; 5110 5111 err = ext4_block_zero_range(inode, from, length, 5112 &did_zero, &zero_written); 5113 if (err) 5114 return err; 5115 /* 5116 * It's necessary to order zeroed data before update i_disksize when 5117 * truncating up or performing an append write, because there might be 5118 * exposing stale on-disk data which may caused by concurrent post-EOF 5119 * mmap write during folio writeback. 5120 */ 5121 if (did_zero && zero_written && !IS_DAX(inode)) { 5122 if (ext4_should_order_data(inode)) { 5123 handle_t *handle; 5124 5125 handle = ext4_journal_start(inode, EXT4_HT_MISC, 1); 5126 if (IS_ERR(handle)) 5127 return PTR_ERR(handle); 5128 5129 err = ext4_jbd2_inode_add_write(handle, inode, from, 5130 length); 5131 ext4_journal_stop(handle); 5132 } else if (ext4_inode_buffered_iomap(inode)) 5133 err = ext4_iomap_mark_disksize_pending(inode, from); 5134 if (err) 5135 return err; 5136 } 5137 5138 trace_ext4_block_zero_eof(inode, from, length, did_zero, zero_written); 5139 return 0; 5140 } 5141 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_block_zero_eof); 5142 5143 /* 5144 * Zero out the unaligned head and tail of the [lstart, lstart+length) 5145 * range. 5146 * 5147 * On return, @partial_zeroed records which edges actually got 5148 * partial-zeroed. Set EXT4_PARTIAL_ZERO_START/EXT4_PARTIAL_ZERO_END if 5149 * the head/tail block got actually partially zeroed (in written, dirty 5150 * unwritten or delalloc state). Cleared if the head/tail block is a 5151 * hole or a clean unwritten block, in which case there is nothing that 5152 * needs zeroing. When the head and tail land in the same block, both 5153 * bits are set together on a successful zeroing. 5154 */ 5155 int ext4_zero_partial_blocks(struct inode *inode, loff_t lstart, loff_t length, 5156 unsigned int *partial_zeroed) 5157 { 5158 struct super_block *sb = inode->i_sb; 5159 unsigned partial_start, partial_end; 5160 ext4_fsblk_t start, end; 5161 loff_t byte_end = (lstart + length - 1); 5162 bool did_zero = false; 5163 int err = 0; 5164 5165 partial_start = lstart & (sb->s_blocksize - 1); 5166 partial_end = byte_end & (sb->s_blocksize - 1); 5167 5168 start = lstart >> sb->s_blocksize_bits; 5169 end = byte_end >> sb->s_blocksize_bits; 5170 5171 /* Handle partial zero within the single block */ 5172 if (start == end && 5173 (partial_start || (partial_end != sb->s_blocksize - 1))) { 5174 err = ext4_block_zero_range(inode, lstart, length, &did_zero, 5175 NULL); 5176 if (did_zero) 5177 *partial_zeroed |= (EXT4_PARTIAL_ZERO_START | 5178 EXT4_PARTIAL_ZERO_END); 5179 return err; 5180 } 5181 /* Handle partial zero out on the start of the range */ 5182 if (partial_start) { 5183 err = ext4_block_zero_range(inode, lstart, sb->s_blocksize, 5184 &did_zero, NULL); 5185 if (err) 5186 return err; 5187 if (did_zero) 5188 *partial_zeroed |= EXT4_PARTIAL_ZERO_START; 5189 } 5190 /* Handle partial zero out on the end of the range */ 5191 if (partial_end != sb->s_blocksize - 1) { 5192 did_zero = false; 5193 err = ext4_block_zero_range(inode, byte_end - partial_end, 5194 partial_end + 1, &did_zero, NULL); 5195 if (err) 5196 return err; 5197 if (did_zero) 5198 *partial_zeroed |= EXT4_PARTIAL_ZERO_END; 5199 } 5200 return err; 5201 } 5202 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_zero_partial_blocks); 5203 5204 int ext4_can_truncate(struct inode *inode) 5205 { 5206 if (S_ISREG(inode->i_mode)) 5207 return 1; 5208 if (S_ISDIR(inode->i_mode)) 5209 return 1; 5210 if (S_ISLNK(inode->i_mode)) 5211 return !ext4_inode_is_fast_symlink(inode); 5212 return 0; 5213 } 5214 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_can_truncate); 5215 5216 /* 5217 * We have to make sure i_disksize gets properly updated before we truncate 5218 * page cache due to hole punching or zero range. Otherwise i_disksize update 5219 * can get lost as it may have been postponed to submission of writeback but 5220 * that will never happen if we remove the folio containing i_size from the 5221 * page cache. Also if we punch hole within i_size but above i_disksize, 5222 * following ext4_page_mkwrite() may mistakenly allocate written blocks over 5223 * the hole and thus introduce allocated blocks beyond i_disksize which is 5224 * not allowed (e2fsck would complain in case of crash). 5225 */ 5226 int ext4_update_disksize_before_punch(struct inode *inode, loff_t offset, 5227 loff_t len) 5228 { 5229 handle_t *handle; 5230 int ret; 5231 5232 loff_t size = i_size_read(inode); 5233 5234 WARN_ON(!inode_is_locked(inode)); 5235 if (offset > size) 5236 return 0; 5237 5238 /* 5239 * We are going to punch the pending zeroed EOF block, persist 5240 * it to ensure i_disksize can be safely updated thereafter. 5241 */ 5242 ret = ext4_iomap_sync_zeroed_eof(inode, offset, offset + len); 5243 if (ret) 5244 return ret; 5245 5246 if (offset + len < size) 5247 size = offset + len; 5248 if (EXT4_I(inode)->i_disksize >= size) 5249 return 0; 5250 5251 handle = ext4_journal_start(inode, EXT4_HT_MISC, 1); 5252 if (IS_ERR(handle)) 5253 return PTR_ERR(handle); 5254 ext4_update_i_disksize(inode, size); 5255 ret = ext4_mark_inode_dirty(handle, inode); 5256 ext4_journal_stop(handle); 5257 5258 return ret; 5259 } 5260 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_update_disksize_before_punch); 5261 5262 static inline void ext4_truncate_folio(struct inode *inode, 5263 loff_t start, loff_t end) 5264 { 5265 unsigned long blocksize = i_blocksize(inode); 5266 struct folio *folio; 5267 5268 /* Nothing to be done if no complete block needs to be truncated. */ 5269 if (round_up(start, blocksize) >= round_down(end, blocksize)) 5270 return; 5271 5272 folio = filemap_lock_folio(inode->i_mapping, start >> PAGE_SHIFT); 5273 if (IS_ERR(folio)) 5274 return; 5275 5276 if (folio_mkclean(folio)) 5277 folio_mark_dirty(folio); 5278 folio_unlock(folio); 5279 folio_put(folio); 5280 } 5281 5282 int ext4_truncate_page_cache_block_range(struct inode *inode, 5283 loff_t start, loff_t end) 5284 { 5285 unsigned long blocksize = i_blocksize(inode); 5286 int ret; 5287 5288 /* 5289 * For journalled data we need to write (and checkpoint) pages 5290 * before discarding page cache to avoid inconsitent data on disk 5291 * in case of crash before freeing or unwritten converting trans 5292 * is committed. 5293 */ 5294 if (ext4_should_journal_data(inode)) { 5295 ret = filemap_write_and_wait_range(inode->i_mapping, start, 5296 end - 1); 5297 if (ret) 5298 return ret; 5299 goto truncate_pagecache; 5300 } 5301 5302 /* 5303 * If the block size is less than the page size, the file's mapped 5304 * blocks within one page could be freed or converted to unwritten. 5305 * So it's necessary to remove writable userspace mappings, and then 5306 * ext4_page_mkwrite() can be called during subsequent write access 5307 * to these partial folios. 5308 */ 5309 if (!IS_ALIGNED(start | end, PAGE_SIZE) && 5310 blocksize < PAGE_SIZE && start < inode->i_size) { 5311 loff_t page_boundary = round_up(start, PAGE_SIZE); 5312 5313 ext4_truncate_folio(inode, start, min(page_boundary, end)); 5314 if (end > page_boundary) 5315 ext4_truncate_folio(inode, 5316 round_down(end, PAGE_SIZE), end); 5317 } 5318 5319 truncate_pagecache: 5320 truncate_pagecache_range(inode, start, end - 1); 5321 return 0; 5322 } 5323 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_truncate_page_cache_block_range); 5324 5325 static void ext4_wait_dax_page(struct inode *inode) 5326 { 5327 filemap_invalidate_unlock(inode->i_mapping); 5328 schedule(); 5329 filemap_invalidate_lock(inode->i_mapping); 5330 } 5331 5332 int ext4_break_layouts(struct inode *inode) 5333 { 5334 if (WARN_ON_ONCE(!rwsem_is_locked(&inode->i_mapping->invalidate_lock))) 5335 return -EINVAL; 5336 5337 return dax_break_layout_inode(inode, ext4_wait_dax_page); 5338 } 5339 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_break_layouts); 5340 5341 /* 5342 * ext4_punch_hole: punches a hole in a file by releasing the blocks 5343 * associated with the given offset and length 5344 * 5345 * @inode: File inode 5346 * @offset: The offset where the hole will begin 5347 * @len: The length of the hole 5348 * 5349 * Returns: 0 on success or negative on failure 5350 */ 5351 5352 int ext4_punch_hole(struct file *file, loff_t offset, loff_t length) 5353 { 5354 struct inode *inode = file_inode(file); 5355 struct super_block *sb = inode->i_sb; 5356 ext4_lblk_t start_lblk, end_lblk; 5357 loff_t max_end = sb->s_maxbytes; 5358 loff_t end = offset + length; 5359 handle_t *handle; 5360 unsigned int credits; 5361 unsigned int partial_zeroed = 0; 5362 int ret; 5363 5364 trace_ext4_punch_hole(inode, offset, length, 0); 5365 WARN_ON_ONCE(!inode_is_locked(inode)); 5366 5367 /* 5368 * For indirect-block based inodes, make sure that the hole within 5369 * one block before last range. 5370 */ 5371 if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) 5372 max_end = EXT4_SB(sb)->s_bitmap_maxbytes - sb->s_blocksize; 5373 5374 /* No need to punch hole beyond i_size */ 5375 if (offset >= inode->i_size || offset >= max_end) 5376 return 0; 5377 5378 /* 5379 * If the hole extends beyond i_size, set the hole to end after 5380 * the block that contains i_size to save pointless tail block zeroing. 5381 */ 5382 if (end >= inode->i_size) 5383 end = round_up(inode->i_size, sb->s_blocksize); 5384 if (end > max_end) 5385 end = max_end; 5386 length = end - offset; 5387 5388 ret = ext4_update_disksize_before_punch(inode, offset, length); 5389 if (ret) 5390 return ret; 5391 5392 /* Now release the pages and zero block aligned part of pages*/ 5393 ret = ext4_truncate_page_cache_block_range(inode, offset, end); 5394 if (ret) 5395 return ret; 5396 5397 ret = ext4_zero_partial_blocks(inode, offset, length, &partial_zeroed); 5398 if (ret) 5399 return ret; 5400 /* 5401 * On the iomap path, partial invalidate of a folio without an ifs 5402 * leaves sub-block dirty bits uncleared. Drain writeback before 5403 * removing extents so that any bio in flight on a partial folio 5404 * completes against blocks still owned by this inode. 5405 */ 5406 if (ext4_inode_buffered_iomap(inode) || 5407 (((file->f_flags & O_SYNC) || IS_SYNC(inode)) && partial_zeroed)) { 5408 ret = filemap_write_and_wait_range(inode->i_mapping, offset, 5409 end - 1); 5410 if (ret) 5411 return ret; 5412 } 5413 5414 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) 5415 credits = ext4_chunk_trans_extent(inode, 0); 5416 else 5417 credits = ext4_blocks_for_truncate(inode); 5418 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits); 5419 if (IS_ERR(handle)) { 5420 ret = PTR_ERR(handle); 5421 ext4_std_error(sb, ret); 5422 return ret; 5423 } 5424 5425 /* If there are blocks to remove, do it */ 5426 start_lblk = EXT4_B_TO_LBLK(inode, offset); 5427 end_lblk = end >> inode->i_blkbits; 5428 5429 if (end_lblk > start_lblk) { 5430 ext4_lblk_t hole_len = end_lblk - start_lblk; 5431 5432 ext4_fc_track_inode(handle, inode); 5433 ext4_check_map_extents_env(inode); 5434 down_write(&EXT4_I(inode)->i_data_sem); 5435 ext4_discard_preallocations(inode); 5436 5437 ext4_es_remove_extent(inode, start_lblk, hole_len); 5438 5439 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) 5440 ret = ext4_ext_remove_space(inode, start_lblk, 5441 end_lblk - 1); 5442 else 5443 ret = ext4_ind_remove_space(handle, inode, start_lblk, 5444 end_lblk); 5445 if (ret) { 5446 up_write(&EXT4_I(inode)->i_data_sem); 5447 goto out_handle; 5448 } 5449 5450 ext4_es_insert_extent(inode, start_lblk, hole_len, ~0, 5451 EXTENT_STATUS_HOLE, 0); 5452 up_write(&EXT4_I(inode)->i_data_sem); 5453 } 5454 ext4_fc_track_range(handle, inode, start_lblk, end_lblk); 5455 5456 ret = ext4_mark_inode_dirty(handle, inode); 5457 if (unlikely(ret)) 5458 goto out_handle; 5459 5460 ext4_update_inode_fsync_trans(handle, inode, 1); 5461 if ((file->f_flags & O_SYNC) || IS_SYNC(inode)) 5462 ext4_handle_sync(handle); 5463 out_handle: 5464 ext4_journal_stop(handle); 5465 return ret; 5466 } 5467 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_punch_hole); 5468 5469 int ext4_inode_attach_jinode(struct inode *inode) 5470 { 5471 struct ext4_inode_info *ei = EXT4_I(inode); 5472 struct jbd2_inode *jinode; 5473 5474 if (ei->jinode || !EXT4_SB(inode->i_sb)->s_journal) 5475 return 0; 5476 5477 jinode = jbd2_alloc_inode(GFP_KERNEL); 5478 spin_lock(&inode->i_lock); 5479 if (!ei->jinode) { 5480 if (!jinode) { 5481 spin_unlock(&inode->i_lock); 5482 return -ENOMEM; 5483 } 5484 jbd2_journal_init_jbd_inode(jinode, inode); 5485 /* 5486 * Publish ->jinode only after it is fully initialized so that 5487 * readers never observe a partially initialized jbd2_inode. 5488 */ 5489 smp_wmb(); 5490 WRITE_ONCE(ei->jinode, jinode); 5491 jinode = NULL; 5492 } 5493 spin_unlock(&inode->i_lock); 5494 if (unlikely(jinode != NULL)) 5495 jbd2_free_inode(jinode); 5496 return 0; 5497 } 5498 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_inode_attach_jinode); 5499 5500 /* 5501 * ext4_truncate() 5502 * 5503 * We block out ext4_get_block() block instantiations across the entire 5504 * transaction, and VFS/VM ensures that ext4_truncate() cannot run 5505 * simultaneously on behalf of the same inode. 5506 * 5507 * As we work through the truncate and commit bits of it to the journal there 5508 * is one core, guiding principle: the file's tree must always be consistent on 5509 * disk. We must be able to restart the truncate after a crash. 5510 * 5511 * The file's tree may be transiently inconsistent in memory (although it 5512 * probably isn't), but whenever we close off and commit a journal transaction, 5513 * the contents of (the filesystem + the journal) must be consistent and 5514 * restartable. It's pretty simple, really: bottom up, right to left (although 5515 * left-to-right works OK too). 5516 * 5517 * Note that at recovery time, journal replay occurs *before* the restart of 5518 * truncate against the orphan inode list. 5519 * 5520 * The committed inode has the new, desired i_size (which is the same as 5521 * i_disksize in this case). After a crash, ext4_orphan_cleanup() will see 5522 * that this inode's truncate did not complete and it will again call 5523 * ext4_truncate() to have another go. So there will be instantiated blocks 5524 * to the right of the truncation point in a crashed ext4 filesystem. But 5525 * that's fine - as long as they are linked from the inode, the post-crash 5526 * ext4_truncate() run will find them and release them. 5527 */ 5528 int ext4_truncate(struct inode *inode) 5529 { 5530 struct ext4_inode_info *ei = EXT4_I(inode); 5531 unsigned int credits; 5532 int err = 0, err2; 5533 handle_t *handle; 5534 5535 KUNIT_STATIC_STUB_REDIRECT(ext4_truncate, inode); 5536 5537 /* 5538 * There is a possibility that we're either freeing the inode 5539 * or it's a completely new inode. In those cases we might not 5540 * have i_rwsem locked because it's not necessary. 5541 */ 5542 if (!(inode_state_read_once(inode) & (I_NEW | I_FREEING))) 5543 WARN_ON(!inode_is_locked(inode)); 5544 trace_ext4_truncate_enter(inode); 5545 5546 if (!ext4_can_truncate(inode)) 5547 goto out_trace; 5548 5549 if (inode->i_size == 0 && !test_opt(inode->i_sb, NO_AUTO_DA_ALLOC)) 5550 ext4_set_inode_state(inode, EXT4_STATE_DA_ALLOC_CLOSE); 5551 5552 if (ext4_has_inline_data(inode)) { 5553 int has_inline = 1; 5554 5555 err = ext4_inline_data_truncate(inode, &has_inline); 5556 if (err || has_inline) 5557 goto out_trace; 5558 } 5559 5560 /* If we zero-out tail of the page, we have to create jinode for jbd2 */ 5561 if (inode->i_size & (inode->i_sb->s_blocksize - 1)) { 5562 err = ext4_inode_attach_jinode(inode); 5563 if (err) 5564 goto out_trace; 5565 5566 /* Zero to the end of the block containing i_size */ 5567 err = ext4_block_zero_eof(inode, inode->i_size, LLONG_MAX); 5568 if (err) 5569 goto out_trace; 5570 } 5571 5572 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) 5573 credits = ext4_chunk_trans_extent(inode, 1); 5574 else 5575 credits = ext4_blocks_for_truncate(inode); 5576 5577 handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits); 5578 if (IS_ERR(handle)) { 5579 err = PTR_ERR(handle); 5580 goto out_trace; 5581 } 5582 5583 /* 5584 * We add the inode to the orphan list, so that if this 5585 * truncate spans multiple transactions, and we crash, we will 5586 * resume the truncate when the filesystem recovers. It also 5587 * marks the inode dirty, to catch the new size. 5588 * 5589 * Implication: the file must always be in a sane, consistent 5590 * truncatable state while each transaction commits. 5591 */ 5592 err = ext4_orphan_add(handle, inode); 5593 if (err) 5594 goto out_stop; 5595 5596 ext4_fc_track_inode(handle, inode); 5597 ext4_check_map_extents_env(inode); 5598 5599 down_write(&EXT4_I(inode)->i_data_sem); 5600 ext4_discard_preallocations(inode); 5601 5602 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) 5603 err = ext4_ext_truncate(handle, inode); 5604 else 5605 ext4_ind_truncate(handle, inode); 5606 5607 up_write(&ei->i_data_sem); 5608 if (err) 5609 goto out_stop; 5610 5611 if (IS_SYNC(inode)) 5612 ext4_handle_sync(handle); 5613 5614 out_stop: 5615 /* 5616 * If this was a simple ftruncate() and the file will remain alive, 5617 * then we need to clear up the orphan record which we created above. 5618 * However, if this was a real unlink then we were called by 5619 * ext4_evict_inode(), and we allow that function to clean up the 5620 * orphan info for us. 5621 */ 5622 if (inode->i_nlink) 5623 ext4_orphan_del(handle, inode); 5624 5625 inode_set_mtime_to_ts(inode, inode_set_ctime_current(inode)); 5626 err2 = ext4_mark_inode_dirty(handle, inode); 5627 if (unlikely(err2 && !err)) 5628 err = err2; 5629 ext4_journal_stop(handle); 5630 5631 out_trace: 5632 trace_ext4_truncate_exit(inode); 5633 return err; 5634 } 5635 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_truncate); 5636 5637 static inline u64 ext4_inode_peek_iversion(const struct inode *inode) 5638 { 5639 if (unlikely(EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL)) 5640 return inode_peek_iversion_raw(inode); 5641 else 5642 return inode_peek_iversion(inode); 5643 } 5644 5645 static int ext4_inode_blocks_set(struct ext4_inode *raw_inode, 5646 struct ext4_inode_info *ei) 5647 { 5648 struct inode *inode = &(ei->vfs_inode); 5649 u64 i_blocks = READ_ONCE(inode->i_blocks); 5650 struct super_block *sb = inode->i_sb; 5651 5652 if (i_blocks <= ~0U) { 5653 /* 5654 * i_blocks can be represented in a 32 bit variable 5655 * as multiple of 512 bytes 5656 */ 5657 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks); 5658 raw_inode->i_blocks_high = 0; 5659 ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE); 5660 return 0; 5661 } 5662 5663 /* 5664 * This should never happen since sb->s_maxbytes should not have 5665 * allowed this, sb->s_maxbytes was set according to the huge_file 5666 * feature in ext4_fill_super(). 5667 */ 5668 if (!ext4_has_feature_huge_file(sb)) 5669 return -EFSCORRUPTED; 5670 5671 if (i_blocks <= 0xffffffffffffULL) { 5672 /* 5673 * i_blocks can be represented in a 48 bit variable 5674 * as multiple of 512 bytes 5675 */ 5676 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks); 5677 raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32); 5678 ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE); 5679 } else { 5680 ext4_set_inode_flag(inode, EXT4_INODE_HUGE_FILE); 5681 /* i_block is stored in file system block size */ 5682 i_blocks = i_blocks >> (inode->i_blkbits - 9); 5683 raw_inode->i_blocks_lo = cpu_to_le32(i_blocks); 5684 raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32); 5685 } 5686 return 0; 5687 } 5688 5689 static int ext4_fill_raw_inode(struct inode *inode, struct ext4_inode *raw_inode) 5690 { 5691 struct ext4_inode_info *ei = EXT4_I(inode); 5692 uid_t i_uid; 5693 gid_t i_gid; 5694 projid_t i_projid; 5695 int block; 5696 int err; 5697 5698 err = ext4_inode_blocks_set(raw_inode, ei); 5699 5700 raw_inode->i_mode = cpu_to_le16(inode->i_mode); 5701 i_uid = i_uid_read(inode); 5702 i_gid = i_gid_read(inode); 5703 i_projid = from_kprojid(&init_user_ns, ei->i_projid); 5704 if (!(test_opt(inode->i_sb, NO_UID32))) { 5705 raw_inode->i_uid_low = cpu_to_le16(low_16_bits(i_uid)); 5706 raw_inode->i_gid_low = cpu_to_le16(low_16_bits(i_gid)); 5707 /* 5708 * Fix up interoperability with old kernels. Otherwise, 5709 * old inodes get re-used with the upper 16 bits of the 5710 * uid/gid intact. 5711 */ 5712 if (ei->i_dtime && !ext4_inode_orphan_tracked(inode)) { 5713 raw_inode->i_uid_high = 0; 5714 raw_inode->i_gid_high = 0; 5715 } else { 5716 raw_inode->i_uid_high = 5717 cpu_to_le16(high_16_bits(i_uid)); 5718 raw_inode->i_gid_high = 5719 cpu_to_le16(high_16_bits(i_gid)); 5720 } 5721 } else { 5722 raw_inode->i_uid_low = cpu_to_le16(fs_high2lowuid(i_uid)); 5723 raw_inode->i_gid_low = cpu_to_le16(fs_high2lowgid(i_gid)); 5724 raw_inode->i_uid_high = 0; 5725 raw_inode->i_gid_high = 0; 5726 } 5727 raw_inode->i_links_count = cpu_to_le16(inode->i_nlink); 5728 5729 EXT4_INODE_SET_CTIME(inode, raw_inode); 5730 EXT4_INODE_SET_MTIME(inode, raw_inode); 5731 EXT4_INODE_SET_ATIME(inode, raw_inode); 5732 EXT4_EINODE_SET_XTIME(i_crtime, ei, raw_inode); 5733 5734 raw_inode->i_dtime = cpu_to_le32(ei->i_dtime); 5735 raw_inode->i_flags = cpu_to_le32(ei->i_flags & 0xFFFFFFFF); 5736 if (likely(!test_opt2(inode->i_sb, HURD_COMPAT))) 5737 raw_inode->i_file_acl_high = 5738 cpu_to_le16(ei->i_file_acl >> 32); 5739 raw_inode->i_file_acl_lo = cpu_to_le32(ei->i_file_acl); 5740 ext4_isize_set(raw_inode, ei->i_disksize); 5741 5742 raw_inode->i_generation = cpu_to_le32(inode->i_generation); 5743 if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) { 5744 if (old_valid_dev(inode->i_rdev)) { 5745 raw_inode->i_block[0] = 5746 cpu_to_le32(old_encode_dev(inode->i_rdev)); 5747 raw_inode->i_block[1] = 0; 5748 } else { 5749 raw_inode->i_block[0] = 0; 5750 raw_inode->i_block[1] = 5751 cpu_to_le32(new_encode_dev(inode->i_rdev)); 5752 raw_inode->i_block[2] = 0; 5753 } 5754 } else if (!ext4_has_inline_data(inode)) { 5755 for (block = 0; block < EXT4_N_BLOCKS; block++) 5756 raw_inode->i_block[block] = ei->i_data[block]; 5757 } 5758 5759 if (likely(!test_opt2(inode->i_sb, HURD_COMPAT))) { 5760 u64 ivers = ext4_inode_peek_iversion(inode); 5761 5762 raw_inode->i_disk_version = cpu_to_le32(ivers); 5763 if (ei->i_extra_isize) { 5764 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi)) 5765 raw_inode->i_version_hi = 5766 cpu_to_le32(ivers >> 32); 5767 raw_inode->i_extra_isize = 5768 cpu_to_le16(ei->i_extra_isize); 5769 } 5770 } 5771 5772 if (i_projid != EXT4_DEF_PROJID && 5773 !ext4_has_feature_project(inode->i_sb)) 5774 err = err ?: -EFSCORRUPTED; 5775 5776 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE && 5777 EXT4_FITS_IN_INODE(raw_inode, ei, i_projid)) 5778 raw_inode->i_projid = cpu_to_le32(i_projid); 5779 5780 ext4_inode_csum_set(inode, raw_inode, ei); 5781 return err; 5782 } 5783 5784 /* 5785 * ext4_get_inode_loc returns with an extra refcount against the inode's 5786 * underlying buffer_head on success. If we pass 'inode' and it does not 5787 * have in-inode xattr, we have all inode data in memory that is needed 5788 * to recreate the on-disk version of this inode. 5789 */ 5790 static int __ext4_get_inode_loc(struct super_block *sb, unsigned long ino, 5791 struct inode *inode, struct ext4_iloc *iloc, 5792 ext4_fsblk_t *ret_block) 5793 { 5794 struct ext4_group_desc *gdp; 5795 struct buffer_head *bh; 5796 ext4_fsblk_t block; 5797 struct blk_plug plug; 5798 int inodes_per_block, inode_offset; 5799 5800 iloc->bh = NULL; 5801 if (ino < EXT4_ROOT_INO || 5802 ino > le32_to_cpu(EXT4_SB(sb)->s_es->s_inodes_count)) 5803 return -EFSCORRUPTED; 5804 5805 iloc->block_group = (ino - 1) / EXT4_INODES_PER_GROUP(sb); 5806 gdp = ext4_get_group_desc(sb, iloc->block_group, NULL); 5807 if (!gdp) 5808 return -EIO; 5809 5810 /* 5811 * Figure out the offset within the block group inode table 5812 */ 5813 inodes_per_block = EXT4_SB(sb)->s_inodes_per_block; 5814 inode_offset = ((ino - 1) % 5815 EXT4_INODES_PER_GROUP(sb)); 5816 iloc->offset = (inode_offset % inodes_per_block) * EXT4_INODE_SIZE(sb); 5817 5818 block = ext4_inode_table(sb, gdp); 5819 if ((block <= le32_to_cpu(EXT4_SB(sb)->s_es->s_first_data_block)) || 5820 (block >= ext4_blocks_count(EXT4_SB(sb)->s_es))) { 5821 ext4_error(sb, "Invalid inode table block %llu in " 5822 "block_group %u", block, iloc->block_group); 5823 return -EFSCORRUPTED; 5824 } 5825 block += (inode_offset / inodes_per_block); 5826 5827 bh = ext4_sb_getblk(sb, block); 5828 if (unlikely(!bh)) 5829 return -ENOMEM; 5830 if (ext4_buffer_uptodate(bh)) 5831 goto has_buffer; 5832 5833 lock_buffer(bh); 5834 if (ext4_buffer_uptodate(bh)) { 5835 /* Someone brought it uptodate while we waited */ 5836 unlock_buffer(bh); 5837 goto has_buffer; 5838 } 5839 5840 /* 5841 * If we have all information of the inode in memory and this 5842 * is the only valid inode in the block, we need not read the 5843 * block. 5844 */ 5845 if (inode && !ext4_test_inode_state(inode, EXT4_STATE_XATTR)) { 5846 struct buffer_head *bitmap_bh; 5847 int i, start; 5848 5849 start = inode_offset & ~(inodes_per_block - 1); 5850 5851 /* 5852 * Is the inode bitmap in cache? Non-blocking lookup: bh above 5853 * is locked, and blocking here would folio_lock() against a 5854 * block_read_full_folio() that locks bh the other way round. 5855 */ 5856 bitmap_bh = ext4_sb_find_get_block(sb, 5857 ext4_inode_bitmap(sb, gdp)); 5858 if (unlikely(!bitmap_bh)) 5859 goto make_io; 5860 5861 /* 5862 * If the inode bitmap isn't in cache then the 5863 * optimisation may end up performing two reads instead 5864 * of one, so skip it. 5865 */ 5866 if (!buffer_uptodate(bitmap_bh)) { 5867 brelse(bitmap_bh); 5868 goto make_io; 5869 } 5870 for (i = start; i < start + inodes_per_block; i++) { 5871 if (i == inode_offset) 5872 continue; 5873 if (ext4_test_bit(i, bitmap_bh->b_data)) 5874 break; 5875 } 5876 brelse(bitmap_bh); 5877 if (i == start + inodes_per_block) { 5878 struct ext4_inode *raw_inode = 5879 (struct ext4_inode *) (bh->b_data + iloc->offset); 5880 5881 /* all other inodes are free, so skip I/O */ 5882 memset(bh->b_data, 0, bh->b_size); 5883 if (!ext4_test_inode_state(inode, EXT4_STATE_NEW)) 5884 ext4_fill_raw_inode(inode, raw_inode); 5885 set_buffer_uptodate(bh); 5886 unlock_buffer(bh); 5887 goto has_buffer; 5888 } 5889 } 5890 5891 make_io: 5892 /* 5893 * If we need to do any I/O, try to pre-readahead extra 5894 * blocks from the inode table. 5895 */ 5896 blk_start_plug(&plug); 5897 if (EXT4_SB(sb)->s_inode_readahead_blks) { 5898 ext4_fsblk_t b, end, table; 5899 unsigned num; 5900 __u32 ra_blks = EXT4_SB(sb)->s_inode_readahead_blks; 5901 5902 table = ext4_inode_table(sb, gdp); 5903 /* s_inode_readahead_blks is always a power of 2 */ 5904 b = block & ~((ext4_fsblk_t) ra_blks - 1); 5905 if (table > b) 5906 b = table; 5907 end = b + ra_blks; 5908 num = EXT4_INODES_PER_GROUP(sb); 5909 if (ext4_has_group_desc_csum(sb)) 5910 num -= ext4_itable_unused_count(sb, gdp); 5911 table += num / inodes_per_block; 5912 if (end > table) 5913 end = table; 5914 while (b <= end) 5915 ext4_sb_breadahead_unmovable(sb, b++); 5916 } 5917 5918 /* 5919 * There are other valid inodes in the buffer, this inode 5920 * has in-inode xattrs, or we don't have this inode in memory. 5921 * Read the block from disk. 5922 */ 5923 trace_ext4_load_inode(sb, ino); 5924 ext4_read_bh_nowait(bh, REQ_META | REQ_PRIO, NULL, 5925 ext4_simulate_fail(sb, EXT4_SIM_INODE_EIO)); 5926 blk_finish_plug(&plug); 5927 wait_on_buffer(bh); 5928 if (!buffer_uptodate(bh)) { 5929 if (ret_block) 5930 *ret_block = block; 5931 brelse(bh); 5932 return -EIO; 5933 } 5934 has_buffer: 5935 iloc->bh = bh; 5936 return 0; 5937 } 5938 5939 static int __ext4_get_inode_loc_noinmem(struct inode *inode, 5940 struct ext4_iloc *iloc) 5941 { 5942 ext4_fsblk_t err_blk = 0; 5943 int ret; 5944 5945 ret = __ext4_get_inode_loc(inode->i_sb, inode->i_ino, NULL, iloc, 5946 &err_blk); 5947 5948 if (ret == -EIO) 5949 ext4_error_inode_block(inode, err_blk, EIO, 5950 "unable to read itable block"); 5951 5952 return ret; 5953 } 5954 5955 int ext4_get_inode_loc(struct inode *inode, struct ext4_iloc *iloc) 5956 { 5957 ext4_fsblk_t err_blk = 0; 5958 int ret; 5959 5960 KUNIT_STATIC_STUB_REDIRECT(ext4_get_inode_loc, inode, iloc); 5961 5962 ret = __ext4_get_inode_loc(inode->i_sb, inode->i_ino, inode, iloc, 5963 &err_blk); 5964 5965 if (ret == -EIO) 5966 ext4_error_inode_block(inode, err_blk, EIO, 5967 "unable to read itable block"); 5968 5969 return ret; 5970 } 5971 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_get_inode_loc); 5972 5973 /* 5974 * ext4_get_inode_loc_noio() is a best-effort variant of ext4_get_inode_loc(). 5975 * It looks up the inode table block in the buffer cache and returns -EAGAIN if 5976 * the block is not present or not uptodate, without starting any I/O. It may 5977 * sleep on the folio lock of the block. 5978 */ 5979 int ext4_get_inode_loc_noio(struct inode *inode, struct ext4_iloc *iloc) 5980 { 5981 struct super_block *sb = inode->i_sb; 5982 struct ext4_group_desc *gdp; 5983 struct buffer_head *bh; 5984 ext4_fsblk_t block; 5985 int inodes_per_block, inode_offset; 5986 unsigned long ino = inode->i_ino; 5987 5988 KUNIT_STATIC_STUB_REDIRECT(ext4_get_inode_loc_noio, inode, iloc); 5989 5990 iloc->bh = NULL; 5991 if (ino < EXT4_ROOT_INO || 5992 ino > le32_to_cpu(EXT4_SB(sb)->s_es->s_inodes_count)) 5993 return -EFSCORRUPTED; 5994 5995 iloc->block_group = (ino - 1) / EXT4_INODES_PER_GROUP(sb); 5996 gdp = ext4_get_group_desc(sb, iloc->block_group, NULL); 5997 if (!gdp) 5998 return -EIO; 5999 6000 /* Figure out the offset within the block group inode table. */ 6001 inodes_per_block = EXT4_SB(sb)->s_inodes_per_block; 6002 inode_offset = ((ino - 1) % EXT4_INODES_PER_GROUP(sb)); 6003 iloc->offset = (inode_offset % inodes_per_block) * EXT4_INODE_SIZE(sb); 6004 6005 block = ext4_inode_table(sb, gdp); 6006 if (block <= le32_to_cpu(EXT4_SB(sb)->s_es->s_first_data_block) || 6007 block >= ext4_blocks_count(EXT4_SB(sb)->s_es)) { 6008 ext4_error(sb, 6009 "Invalid inode table block %llu in block_group %u", 6010 block, iloc->block_group); 6011 return -EFSCORRUPTED; 6012 } 6013 block += inode_offset / inodes_per_block; 6014 6015 bh = ext4_sb_find_get_block_nonatomic(sb, block); 6016 if (!bh) 6017 return -EAGAIN; 6018 if (!ext4_buffer_uptodate(bh)) { 6019 brelse(bh); 6020 return -EAGAIN; 6021 } 6022 6023 iloc->bh = bh; 6024 return 0; 6025 } 6026 6027 6028 int ext4_get_fc_inode_loc(struct super_block *sb, unsigned long ino, 6029 struct ext4_iloc *iloc) 6030 { 6031 KUNIT_STATIC_STUB_REDIRECT(ext4_get_fc_inode_loc, sb, ino, iloc); 6032 6033 return __ext4_get_inode_loc(sb, ino, NULL, iloc, NULL); 6034 } 6035 6036 static bool ext4_should_enable_dax(struct inode *inode) 6037 { 6038 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb); 6039 6040 if (test_opt2(inode->i_sb, DAX_NEVER)) 6041 return false; 6042 if (!S_ISREG(inode->i_mode)) 6043 return false; 6044 if (ext4_should_journal_data(inode)) 6045 return false; 6046 if (ext4_has_inline_data(inode)) 6047 return false; 6048 if (ext4_test_inode_flag(inode, EXT4_INODE_ENCRYPT)) 6049 return false; 6050 if (ext4_test_inode_flag(inode, EXT4_INODE_VERITY)) 6051 return false; 6052 if (!test_bit(EXT4_FLAGS_BDEV_IS_DAX, &sbi->s_ext4_flags)) 6053 return false; 6054 if (test_opt(inode->i_sb, DAX_ALWAYS)) 6055 return true; 6056 6057 return ext4_test_inode_flag(inode, EXT4_INODE_DAX); 6058 } 6059 6060 void ext4_set_inode_flags(struct inode *inode, bool init) 6061 { 6062 unsigned int flags = EXT4_I(inode)->i_flags; 6063 unsigned int new_fl = 0; 6064 6065 WARN_ON_ONCE(IS_DAX(inode) && init); 6066 6067 if (flags & EXT4_SYNC_FL) 6068 new_fl |= S_SYNC; 6069 if (flags & EXT4_APPEND_FL) 6070 new_fl |= S_APPEND; 6071 if (flags & EXT4_IMMUTABLE_FL) 6072 new_fl |= S_IMMUTABLE; 6073 if (flags & EXT4_NOATIME_FL) 6074 new_fl |= S_NOATIME; 6075 if (flags & EXT4_DIRSYNC_FL) 6076 new_fl |= S_DIRSYNC; 6077 6078 /* Because of the way inode_set_flags() works we must preserve S_DAX 6079 * here if already set. */ 6080 new_fl |= (inode->i_flags & S_DAX); 6081 if (init && ext4_should_enable_dax(inode)) 6082 new_fl |= S_DAX; 6083 6084 if (flags & EXT4_ENCRYPT_FL) 6085 new_fl |= S_ENCRYPTED; 6086 if (flags & EXT4_CASEFOLD_FL) 6087 new_fl |= S_CASEFOLD; 6088 if (flags & EXT4_VERITY_FL) 6089 new_fl |= S_VERITY; 6090 inode_set_flags(inode, new_fl, 6091 S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME|S_DIRSYNC|S_DAX| 6092 S_ENCRYPTED|S_CASEFOLD|S_VERITY); 6093 } 6094 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_set_inode_flags); 6095 6096 static blkcnt_t ext4_inode_blocks(struct ext4_inode *raw_inode, 6097 struct ext4_inode_info *ei) 6098 { 6099 blkcnt_t i_blocks ; 6100 struct inode *inode = &(ei->vfs_inode); 6101 struct super_block *sb = inode->i_sb; 6102 6103 if (ext4_has_feature_huge_file(sb)) { 6104 /* we are using combined 48 bit field */ 6105 i_blocks = ((u64)le16_to_cpu(raw_inode->i_blocks_high)) << 32 | 6106 le32_to_cpu(raw_inode->i_blocks_lo); 6107 if (ext4_test_inode_flag(inode, EXT4_INODE_HUGE_FILE)) { 6108 /* i_blocks represent file system block size */ 6109 return i_blocks << (inode->i_blkbits - 9); 6110 } else { 6111 return i_blocks; 6112 } 6113 } else { 6114 return le32_to_cpu(raw_inode->i_blocks_lo); 6115 } 6116 } 6117 6118 static inline int ext4_iget_extra_inode(struct inode *inode, 6119 struct ext4_inode *raw_inode, 6120 struct ext4_inode_info *ei) 6121 { 6122 __le32 *magic = (void *)raw_inode + 6123 EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize; 6124 6125 if (EXT4_INODE_HAS_XATTR_SPACE(inode) && 6126 *magic == cpu_to_le32(EXT4_XATTR_MAGIC)) { 6127 int err; 6128 6129 err = xattr_check_inode(inode, IHDR(inode, raw_inode), 6130 ITAIL(inode, raw_inode)); 6131 if (err) 6132 return err; 6133 6134 ext4_set_inode_state(inode, EXT4_STATE_XATTR); 6135 err = ext4_find_inline_data_nolock(inode); 6136 if (!err && ext4_has_inline_data(inode)) 6137 ext4_set_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA); 6138 return err; 6139 } else 6140 EXT4_I(inode)->i_inline_off = 0; 6141 return 0; 6142 } 6143 6144 int ext4_get_projid(struct inode *inode, kprojid_t *projid) 6145 { 6146 if (!ext4_has_feature_project(inode->i_sb)) 6147 return -EOPNOTSUPP; 6148 *projid = EXT4_I(inode)->i_projid; 6149 return 0; 6150 } 6151 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_get_projid); 6152 6153 /* 6154 * ext4 has self-managed i_version for ea inodes, it stores the lower 32bit of 6155 * refcount in i_version, so use raw values if inode has EXT4_EA_INODE_FL flag 6156 * set. 6157 */ 6158 static inline void ext4_inode_set_iversion_queried(struct inode *inode, u64 val) 6159 { 6160 if (unlikely(EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL)) 6161 inode_set_iversion_raw(inode, val); 6162 else 6163 inode_set_iversion_queried(inode, val); 6164 } 6165 6166 static int check_igot_inode(struct inode *inode, ext4_iget_flags flags, 6167 const char *function, unsigned int line) 6168 { 6169 const char *err_str; 6170 6171 if (flags & EXT4_IGET_EA_INODE) { 6172 if (!(EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL)) { 6173 err_str = "missing EA_INODE flag"; 6174 goto error; 6175 } 6176 if (ext4_test_inode_state(inode, EXT4_STATE_XATTR) || 6177 EXT4_I(inode)->i_file_acl) { 6178 err_str = "ea_inode with extended attributes"; 6179 goto error; 6180 } 6181 } else { 6182 if ((EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL)) { 6183 /* 6184 * open_by_handle_at() could provide an old inode number 6185 * that has since been reused for an ea_inode; this does 6186 * not indicate filesystem corruption 6187 */ 6188 if (flags & EXT4_IGET_HANDLE) 6189 return -ESTALE; 6190 err_str = "unexpected EA_INODE flag"; 6191 goto error; 6192 } 6193 } 6194 if (is_bad_inode(inode) && !(flags & EXT4_IGET_BAD)) { 6195 err_str = "unexpected bad inode w/o EXT4_IGET_BAD"; 6196 goto error; 6197 } 6198 return 0; 6199 6200 error: 6201 ext4_error_inode(inode, function, line, 0, "%s", err_str); 6202 return -EFSCORRUPTED; 6203 } 6204 6205 /* 6206 * Determine whether an inode should use the iomap buffered I/O path. 6207 * EXT4_STATE_BUFFERED_IOMAP is generally set at inode initialization 6208 * time. Online switching of the buffered I/O path on an active inode is 6209 * NOT supported, with the exception of changing a per-inode journal 6210 * flag. 6211 * 6212 * For features like inline data, fsverity, and encryption that can be 6213 * dynamically enabled or disabled, we check the superblock-level 6214 * feature flags. If any of these is globally enabled, no inode is 6215 * allowed into the iomap buffered I/O path. This avoids the complexity 6216 * of dynamic toggling. 6217 * 6218 * For the global data journal mode (EXT4_MOUNT_JOURNAL_DATA), dynamic 6219 * change through remount is deferred. It will only become available 6220 * after the inode is re-initialized (i.e., after the last reference 6221 * drops and the inode is re-read from disk with the journal flag 6222 * cleared). 6223 * 6224 * For the per-inode data journal mode (EXT4_INODE_JOURNAL_DATA), 6225 * dynamic changes take effect immediately. This is safe because 6226 * address_space operations can be switched and all page cache can be 6227 * dropped under i_rwsem and filemap_invalidate_lock. 6228 * 6229 * For extent-to-indirect block migration (via EXT4_IOC_SETFLAGS 6230 * clearing EXT4_EXTENTS_FL), this operation is directly rejected for 6231 * inodes using the iomap path. 6232 * 6233 * When remounting to toggle the buffered_iomap mount option, the change 6234 * of I/O path is deferred as well, it will be available after the inode 6235 * is re-initialized. 6236 */ 6237 void ext4_enable_buffered_iomap(struct inode *inode) 6238 { 6239 struct super_block *sb = inode->i_sb; 6240 6241 if (!test_opt2(sb, BUFFERED_IOMAP)) 6242 return; 6243 if (!S_ISREG(inode->i_mode)) 6244 return; 6245 if (ext4_test_inode_flag(inode, EXT4_INODE_EA_INODE)) 6246 return; 6247 6248 /* Unsupported Features */ 6249 if (ext4_has_feature_inline_data(sb)) 6250 return; 6251 if (ext4_has_feature_verity(sb)) 6252 return; 6253 if (ext4_has_feature_encrypt(sb)) 6254 return; 6255 if (test_opt(sb, DATA_FLAGS) == EXT4_MOUNT_JOURNAL_DATA || 6256 ext4_test_inode_flag(inode, EXT4_INODE_JOURNAL_DATA)) 6257 return; 6258 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) 6259 return; 6260 6261 ext4_set_inode_state(inode, EXT4_STATE_BUFFERED_IOMAP); 6262 6263 /* 6264 * Install the iomap end_io handler on the shared conversion 6265 * work. This is safe at inode initialization and during the 6266 * buffered I/O path changes where we flush all pending 6267 * writebacks and drop page cache under i_rwsem and 6268 * filemap_invalidate_lock. 6269 */ 6270 INIT_WORK(&EXT4_I(inode)->i_rsv_conversion_work, ext4_iomap_end_io); 6271 } 6272 6273 static void ext4_disable_buffered_iomap(struct inode *inode) 6274 { 6275 ext4_clear_inode_state(inode, EXT4_STATE_BUFFERED_IOMAP); 6276 6277 /* 6278 * Reinstall the buffer_head end_io handler on the shared 6279 * conversion work. This is safe during the buffered I/O path 6280 * changes where we flush all pending writebacks and drop page 6281 * cache under i_rwsem and filemap_invalidate_lock. 6282 */ 6283 INIT_WORK(&EXT4_I(inode)->i_rsv_conversion_work, ext4_end_io_rsv_work); 6284 } 6285 6286 void ext4_set_inode_mapping_order(struct inode *inode) 6287 { 6288 struct super_block *sb = inode->i_sb; 6289 u16 min_order, max_order; 6290 6291 max_order = EXT4_SB(sb)->s_max_folio_order; 6292 if (!max_order) 6293 return; 6294 6295 min_order = EXT4_SB(sb)->s_min_folio_order; 6296 if (!min_order && !S_ISREG(inode->i_mode)) 6297 return; 6298 6299 if (ext4_test_inode_flag(inode, EXT4_INODE_JOURNAL_DATA)) 6300 max_order = min_order; 6301 6302 mapping_set_folio_order_range(inode->i_mapping, min_order, max_order); 6303 } 6304 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_set_inode_mapping_order); 6305 6306 static int ext4_iget_match(struct inode *inode, u64 ino, void *data) 6307 { 6308 if (inode->i_ino != ino) 6309 return 0; 6310 spin_lock(&inode->i_lock); 6311 if (inode_state_read(inode) & (I_FREEING | I_WILL_FREE | I_CREATING)) { 6312 spin_unlock(&inode->i_lock); 6313 return -1; 6314 } 6315 __iget(inode); 6316 spin_unlock(&inode->i_lock); 6317 return 1; 6318 } 6319 6320 struct inode *__ext4_iget(struct super_block *sb, unsigned long ino, 6321 ext4_iget_flags flags, const char *function, 6322 unsigned int line) 6323 { 6324 struct ext4_iloc iloc; 6325 struct ext4_inode *raw_inode; 6326 struct ext4_inode_info *ei; 6327 struct ext4_super_block *es = EXT4_SB(sb)->s_es; 6328 struct inode *inode; 6329 journal_t *journal = EXT4_SB(sb)->s_journal; 6330 long ret; 6331 loff_t size; 6332 int block; 6333 uid_t i_uid; 6334 gid_t i_gid; 6335 projid_t i_projid; 6336 6337 KUNIT_STATIC_STUB_REDIRECT(__ext4_iget, sb, ino, flags, function, line); 6338 6339 if ((!(flags & EXT4_IGET_SPECIAL) && is_special_ino(sb, ino)) || 6340 (ino < EXT4_ROOT_INO) || 6341 (ino > le32_to_cpu(es->s_inodes_count))) { 6342 if (flags & EXT4_IGET_HANDLE) 6343 return ERR_PTR(-ESTALE); 6344 __ext4_error(sb, function, line, false, EFSCORRUPTED, 0, 6345 "inode #%lu: comm %s: iget: illegal inode #", 6346 ino, current->comm); 6347 return ERR_PTR(-EFSCORRUPTED); 6348 } 6349 6350 if (flags & EXT4_IGET_NOWAIT) { 6351 inode = find_inode_nowait(sb, ino, ext4_iget_match, NULL); 6352 if (!inode) 6353 return ERR_PTR(-ENOENT); 6354 6355 if (inode_state_read_once(inode) & I_NEW) 6356 wait_on_new_inode(inode); 6357 6358 if (unlikely(inode_unhashed(inode))) { 6359 iput(inode); 6360 return ERR_PTR(-ENOENT); 6361 } 6362 } else { 6363 inode = iget_locked(sb, ino); 6364 if (!inode) 6365 return ERR_PTR(-ENOMEM); 6366 } 6367 6368 if (!(inode_state_read_once(inode) & I_NEW)) { 6369 ret = check_igot_inode(inode, flags, function, line); 6370 if (ret) { 6371 iput(inode); 6372 return ERR_PTR(ret); 6373 } 6374 return inode; 6375 } 6376 6377 ei = EXT4_I(inode); 6378 iloc.bh = NULL; 6379 6380 ret = __ext4_get_inode_loc_noinmem(inode, &iloc); 6381 if (ret < 0) 6382 goto bad_inode; 6383 raw_inode = ext4_raw_inode(&iloc); 6384 6385 if ((flags & EXT4_IGET_HANDLE) && 6386 (raw_inode->i_links_count == 0) && (raw_inode->i_mode == 0)) { 6387 ret = -ESTALE; 6388 goto bad_inode; 6389 } 6390 6391 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) { 6392 ei->i_extra_isize = le16_to_cpu(raw_inode->i_extra_isize); 6393 if (EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize > 6394 EXT4_INODE_SIZE(inode->i_sb) || 6395 (ei->i_extra_isize & 3)) { 6396 ext4_error_inode(inode, function, line, 0, 6397 "iget: bad extra_isize %u " 6398 "(inode size %u)", 6399 ei->i_extra_isize, 6400 EXT4_INODE_SIZE(inode->i_sb)); 6401 ret = -EFSCORRUPTED; 6402 goto bad_inode; 6403 } 6404 } else 6405 ei->i_extra_isize = 0; 6406 6407 /* Precompute checksum seed for inode metadata */ 6408 if (ext4_has_feature_metadata_csum(sb)) { 6409 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb); 6410 __u32 csum; 6411 __le32 inum = cpu_to_le32(inode->i_ino); 6412 __le32 gen = raw_inode->i_generation; 6413 csum = ext4_chksum(sbi->s_csum_seed, (__u8 *)&inum, 6414 sizeof(inum)); 6415 ei->i_csum_seed = ext4_chksum(csum, (__u8 *)&gen, sizeof(gen)); 6416 } 6417 6418 if ((!ext4_inode_csum_verify(inode, raw_inode, ei) || 6419 ext4_simulate_fail(sb, EXT4_SIM_INODE_CRC)) && 6420 (!(EXT4_SB(sb)->s_mount_state & EXT4_FC_REPLAY))) { 6421 ext4_error_inode_err(inode, function, line, 0, 6422 EFSBADCRC, "iget: checksum invalid"); 6423 ret = -EFSBADCRC; 6424 goto bad_inode; 6425 } 6426 6427 inode->i_mode = le16_to_cpu(raw_inode->i_mode); 6428 i_uid = (uid_t)le16_to_cpu(raw_inode->i_uid_low); 6429 i_gid = (gid_t)le16_to_cpu(raw_inode->i_gid_low); 6430 if (ext4_has_feature_project(sb) && 6431 EXT4_INODE_SIZE(sb) > EXT4_GOOD_OLD_INODE_SIZE && 6432 EXT4_FITS_IN_INODE(raw_inode, ei, i_projid)) 6433 i_projid = (projid_t)le32_to_cpu(raw_inode->i_projid); 6434 else 6435 i_projid = EXT4_DEF_PROJID; 6436 6437 if (!(test_opt(inode->i_sb, NO_UID32))) { 6438 i_uid |= le16_to_cpu(raw_inode->i_uid_high) << 16; 6439 i_gid |= le16_to_cpu(raw_inode->i_gid_high) << 16; 6440 } 6441 i_uid_write(inode, i_uid); 6442 i_gid_write(inode, i_gid); 6443 ei->i_projid = make_kprojid(&init_user_ns, i_projid); 6444 set_nlink(inode, le16_to_cpu(raw_inode->i_links_count)); 6445 6446 ei->i_inline_off = 0; 6447 ei->i_dir_start_lookup = 0; 6448 ei->i_dtime = le32_to_cpu(raw_inode->i_dtime); 6449 /* We now have enough fields to check if the inode was active or not. 6450 * This is needed because nfsd might try to access dead inodes 6451 * the test is that same one that e2fsck uses 6452 * NeilBrown 1999oct15 6453 */ 6454 if (inode->i_nlink == 0) { 6455 if ((inode->i_mode == 0 || flags & EXT4_IGET_SPECIAL || 6456 !(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_ORPHAN_FS)) && 6457 ino != EXT4_BOOT_LOADER_INO) { 6458 /* this inode is deleted or unallocated */ 6459 if (flags & EXT4_IGET_SPECIAL) { 6460 ext4_error_inode(inode, function, line, 0, 6461 "iget: special inode unallocated"); 6462 ret = -EFSCORRUPTED; 6463 } else 6464 ret = -ESTALE; 6465 goto bad_inode; 6466 } 6467 /* The only unlinked inodes we let through here have 6468 * valid i_mode and are being read by the orphan 6469 * recovery code: that's fine, we're about to complete 6470 * the process of deleting those. 6471 * OR it is the EXT4_BOOT_LOADER_INO which is 6472 * not initialized on a new filesystem. */ 6473 } 6474 ei->i_flags = le32_to_cpu(raw_inode->i_flags); 6475 ext4_set_inode_flags(inode, true); 6476 /* Detect invalid flag combination - can't have both inline data and extents */ 6477 if (ext4_test_inode_flag(inode, EXT4_INODE_INLINE_DATA) && 6478 ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) { 6479 ext4_error_inode(inode, function, line, 0, 6480 "inode has both inline data and extents flags"); 6481 ret = -EFSCORRUPTED; 6482 goto bad_inode; 6483 } 6484 inode->i_blocks = ext4_inode_blocks(raw_inode, ei); 6485 ei->i_file_acl = le32_to_cpu(raw_inode->i_file_acl_lo); 6486 if (ext4_has_feature_64bit(sb)) 6487 ei->i_file_acl |= 6488 ((__u64)le16_to_cpu(raw_inode->i_file_acl_high)) << 32; 6489 inode->i_size = ext4_isize(sb, raw_inode); 6490 size = i_size_read(inode); 6491 if (size < 0 || size > ext4_get_maxbytes(inode)) { 6492 ext4_error_inode(inode, function, line, 0, 6493 "iget: bad i_size value: %lld", size); 6494 ret = -EFSCORRUPTED; 6495 goto bad_inode; 6496 } 6497 /* 6498 * If dir_index is not enabled but there's dir with INDEX flag set, 6499 * we'd normally treat htree data as empty space. But with metadata 6500 * checksumming that corrupts checksums so forbid that. 6501 */ 6502 if (!ext4_has_feature_dir_index(sb) && 6503 ext4_has_feature_metadata_csum(sb) && 6504 ext4_test_inode_flag(inode, EXT4_INODE_INDEX)) { 6505 ext4_error_inode(inode, function, line, 0, 6506 "iget: Dir with htree data on filesystem without dir_index feature."); 6507 ret = -EFSCORRUPTED; 6508 goto bad_inode; 6509 } 6510 ei->i_disksize = inode->i_size; 6511 #ifdef CONFIG_QUOTA 6512 ei->i_reserved_quota = 0; 6513 #endif 6514 inode->i_generation = le32_to_cpu(raw_inode->i_generation); 6515 ei->i_block_group = iloc.block_group; 6516 ei->i_last_alloc_group = ~0; 6517 /* 6518 * NOTE! The in-memory inode i_data array is in little-endian order 6519 * even on big-endian machines: we do NOT byteswap the block numbers! 6520 */ 6521 for (block = 0; block < EXT4_N_BLOCKS; block++) 6522 ei->i_data[block] = raw_inode->i_block[block]; 6523 INIT_LIST_HEAD(&ei->i_orphan); 6524 ext4_fc_init_inode(&ei->vfs_inode); 6525 6526 /* 6527 * Set transaction id's of transactions that have to be committed 6528 * to finish f[data]sync. We set them to currently running transaction 6529 * as we cannot be sure that the inode or some of its metadata isn't 6530 * part of the transaction - the inode could have been reclaimed and 6531 * now it is reread from disk. 6532 */ 6533 if (journal) { 6534 transaction_t *transaction; 6535 tid_t tid; 6536 6537 read_lock(&journal->j_state_lock); 6538 if (journal->j_running_transaction) 6539 transaction = journal->j_running_transaction; 6540 else 6541 transaction = journal->j_committing_transaction; 6542 if (transaction) 6543 tid = transaction->t_tid; 6544 else 6545 tid = journal->j_commit_sequence; 6546 read_unlock(&journal->j_state_lock); 6547 ei->i_sync_tid = tid; 6548 ei->i_datasync_tid = tid; 6549 } 6550 6551 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) { 6552 if (ei->i_extra_isize == 0) { 6553 /* The extra space is currently unused. Use it. */ 6554 BUILD_BUG_ON(sizeof(struct ext4_inode) & 3); 6555 ei->i_extra_isize = sizeof(struct ext4_inode) - 6556 EXT4_GOOD_OLD_INODE_SIZE; 6557 } else { 6558 ret = ext4_iget_extra_inode(inode, raw_inode, ei); 6559 if (ret) 6560 goto bad_inode; 6561 } 6562 } 6563 6564 EXT4_INODE_GET_CTIME(inode, raw_inode); 6565 EXT4_INODE_GET_ATIME(inode, raw_inode); 6566 EXT4_INODE_GET_MTIME(inode, raw_inode); 6567 EXT4_EINODE_GET_XTIME(i_crtime, ei, raw_inode); 6568 6569 if (likely(!test_opt2(inode->i_sb, HURD_COMPAT))) { 6570 u64 ivers = le32_to_cpu(raw_inode->i_disk_version); 6571 6572 if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) { 6573 if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi)) 6574 ivers |= 6575 (__u64)(le32_to_cpu(raw_inode->i_version_hi)) << 32; 6576 } 6577 ext4_inode_set_iversion_queried(inode, ivers); 6578 } 6579 6580 ret = 0; 6581 if (ei->i_file_acl && 6582 !ext4_inode_block_valid(inode, ei->i_file_acl, 1)) { 6583 ext4_error_inode(inode, function, line, 0, 6584 "iget: bad extended attribute block %llu", 6585 ei->i_file_acl); 6586 ret = -EFSCORRUPTED; 6587 goto bad_inode; 6588 } else if (!ext4_has_inline_data(inode)) { 6589 /* validate the block references in the inode */ 6590 if (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) || 6591 (S_ISLNK(inode->i_mode) && 6592 !ext4_inode_is_fast_symlink(inode))) { 6593 if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) 6594 ret = ext4_ext_check_inode(inode); 6595 else 6596 ret = ext4_ind_check_inode(inode); 6597 } 6598 } 6599 if (ret) 6600 goto bad_inode; 6601 6602 ext4_enable_buffered_iomap(inode); 6603 6604 if (S_ISREG(inode->i_mode)) { 6605 inode->i_op = &ext4_file_inode_operations; 6606 inode->i_fop = &ext4_file_operations; 6607 ext4_set_aops(inode); 6608 } else if (S_ISDIR(inode->i_mode)) { 6609 inode->i_op = &ext4_dir_inode_operations; 6610 inode->i_fop = &ext4_dir_operations; 6611 } else if (S_ISLNK(inode->i_mode)) { 6612 /* VFS does not allow setting these so must be corruption */ 6613 if (IS_APPEND(inode) || IS_IMMUTABLE(inode)) { 6614 ext4_error_inode(inode, function, line, 0, 6615 "iget: immutable or append flags " 6616 "not allowed on symlinks"); 6617 ret = -EFSCORRUPTED; 6618 goto bad_inode; 6619 } 6620 if (IS_ENCRYPTED(inode)) { 6621 inode->i_op = &ext4_encrypted_symlink_inode_operations; 6622 } else if (ext4_inode_is_fast_symlink(inode)) { 6623 inode->i_op = &ext4_fast_symlink_inode_operations; 6624 6625 /* 6626 * Orphan cleanup can see inodes with i_size == 0 6627 * and i_data uninitialized. Skip size checks in 6628 * that case. This is safe because the first thing 6629 * ext4_evict_inode() does for fast symlinks is 6630 * clearing of i_data and i_size. 6631 */ 6632 if ((EXT4_SB(sb)->s_mount_state & EXT4_ORPHAN_FS)) { 6633 if (inode->i_nlink != 0) { 6634 ext4_error_inode(inode, function, line, 0, 6635 "invalid orphan symlink nlink %d", 6636 inode->i_nlink); 6637 ret = -EFSCORRUPTED; 6638 goto bad_inode; 6639 } 6640 } else { 6641 if (inode->i_size == 0 || 6642 inode->i_size >= sizeof(ei->i_data) || 6643 strnlen((char *)ei->i_data, inode->i_size + 1) != 6644 inode->i_size) { 6645 ext4_error_inode(inode, function, line, 0, 6646 "invalid fast symlink length %llu", 6647 (unsigned long long)inode->i_size); 6648 ret = -EFSCORRUPTED; 6649 goto bad_inode; 6650 } 6651 inode_set_cached_link(inode, (char *)ei->i_data, 6652 inode->i_size); 6653 } 6654 } else { 6655 inode->i_op = &ext4_symlink_inode_operations; 6656 } 6657 } else if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode) || 6658 S_ISFIFO(inode->i_mode) || S_ISSOCK(inode->i_mode)) { 6659 inode->i_op = &ext4_special_inode_operations; 6660 if (raw_inode->i_block[0]) 6661 init_special_inode(inode, inode->i_mode, 6662 old_decode_dev(le32_to_cpu(raw_inode->i_block[0]))); 6663 else 6664 init_special_inode(inode, inode->i_mode, 6665 new_decode_dev(le32_to_cpu(raw_inode->i_block[1]))); 6666 } else if (ino == EXT4_BOOT_LOADER_INO) { 6667 make_bad_inode(inode); 6668 } else { 6669 ret = -EFSCORRUPTED; 6670 ext4_error_inode(inode, function, line, 0, 6671 "iget: bogus i_mode (%o)", inode->i_mode); 6672 goto bad_inode; 6673 } 6674 if (IS_CASEFOLDED(inode) && !ext4_has_feature_casefold(inode->i_sb)) { 6675 ext4_error_inode(inode, function, line, 0, 6676 "casefold flag without casefold feature"); 6677 ret = -EFSCORRUPTED; 6678 goto bad_inode; 6679 } 6680 if (IS_ENCRYPTED(inode) && sb->s_blocksize > PAGE_SIZE) { 6681 ext4_error_inode(inode, function, line, 0, 6682 "encrypted inode with block size larger than page size"); 6683 ret = -EFSCORRUPTED; 6684 goto bad_inode; 6685 } 6686 6687 ext4_set_inode_mapping_order(inode); 6688 6689 ret = check_igot_inode(inode, flags, function, line); 6690 /* 6691 * -ESTALE here means there is nothing inherently wrong with the inode, 6692 * it's just not an inode we can return for an fhandle lookup. 6693 */ 6694 if (ret == -ESTALE) { 6695 brelse(iloc.bh); 6696 unlock_new_inode(inode); 6697 iput(inode); 6698 return ERR_PTR(-ESTALE); 6699 } 6700 if (ret) 6701 goto bad_inode; 6702 brelse(iloc.bh); 6703 /* Initialize the "no ACL's" state for the simple cases */ 6704 if (!ext4_test_inode_state(inode, EXT4_STATE_XATTR) && !ei->i_file_acl) 6705 cache_no_acl(inode); 6706 unlock_new_inode(inode); 6707 return inode; 6708 6709 bad_inode: 6710 brelse(iloc.bh); 6711 iget_failed(inode); 6712 return ERR_PTR(ret); 6713 } 6714 EXPORT_SYMBOL_FOR_EXT4_TEST(__ext4_iget); 6715 6716 static void __ext4_update_other_inode_time(struct super_block *sb, 6717 unsigned long orig_ino, 6718 unsigned long ino, 6719 struct ext4_inode *raw_inode) 6720 { 6721 struct inode *inode; 6722 6723 inode = find_inode_by_ino_rcu(sb, ino); 6724 if (!inode) 6725 return; 6726 6727 if (!inode_is_dirtytime_only(inode)) 6728 return; 6729 6730 spin_lock(&inode->i_lock); 6731 if (inode_is_dirtytime_only(inode)) { 6732 struct ext4_inode_info *ei = EXT4_I(inode); 6733 6734 inode_state_clear(inode, I_DIRTY_TIME); 6735 spin_unlock(&inode->i_lock); 6736 6737 spin_lock(&ei->i_raw_lock); 6738 EXT4_INODE_SET_CTIME(inode, raw_inode); 6739 EXT4_INODE_SET_MTIME(inode, raw_inode); 6740 EXT4_INODE_SET_ATIME(inode, raw_inode); 6741 ext4_inode_csum_set(inode, raw_inode, ei); 6742 spin_unlock(&ei->i_raw_lock); 6743 trace_ext4_other_inode_update_time(inode, orig_ino); 6744 return; 6745 } 6746 spin_unlock(&inode->i_lock); 6747 } 6748 6749 /* 6750 * Opportunistically update the other time fields for other inodes in 6751 * the same inode table block. 6752 */ 6753 static void ext4_update_other_inodes_time(struct super_block *sb, 6754 unsigned long orig_ino, char *buf) 6755 { 6756 unsigned long ino; 6757 int i, inodes_per_block = EXT4_SB(sb)->s_inodes_per_block; 6758 int inode_size = EXT4_INODE_SIZE(sb); 6759 6760 /* 6761 * Calculate the first inode in the inode table block. Inode 6762 * numbers are one-based. That is, the first inode in a block 6763 * (assuming 4k blocks and 256 byte inodes) is (n*16 + 1). 6764 */ 6765 ino = ((orig_ino - 1) & ~(inodes_per_block - 1)) + 1; 6766 rcu_read_lock(); 6767 for (i = 0; i < inodes_per_block; i++, ino++, buf += inode_size) { 6768 if (ino == orig_ino) 6769 continue; 6770 __ext4_update_other_inode_time(sb, orig_ino, ino, 6771 (struct ext4_inode *)buf); 6772 } 6773 rcu_read_unlock(); 6774 } 6775 6776 /* 6777 * Post the struct inode info into an on-disk inode location in the 6778 * buffer-cache. This gobbles the caller's reference to the 6779 * buffer_head in the inode location struct. 6780 * 6781 * The caller must have write access to iloc->bh. 6782 */ 6783 static int ext4_do_update_inode(handle_t *handle, 6784 struct inode *inode, 6785 struct ext4_iloc *iloc) 6786 { 6787 struct ext4_inode *raw_inode = ext4_raw_inode(iloc); 6788 struct ext4_inode_info *ei = EXT4_I(inode); 6789 struct buffer_head *bh = iloc->bh; 6790 struct super_block *sb = inode->i_sb; 6791 int err; 6792 int need_datasync = 0, set_large_file = 0; 6793 6794 spin_lock(&ei->i_raw_lock); 6795 6796 /* 6797 * For fields not tracked in the in-memory inode, initialise them 6798 * to zero for new inodes. 6799 */ 6800 if (ext4_test_inode_state(inode, EXT4_STATE_NEW)) 6801 memset(raw_inode, 0, EXT4_SB(inode->i_sb)->s_inode_size); 6802 6803 if (READ_ONCE(ei->i_disksize) != ext4_isize(inode->i_sb, raw_inode)) 6804 need_datasync = 1; 6805 if (ei->i_disksize > 0x7fffffffULL) { 6806 if (!ext4_has_feature_large_file(sb) || 6807 EXT4_SB(sb)->s_es->s_rev_level == cpu_to_le32(EXT4_GOOD_OLD_REV)) 6808 set_large_file = 1; 6809 } 6810 6811 err = ext4_fill_raw_inode(inode, raw_inode); 6812 spin_unlock(&ei->i_raw_lock); 6813 if (err) { 6814 EXT4_ERROR_INODE(inode, "corrupted inode contents"); 6815 goto out_brelse; 6816 } 6817 6818 if (inode->i_sb->s_flags & SB_LAZYTIME) 6819 ext4_update_other_inodes_time(inode->i_sb, inode->i_ino, 6820 bh->b_data); 6821 6822 BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata"); 6823 err = ext4_handle_dirty_metadata(handle, NULL, bh); 6824 if (err) 6825 goto out_error; 6826 ext4_clear_inode_state(inode, EXT4_STATE_NEW); 6827 if (set_large_file) { 6828 BUFFER_TRACE(EXT4_SB(sb)->s_sbh, "get write access"); 6829 err = ext4_journal_get_write_access(handle, sb, 6830 EXT4_SB(sb)->s_sbh, 6831 EXT4_JTR_NONE); 6832 if (err) 6833 goto out_error; 6834 lock_buffer(EXT4_SB(sb)->s_sbh); 6835 ext4_set_feature_large_file(sb); 6836 ext4_superblock_csum_set(sb); 6837 unlock_buffer(EXT4_SB(sb)->s_sbh); 6838 ext4_handle_sync(handle); 6839 err = ext4_handle_dirty_metadata(handle, NULL, 6840 EXT4_SB(sb)->s_sbh); 6841 } 6842 ext4_update_inode_fsync_trans(handle, inode, need_datasync); 6843 out_error: 6844 ext4_std_error(inode->i_sb, err); 6845 out_brelse: 6846 brelse(bh); 6847 return err; 6848 } 6849 6850 /* 6851 * ext4_write_inode() 6852 * 6853 * We are called from a few places: 6854 * 6855 * - Within generic_file_aio_write() -> generic_write_sync() for O_SYNC files. 6856 * Here, there will be no transaction running. We wait for any running 6857 * transaction to commit. 6858 * 6859 * - Within flush work (sys_sync(), kupdate and such). 6860 * We wait on commit, if told to. 6861 * 6862 * - Within iput_final() -> write_inode_now() 6863 * We wait on commit, if told to. 6864 * 6865 * In all cases it is actually safe for us to return without doing anything, 6866 * because the inode has been copied into a raw inode buffer in 6867 * ext4_mark_inode_dirty(). This is a correctness thing for WB_SYNC_ALL 6868 * writeback. 6869 * 6870 * For nojournal mode all the work is done in ext4_sync_inode_metadata() 6871 * because inode content is already copied into raw inode buffer and inode 6872 * is marked with I_METADATA_WRITEBACK. 6873 * 6874 * Note that we are absolutely dependent upon all inode dirtiers doing the 6875 * right thing: they *must* call mark_inode_dirty() after dirtying info in 6876 * which we are interested. 6877 * 6878 * It would be a bug for them to not do this. The code: 6879 * 6880 * mark_inode_dirty(inode) 6881 * stuff(); 6882 * inode->i_size = expr; 6883 * 6884 * is in error because write_inode() could occur while `stuff()' is running, 6885 * and the new i_size will be lost. Plus the inode will no longer be on the 6886 * superblock's dirty inode list. 6887 */ 6888 int ext4_write_inode(struct inode *inode, struct writeback_control *wbc) 6889 { 6890 int err; 6891 6892 if (WARN_ON_ONCE(current->flags & PF_MEMALLOC)) 6893 return 0; 6894 6895 err = ext4_emergency_state(inode->i_sb); 6896 if (unlikely(err)) 6897 return err; 6898 6899 if (!EXT4_SB(inode->i_sb)->s_journal) 6900 return 0; 6901 6902 if (ext4_journal_current_handle()) { 6903 ext4_debug("called recursively, non-PF_MEMALLOC!\n"); 6904 dump_stack(); 6905 return -EIO; 6906 } 6907 6908 /* 6909 * No need to force transaction in WB_SYNC_NONE mode. Also 6910 * ext4_sync_fs() will force the commit after everything is 6911 * written. 6912 */ 6913 if (wbc->sync_mode != WB_SYNC_ALL || wbc->for_sync) 6914 return 0; 6915 6916 return ext4_fc_commit(EXT4_SB(inode->i_sb)->s_journal, 6917 EXT4_I(inode)->i_sync_tid); 6918 } 6919 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_write_inode); 6920 6921 int ext4_sync_inode_metadata(struct inode *inode, struct writeback_control *wbc) 6922 { 6923 struct ext4_iloc iloc; 6924 struct mapping_metadata_bhs *mmb; 6925 int err; 6926 6927 /* We should only get here in nojournal mode */ 6928 if (WARN_ON_ONCE(EXT4_SB(inode->i_sb)->s_journal)) 6929 return -EFSCORRUPTED; 6930 6931 mmb = READ_ONCE(EXT4_I(inode)->i_metadata_bhs); 6932 if (mmb) { 6933 err = mmb_sync(mmb); 6934 if (err) 6935 return err; 6936 } 6937 /* A block that isn't cached is neither dirty nor under writeback. */ 6938 err = ext4_get_inode_loc_noio(inode, &iloc); 6939 if (err == -EAGAIN) 6940 return 0; 6941 if (err) 6942 return err; 6943 sync_dirty_buffer(iloc.bh); 6944 if (buffer_write_io_error(iloc.bh)) { 6945 ext4_error_inode_block(inode, iloc.bh->b_blocknr, EIO, 6946 "IO error syncing inode"); 6947 err = -EIO; 6948 } 6949 brelse(iloc.bh); 6950 return err; 6951 } 6952 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_sync_inode_metadata); 6953 6954 /* 6955 * In data=journal mode ext4_journalled_invalidate_folio() may fail to invalidate 6956 * buffers that are attached to a folio straddling i_size and are undergoing 6957 * commit. In that case we have to wait for commit to finish and try again. 6958 */ 6959 static void ext4_wait_for_tail_page_commit(struct inode *inode) 6960 { 6961 unsigned offset; 6962 journal_t *journal = EXT4_SB(inode->i_sb)->s_journal; 6963 tid_t commit_tid; 6964 int ret; 6965 bool has_transaction; 6966 6967 offset = inode->i_size & (PAGE_SIZE - 1); 6968 /* 6969 * If the folio is fully truncated, we don't need to wait for any commit 6970 * (and we even should not as __ext4_journalled_invalidate_folio() may 6971 * strip all buffers from the folio but keep the folio dirty which can then 6972 * confuse e.g. concurrent ext4_writepages() seeing dirty folio without 6973 * buffers). Also we don't need to wait for any commit if all buffers in 6974 * the folio remain valid. This is most beneficial for the common case of 6975 * blocksize == PAGESIZE. 6976 */ 6977 if (!offset || offset > (PAGE_SIZE - i_blocksize(inode))) 6978 return; 6979 while (1) { 6980 struct folio *folio = filemap_lock_folio(inode->i_mapping, 6981 inode->i_size >> PAGE_SHIFT); 6982 if (IS_ERR(folio)) 6983 return; 6984 ret = __ext4_journalled_invalidate_folio(folio, offset, 6985 folio_size(folio) - offset); 6986 folio_unlock(folio); 6987 folio_put(folio); 6988 if (ret != -EBUSY) 6989 return; 6990 has_transaction = false; 6991 read_lock(&journal->j_state_lock); 6992 if (journal->j_committing_transaction) { 6993 commit_tid = journal->j_committing_transaction->t_tid; 6994 has_transaction = true; 6995 } 6996 read_unlock(&journal->j_state_lock); 6997 if (has_transaction) 6998 jbd2_log_wait_commit(journal, commit_tid); 6999 } 7000 } 7001 7002 /* 7003 * Set i_size and i_disksize to 'newsize'. 7004 * 7005 * Both i_rwsem and i_data_sem are required here to avoid races between 7006 * generic append writeback (or zeroed pending I/O writeback) and 7007 * concurrent operations (e.g., fallocate, truncate) that also modify 7008 * i_size and i_disksize. This also ensures that the writeback ioend worker 7009 * observes the latest i_size under the same lock protection. 7010 */ 7011 static inline void ext4_set_inode_size(struct inode *inode, loff_t newsize) 7012 { 7013 WARN_ON_ONCE(S_ISREG(inode->i_mode) && !inode_is_locked(inode)); 7014 7015 down_write(&EXT4_I(inode)->i_data_sem); 7016 i_size_write(inode, newsize); 7017 __ext4_set_i_disksize(inode, newsize); 7018 up_write(&EXT4_I(inode)->i_data_sem); 7019 } 7020 7021 static int ext4_truncate_up(struct inode *inode, loff_t oldsize, loff_t newsize) 7022 { 7023 ext4_lblk_t old_lblk, new_lblk; 7024 handle_t *handle; 7025 int ret; 7026 7027 if (!IS_ALIGNED(oldsize | newsize, i_blocksize(inode))) { 7028 ret = ext4_inode_attach_jinode(inode); 7029 if (ret) 7030 return ret; 7031 } 7032 7033 inode_set_mtime_to_ts(inode, inode_set_ctime_current(inode)); 7034 if (!IS_ALIGNED(oldsize, i_blocksize(inode))) { 7035 ret = ext4_block_zero_eof(inode, oldsize, LLONG_MAX); 7036 if (ret) 7037 return ret; 7038 } 7039 7040 handle = ext4_journal_start(inode, EXT4_HT_INODE, 3); 7041 if (IS_ERR(handle)) 7042 return PTR_ERR(handle); 7043 7044 old_lblk = oldsize > 0 ? (oldsize - 1) >> inode->i_blkbits : 0; 7045 new_lblk = newsize > 0 ? (newsize - 1) >> inode->i_blkbits : 0; 7046 ext4_fc_track_range(handle, inode, old_lblk, new_lblk); 7047 7048 ext4_set_inode_size(inode, newsize); 7049 7050 ret = ext4_mark_inode_dirty(handle, inode); 7051 ext4_journal_stop(handle); 7052 if (ret) 7053 return ret; 7054 /* 7055 * isize extend must be called outside an active handle due to 7056 * the lock ordering of transaction start and folio lock in the 7057 * iomap buffered I/O path (folio lock -> transaction start). 7058 */ 7059 pagecache_isize_extended(inode, oldsize, newsize); 7060 return 0; 7061 } 7062 7063 static int ext4_truncate_down(struct inode *inode, loff_t oldsize, 7064 loff_t newsize, int *orphan) 7065 { 7066 ext4_lblk_t start_lblk; 7067 handle_t *handle; 7068 int ret; 7069 7070 /* Do not change i_size. */ 7071 if (newsize == oldsize) 7072 goto truncate; 7073 7074 /* Shrink. */ 7075 handle = ext4_journal_start(inode, EXT4_HT_INODE, 3); 7076 if (IS_ERR(handle)) 7077 return PTR_ERR(handle); 7078 7079 if (ext4_handle_valid(handle)) { 7080 ret = ext4_orphan_add(handle, inode); 7081 *orphan = 1; 7082 if (ret) { 7083 ext4_journal_stop(handle); 7084 return ret; 7085 } 7086 } 7087 7088 start_lblk = newsize > 0 ? (newsize - 1) >> inode->i_blkbits : 0; 7089 ext4_fc_track_range(handle, inode, start_lblk, EXT_MAX_BLOCKS - 1); 7090 7091 down_write(&EXT4_I(inode)->i_data_sem); 7092 /* 7093 * Truncate the zeroed EOF block invalidates the pending disksize 7094 * update, so clear the disksize-grow-pending state. 7095 */ 7096 if (ext4_test_inode_state(inode, EXT4_STATE_DISKSIZE_GROW_PENDING) && 7097 (newsize <= EXT4_I(inode)->i_disksize)) 7098 ext4_iomap_clear_disksize_pending(inode); 7099 7100 i_size_write(inode, newsize); 7101 __ext4_set_i_disksize(inode, newsize); 7102 up_write(&EXT4_I(inode)->i_data_sem); 7103 7104 ret = ext4_mark_inode_dirty(handle, inode); 7105 ext4_journal_stop(handle); 7106 if (ret) 7107 return ret; 7108 7109 if (ext4_should_journal_data(inode)) 7110 ext4_wait_for_tail_page_commit(inode); 7111 truncate: 7112 /* 7113 * Truncate pagecache after we've waited for commit in data=journal 7114 * mode to make pages freeable. Call ext4_truncate() even if 7115 * i_size didn't change to truncate possible preallocated blocks. 7116 */ 7117 truncate_pagecache(inode, newsize); 7118 return ext4_truncate(inode); 7119 } 7120 7121 /* 7122 * ext4_setattr() 7123 * 7124 * Called from notify_change. 7125 * 7126 * We want to trap VFS attempts to truncate the file as soon as 7127 * possible. In particular, we want to make sure that when the VFS 7128 * shrinks i_size, we put the inode on the orphan list and modify 7129 * i_disksize immediately, so that during the subsequent flushing of 7130 * dirty pages and freeing of disk blocks, we can guarantee that any 7131 * commit will leave the blocks being flushed in an unused state on 7132 * disk. (On recovery, the inode will get truncated and the blocks will 7133 * be freed, so we have a strong guarantee that no future commit will 7134 * leave these blocks visible to the user.) 7135 * 7136 * Another thing we have to assure is that if we are in ordered mode 7137 * and inode is still attached to the committing transaction, we must 7138 * we start writeout of all the dirty pages which are being truncated. 7139 * This way we are sure that all the data written in the previous 7140 * transaction are already on disk (truncate waits for pages under 7141 * writeback). 7142 * 7143 * Called with inode->i_rwsem down. 7144 */ 7145 int ext4_setattr(const struct mnt_idmap *idmap, struct dentry *dentry, 7146 struct iattr *attr) 7147 { 7148 struct inode *inode = d_inode(dentry); 7149 int error, rc = 0; 7150 int orphan = 0; 7151 const unsigned int ia_valid = attr->ia_valid; 7152 bool inc_ivers = true; 7153 7154 error = ext4_emergency_state(inode->i_sb); 7155 if (unlikely(error)) 7156 return error; 7157 7158 if (unlikely(IS_IMMUTABLE(inode))) 7159 return -EPERM; 7160 7161 if (unlikely(IS_APPEND(inode) && 7162 (ia_valid & (ATTR_MODE | ATTR_UID | 7163 ATTR_GID | ATTR_TIMES_SET)))) 7164 return -EPERM; 7165 7166 error = setattr_prepare(idmap, dentry, attr); 7167 if (error) 7168 return error; 7169 7170 error = fscrypt_prepare_setattr(dentry, attr); 7171 if (error) 7172 return error; 7173 7174 if (is_quota_modification(idmap, inode, attr)) { 7175 error = dquot_initialize(inode); 7176 if (error) 7177 return error; 7178 } 7179 7180 if (i_uid_needs_update(idmap, attr, inode) || 7181 i_gid_needs_update(idmap, attr, inode)) { 7182 handle_t *handle; 7183 7184 /* (user+group)*(old+new) structure, inode write (sb, 7185 * inode block, ? - but truncate inode update has it) */ 7186 handle = ext4_journal_start(inode, EXT4_HT_QUOTA, 7187 (EXT4_MAXQUOTAS_INIT_BLOCKS(inode->i_sb) + 7188 EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb)) + 3); 7189 if (IS_ERR(handle)) { 7190 error = PTR_ERR(handle); 7191 goto err_out; 7192 } 7193 7194 /* dquot_transfer() calls back ext4_get_inode_usage() which 7195 * counts xattr inode references. 7196 */ 7197 down_read(&EXT4_I(inode)->xattr_sem); 7198 error = dquot_transfer(idmap, inode, attr); 7199 up_read(&EXT4_I(inode)->xattr_sem); 7200 7201 if (error) { 7202 ext4_journal_stop(handle); 7203 return error; 7204 } 7205 /* Update corresponding info in inode so that everything is in 7206 * one transaction */ 7207 i_uid_update(idmap, attr, inode); 7208 i_gid_update(idmap, attr, inode); 7209 error = ext4_mark_inode_dirty(handle, inode); 7210 ext4_journal_stop(handle); 7211 if (unlikely(error)) { 7212 return error; 7213 } 7214 } 7215 7216 if (attr->ia_valid & ATTR_SIZE) { 7217 loff_t oldsize = inode->i_size; 7218 int shrink = (attr->ia_size < inode->i_size); 7219 7220 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) { 7221 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb); 7222 7223 if (attr->ia_size > sbi->s_bitmap_maxbytes) { 7224 return -EFBIG; 7225 } 7226 } 7227 if (!S_ISREG(inode->i_mode)) { 7228 return -EINVAL; 7229 } 7230 7231 if (attr->ia_size == inode->i_size) 7232 inc_ivers = false; 7233 7234 /* 7235 * If file has inline data but new size exceeds inline capacity, 7236 * convert to extent-based storage first to prevent inconsistent 7237 * state (inline flag set but size exceeds inline capacity). 7238 */ 7239 if (ext4_has_inline_data(inode) && 7240 attr->ia_size > EXT4_I(inode)->i_inline_size) { 7241 error = ext4_convert_inline_data(inode); 7242 if (error) 7243 return error; 7244 } 7245 7246 if (shrink) { 7247 if (ext4_should_order_data(inode)) { 7248 error = ext4_begin_ordered_truncate(inode, 7249 attr->ia_size); 7250 if (error) 7251 goto err_out; 7252 } 7253 /* 7254 * Blocks are going to be removed from the inode. Wait 7255 * for dio in flight. 7256 */ 7257 inode_dio_wait(inode); 7258 } 7259 7260 filemap_invalidate_lock(inode->i_mapping); 7261 7262 rc = ext4_break_layouts(inode); 7263 if (rc) { 7264 filemap_invalidate_unlock(inode->i_mapping); 7265 goto err_out; 7266 } 7267 7268 if (attr->ia_size > oldsize) 7269 error = ext4_truncate_up(inode, oldsize, attr->ia_size); 7270 else { 7271 /* Shrink or do not change i_size. */ 7272 error = ext4_truncate_down(inode, oldsize, 7273 attr->ia_size, &orphan); 7274 } 7275 7276 filemap_invalidate_unlock(inode->i_mapping); 7277 } 7278 7279 if (!error) { 7280 if (inc_ivers) 7281 inode_inc_iversion(inode); 7282 setattr_copy(idmap, inode, attr); 7283 mark_inode_dirty(inode); 7284 } 7285 7286 /* 7287 * If the call to ext4_truncate failed to get a transaction handle at 7288 * all, we need to clean up the in-core orphan list manually. 7289 */ 7290 if (orphan && inode->i_nlink) 7291 ext4_orphan_del(NULL, inode); 7292 7293 if (!error && (ia_valid & ATTR_MODE)) 7294 rc = posix_acl_chmod(idmap, dentry, inode->i_mode); 7295 7296 err_out: 7297 if (error) 7298 ext4_std_error(inode->i_sb, error); 7299 if (!error) 7300 error = rc; 7301 return error; 7302 } 7303 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_setattr); 7304 7305 u32 ext4_dio_alignment(struct inode *inode) 7306 { 7307 if (fsverity_active(inode)) 7308 return 0; 7309 if (ext4_should_journal_data(inode)) 7310 return 0; 7311 if (ext4_has_inline_data(inode)) 7312 return 0; 7313 if (IS_ENCRYPTED(inode)) 7314 return i_blocksize(inode); 7315 return 1; /* use the iomap defaults */ 7316 } 7317 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_dio_alignment); 7318 7319 int ext4_getattr(const struct mnt_idmap *idmap, const struct path *path, 7320 struct kstat *stat, u32 request_mask, unsigned int query_flags) 7321 { 7322 struct inode *inode = d_inode(path->dentry); 7323 struct ext4_inode *raw_inode; 7324 struct ext4_inode_info *ei = EXT4_I(inode); 7325 unsigned int flags; 7326 7327 if ((request_mask & STATX_BTIME) && 7328 EXT4_FITS_IN_INODE(raw_inode, ei, i_crtime)) { 7329 stat->result_mask |= STATX_BTIME; 7330 stat->btime.tv_sec = ei->i_crtime.tv_sec; 7331 stat->btime.tv_nsec = ei->i_crtime.tv_nsec; 7332 } 7333 7334 /* Return the DIO alignment restrictions if requested. */ 7335 if ((request_mask & STATX_DIOALIGN) && S_ISREG(inode->i_mode)) { 7336 u32 dio_align = ext4_dio_alignment(inode); 7337 7338 stat->result_mask |= STATX_DIOALIGN; 7339 if (dio_align == 1) { 7340 struct block_device *bdev = inode->i_sb->s_bdev; 7341 7342 /* iomap defaults */ 7343 stat->dio_mem_align = bdev_dma_alignment(bdev) + 1; 7344 stat->dio_offset_align = bdev_logical_block_size(bdev); 7345 } else { 7346 stat->dio_mem_align = dio_align; 7347 stat->dio_offset_align = dio_align; 7348 } 7349 } 7350 7351 if ((request_mask & STATX_WRITE_ATOMIC) && S_ISREG(inode->i_mode)) { 7352 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb); 7353 unsigned int awu_min = 0, awu_max = 0; 7354 7355 if (ext4_inode_can_atomic_write(inode)) { 7356 awu_min = sbi->s_awu_min; 7357 awu_max = sbi->s_awu_max; 7358 } 7359 7360 generic_fill_statx_atomic_writes(stat, awu_min, awu_max, 7361 awu_max); 7362 } 7363 7364 flags = ei->i_flags & EXT4_FL_USER_VISIBLE; 7365 if (flags & EXT4_APPEND_FL) 7366 stat->attributes |= STATX_ATTR_APPEND; 7367 if (flags & EXT4_COMPR_FL) 7368 stat->attributes |= STATX_ATTR_COMPRESSED; 7369 if (flags & EXT4_ENCRYPT_FL) 7370 stat->attributes |= STATX_ATTR_ENCRYPTED; 7371 if (flags & EXT4_IMMUTABLE_FL) 7372 stat->attributes |= STATX_ATTR_IMMUTABLE; 7373 if (flags & EXT4_NODUMP_FL) 7374 stat->attributes |= STATX_ATTR_NODUMP; 7375 7376 stat->attributes_mask |= (STATX_ATTR_APPEND | 7377 STATX_ATTR_COMPRESSED | 7378 STATX_ATTR_ENCRYPTED | 7379 STATX_ATTR_IMMUTABLE | 7380 STATX_ATTR_NODUMP); 7381 7382 generic_fillattr(idmap, request_mask, inode, stat); 7383 return 0; 7384 } 7385 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_getattr); 7386 7387 int ext4_file_getattr(const struct mnt_idmap *idmap, 7388 const struct path *path, struct kstat *stat, 7389 u32 request_mask, unsigned int query_flags) 7390 { 7391 struct inode *inode = d_inode(path->dentry); 7392 u64 delalloc_blocks; 7393 7394 ext4_getattr(idmap, path, stat, request_mask, query_flags); 7395 7396 /* 7397 * If there is inline data in the inode, the inode will normally not 7398 * have data blocks allocated (it may have an external xattr block). 7399 * Report at least one sector for such files, so tools like tar, rsync, 7400 * others don't incorrectly think the file is completely sparse. 7401 */ 7402 if (unlikely(ext4_has_inline_data(inode))) 7403 stat->blocks += (stat->size + 511) >> 9; 7404 7405 /* 7406 * We can't update i_blocks if the block allocation is delayed 7407 * otherwise in the case of system crash before the real block 7408 * allocation is done, we will have i_blocks inconsistent with 7409 * on-disk file blocks. 7410 * We always keep i_blocks updated together with real 7411 * allocation. But to not confuse with user, stat 7412 * will return the blocks that include the delayed allocation 7413 * blocks for this file. 7414 */ 7415 delalloc_blocks = EXT4_C2B(EXT4_SB(inode->i_sb), 7416 EXT4_I(inode)->i_reserved_data_blocks); 7417 stat->blocks += delalloc_blocks << (inode->i_sb->s_blocksize_bits - 9); 7418 return 0; 7419 } 7420 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_file_getattr); 7421 7422 static int ext4_index_trans_blocks(struct inode *inode, int lblocks, 7423 int pextents) 7424 { 7425 if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) 7426 return ext4_ind_trans_blocks(inode, lblocks); 7427 return ext4_ext_index_trans_blocks(inode, pextents); 7428 } 7429 7430 /* 7431 * Calculate number of credits needed in a transaction to: 7432 * * Allocate data blocks from @alloc_extents different groups - note that 7433 * with flexbg a single physical extent can span multiple groups but 7434 * single mballoc request only returns extent within one group. 7435 * * Allocate metatadata (extent tree blocks, indirect blocks) to store 7436 * pointers to @pextents data extents having @lblocks in total. 7437 * * Modify extent tree / indirect block tree, inode, superblock, quota 7438 * tracking, xattr blocks 7439 */ 7440 int ext4_meta_trans_blocks(struct inode *inode, int lblocks, int pextents, 7441 int alloc_extents) 7442 { 7443 ext4_group_t groups, ngroups = ext4_get_groups_count(inode->i_sb); 7444 int gdpblocks; 7445 int idxblocks; 7446 int ret; 7447 7448 /* 7449 * How many index and leaf blocks need to touch to map @lblocks 7450 * logical blocks to @pextents physical extents? 7451 */ 7452 idxblocks = ext4_index_trans_blocks(inode, lblocks, pextents); 7453 7454 /* 7455 * Now let's see how many group bitmaps and group descriptors need 7456 * to account 7457 */ 7458 groups = idxblocks + alloc_extents; 7459 gdpblocks = groups; 7460 if (groups > ngroups) 7461 groups = ngroups; 7462 if (groups > EXT4_SB(inode->i_sb)->s_gdb_count) 7463 gdpblocks = EXT4_SB(inode->i_sb)->s_gdb_count; 7464 7465 /* bitmaps and block group descriptor blocks */ 7466 ret = idxblocks + groups + gdpblocks; 7467 7468 /* Blocks for super block, inode, quota and xattr blocks */ 7469 ret += EXT4_META_TRANS_BLOCKS(inode->i_sb); 7470 7471 return ret; 7472 } 7473 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_meta_trans_blocks); 7474 7475 /* 7476 * Calculate the journal credits for modifying the number of blocks 7477 * in a single extent within one transaction. 'nrblocks' is used only 7478 * for non-extent inodes. For extent type inodes, 'nrblocks' can be 7479 * zero if the exact number of blocks is unknown. 7480 */ 7481 int ext4_chunk_trans_extent(struct inode *inode, int nrblocks) 7482 { 7483 int ret; 7484 7485 ret = ext4_meta_trans_blocks(inode, nrblocks, 1, 1); 7486 /* Account for data blocks for journalled mode */ 7487 if (ext4_should_journal_data(inode)) 7488 ret += nrblocks; 7489 return ret; 7490 } 7491 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_chunk_trans_extent); 7492 7493 /* 7494 * Calculate the journal credits for a chunk of data modification. 7495 * 7496 * This is called from DIO, fallocate or whoever calling 7497 * ext4_map_blocks() to map/allocate a chunk of contiguous disk blocks. 7498 * 7499 * journal buffers for data blocks are not included here, as DIO 7500 * and fallocate do no need to journal data buffers. 7501 */ 7502 int ext4_chunk_trans_blocks(struct inode *inode, int nrblocks) 7503 { 7504 return ext4_meta_trans_blocks(inode, nrblocks, 1, 1); 7505 } 7506 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_chunk_trans_blocks); 7507 7508 /* 7509 * The caller must have previously called ext4_reserve_inode_write(). 7510 * Give this, we know that the caller already has write access to iloc->bh. 7511 */ 7512 int ext4_mark_iloc_dirty(handle_t *handle, 7513 struct inode *inode, struct ext4_iloc *iloc) 7514 { 7515 struct super_block *sb = inode->i_sb; 7516 int err = 0; 7517 7518 KUNIT_STATIC_STUB_REDIRECT(ext4_mark_iloc_dirty, handle, inode, iloc); 7519 7520 err = ext4_emergency_state(sb); 7521 if (unlikely(err)) { 7522 put_bh(iloc->bh); 7523 return err; 7524 } 7525 ext4_fc_track_inode(handle, inode); 7526 7527 /* the do_update_inode consumes one bh->b_count */ 7528 get_bh(iloc->bh); 7529 7530 /* ext4_do_update_inode() does jbd2_journal_dirty_metadata */ 7531 err = ext4_do_update_inode(handle, inode, iloc); 7532 put_bh(iloc->bh); 7533 /* 7534 * Mark that there's metadata writeout pending for the inode so that it 7535 * gets properly flushed on fsync(2) and similar. We don't bother for 7536 * fastcommit replay as that flushes the whole bdev afterwards anyway. 7537 * It is faster this way and we avoid entering fs writeback paths which 7538 * aren't fully initialized yet. 7539 */ 7540 if (!ext4_handle_valid(handle) && 7541 !(EXT4_SB(sb)->s_mount_state & EXT4_FC_REPLAY)) { 7542 /* 7543 * Inode didn't need to go through dirtying, make sure it is 7544 * attached to wb so that writeback can handle it. 7545 */ 7546 spin_lock(&inode->i_lock); 7547 inode_attach_wb(inode, NULL); 7548 spin_unlock(&inode->i_lock); 7549 set_inode_metadata_writeback(inode); 7550 } 7551 return err; 7552 } 7553 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_mark_iloc_dirty); 7554 7555 /* 7556 * On success, We end up with an outstanding reference count against 7557 * iloc->bh. This _must_ be cleaned up later. 7558 */ 7559 7560 int 7561 ext4_reserve_inode_write(handle_t *handle, struct inode *inode, 7562 struct ext4_iloc *iloc) 7563 { 7564 int err; 7565 7566 err = ext4_emergency_state(inode->i_sb); 7567 if (unlikely(err)) 7568 return err; 7569 7570 err = ext4_get_inode_loc(inode, iloc); 7571 if (!err) { 7572 BUFFER_TRACE(iloc->bh, "get_write_access"); 7573 err = ext4_journal_get_write_access(handle, inode->i_sb, 7574 iloc->bh, EXT4_JTR_NONE); 7575 if (err) { 7576 brelse(iloc->bh); 7577 iloc->bh = NULL; 7578 } 7579 ext4_fc_track_inode(handle, inode); 7580 } 7581 ext4_std_error(inode->i_sb, err); 7582 return err; 7583 } 7584 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_reserve_inode_write); 7585 7586 static int __ext4_expand_extra_isize(struct inode *inode, 7587 unsigned int new_extra_isize, 7588 struct ext4_iloc *iloc, 7589 handle_t *handle, int *no_expand) 7590 { 7591 struct ext4_inode *raw_inode; 7592 struct ext4_xattr_ibody_header *header; 7593 unsigned int inode_size = EXT4_INODE_SIZE(inode->i_sb); 7594 struct ext4_inode_info *ei = EXT4_I(inode); 7595 int error; 7596 7597 /* this was checked at iget time, but double check for good measure */ 7598 if ((EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize > inode_size) || 7599 (ei->i_extra_isize & 3)) { 7600 EXT4_ERROR_INODE(inode, "bad extra_isize %u (inode size %u)", 7601 ei->i_extra_isize, 7602 EXT4_INODE_SIZE(inode->i_sb)); 7603 return -EFSCORRUPTED; 7604 } 7605 if ((new_extra_isize < ei->i_extra_isize) || 7606 (new_extra_isize < 4) || 7607 (new_extra_isize > inode_size - EXT4_GOOD_OLD_INODE_SIZE)) 7608 return -EINVAL; /* Should never happen */ 7609 7610 raw_inode = ext4_raw_inode(iloc); 7611 7612 header = IHDR(inode, raw_inode); 7613 7614 /* No extended attributes present */ 7615 if (!ext4_test_inode_state(inode, EXT4_STATE_XATTR) || 7616 header->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC)) { 7617 memset((void *)raw_inode + EXT4_GOOD_OLD_INODE_SIZE + 7618 EXT4_I(inode)->i_extra_isize, 0, 7619 new_extra_isize - EXT4_I(inode)->i_extra_isize); 7620 EXT4_I(inode)->i_extra_isize = new_extra_isize; 7621 return 0; 7622 } 7623 7624 /* 7625 * We may need to allocate external xattr block so we need quotas 7626 * initialized. Here we can be called with various locks held so we 7627 * cannot affort to initialize quotas ourselves. So just bail. 7628 */ 7629 if (dquot_initialize_needed(inode)) 7630 return -EAGAIN; 7631 7632 /* try to expand with EAs present */ 7633 error = ext4_expand_extra_isize_ea(inode, new_extra_isize, 7634 raw_inode, handle); 7635 if (error) { 7636 /* 7637 * Inode size expansion failed; don't try again 7638 */ 7639 *no_expand = 1; 7640 } 7641 7642 return error; 7643 } 7644 7645 /* 7646 * Expand an inode by new_extra_isize bytes. 7647 * Returns 0 on success or negative error number on failure. 7648 */ 7649 static int ext4_try_to_expand_extra_isize(struct inode *inode, 7650 unsigned int new_extra_isize, 7651 struct ext4_iloc iloc, 7652 handle_t *handle) 7653 { 7654 int no_expand; 7655 int error; 7656 7657 if (ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND)) 7658 return -EOVERFLOW; 7659 7660 /* 7661 * Skip expansion during mount (!SB_ACTIVE). Expanding extra isize 7662 * may move xattrs to external blocks and release ea_inodes via iput. 7663 * When !SB_ACTIVE, iput triggers write_inode_now() which acquires 7664 * s_writepages_rwsem, causing a deadlock with the caller's active 7665 * jbd2 handle (lock order: s_writepages_rwsem -> jbd2_handle). 7666 * 7667 * Skip it while unmounting as well. shrink_dcache_for_umount() 7668 * clears s_root before generic_shutdown_super() clears SB_ACTIVE, and 7669 * the last iput() of a lazytime inode in that window redirties it and 7670 * lands here. Moving xattrs out to a block then needs a new EA inode, 7671 * which ext4_xattr_inode_create() refuses without s_root. 7672 */ 7673 if (unlikely(!(inode->i_sb->s_flags & SB_ACTIVE) || !inode->i_sb->s_root)) 7674 return -EBUSY; 7675 7676 /* 7677 * In nojournal mode, we can immediately attempt to expand 7678 * the inode. When journaled, we first need to obtain extra 7679 * buffer credits since we may write into the EA block 7680 * with this same handle. If journal_extend fails, then it will 7681 * only result in a minor loss of functionality for that inode. 7682 * If this is felt to be critical, then e2fsck should be run to 7683 * force a large enough s_min_extra_isize. 7684 */ 7685 if (ext4_journal_extend(handle, 7686 EXT4_DATA_TRANS_BLOCKS(inode->i_sb), 0) != 0) 7687 return -ENOSPC; 7688 7689 if (ext4_write_trylock_xattr(inode, &no_expand) == 0) 7690 return -EBUSY; 7691 7692 error = __ext4_expand_extra_isize(inode, new_extra_isize, &iloc, 7693 handle, &no_expand); 7694 ext4_write_unlock_xattr(inode, &no_expand); 7695 7696 return error; 7697 } 7698 7699 int ext4_expand_extra_isize(struct inode *inode, 7700 unsigned int new_extra_isize, 7701 struct ext4_iloc *iloc) 7702 { 7703 handle_t *handle; 7704 int no_expand; 7705 int error, rc; 7706 7707 if (ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND)) { 7708 brelse(iloc->bh); 7709 return -EOVERFLOW; 7710 } 7711 7712 handle = ext4_journal_start(inode, EXT4_HT_INODE, 7713 EXT4_DATA_TRANS_BLOCKS(inode->i_sb)); 7714 if (IS_ERR(handle)) { 7715 error = PTR_ERR(handle); 7716 brelse(iloc->bh); 7717 return error; 7718 } 7719 7720 ext4_write_lock_xattr(inode, &no_expand); 7721 7722 BUFFER_TRACE(iloc->bh, "get_write_access"); 7723 error = ext4_journal_get_write_access(handle, inode->i_sb, iloc->bh, 7724 EXT4_JTR_NONE); 7725 if (error) { 7726 brelse(iloc->bh); 7727 goto out_unlock; 7728 } 7729 7730 error = __ext4_expand_extra_isize(inode, new_extra_isize, iloc, 7731 handle, &no_expand); 7732 7733 rc = ext4_mark_iloc_dirty(handle, inode, iloc); 7734 if (!error) 7735 error = rc; 7736 7737 out_unlock: 7738 ext4_write_unlock_xattr(inode, &no_expand); 7739 ext4_journal_stop(handle); 7740 return error; 7741 } 7742 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_expand_extra_isize); 7743 7744 /* 7745 * What we do here is to mark the in-core inode as clean with respect to inode 7746 * dirtiness (it may still be data-dirty). 7747 * This means that the in-core inode may be reaped by prune_icache 7748 * without having to perform any I/O. This is a very good thing, 7749 * because *any* task may call prune_icache - even ones which 7750 * have a transaction open against a different journal. 7751 * 7752 * Is this cheating? Not really. Sure, we haven't written the 7753 * inode out, but prune_icache isn't a user-visible syncing function. 7754 * Whenever the user wants stuff synced (sys_sync, sys_msync, sys_fsync) 7755 * we start and wait on commits. 7756 */ 7757 int __ext4_mark_inode_dirty(handle_t *handle, struct inode *inode, 7758 const char *func, unsigned int line) 7759 { 7760 struct ext4_iloc iloc; 7761 struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb); 7762 int err; 7763 7764 KUNIT_STATIC_STUB_REDIRECT(__ext4_mark_inode_dirty, handle, inode, 7765 func, line); 7766 7767 might_sleep(); 7768 trace_ext4_mark_inode_dirty(inode, _RET_IP_); 7769 err = ext4_reserve_inode_write(handle, inode, &iloc); 7770 if (err) 7771 goto out; 7772 7773 if (EXT4_I(inode)->i_extra_isize < sbi->s_want_extra_isize) 7774 ext4_try_to_expand_extra_isize(inode, sbi->s_want_extra_isize, 7775 iloc, handle); 7776 7777 err = ext4_mark_iloc_dirty(handle, inode, &iloc); 7778 out: 7779 if (unlikely(err)) 7780 ext4_error_inode_err(inode, func, line, 0, err, 7781 "mark_inode_dirty error"); 7782 return err; 7783 } 7784 7785 /* 7786 * ext4_dirty_inode() is called from __mark_inode_dirty() 7787 * 7788 * We're really interested in the case where a file is being extended. 7789 * i_size has been changed by generic_commit_write() and we thus need 7790 * to include the updated inode in the current transaction. 7791 * 7792 * Also, dquot_alloc_block() will always dirty the inode when blocks 7793 * are allocated to the file. 7794 * 7795 * If the inode is marked synchronous, we don't honour that here - doing 7796 * so would cause a commit on atime updates, which we don't bother doing. 7797 * We handle synchronous inodes at the highest possible level. 7798 */ 7799 void ext4_dirty_inode(struct inode *inode, int flags) 7800 { 7801 handle_t *handle; 7802 7803 handle = ext4_journal_start(inode, EXT4_HT_INODE, 2); 7804 if (IS_ERR(handle)) 7805 return; 7806 ext4_mark_inode_dirty(handle, inode); 7807 ext4_journal_stop(handle); 7808 } 7809 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_dirty_inode); 7810 7811 int ext4_change_inode_journal_flag(struct inode *inode, int val) 7812 { 7813 journal_t *journal; 7814 handle_t *handle; 7815 int err; 7816 int alloc_ctx; 7817 7818 /* 7819 * We have to be very careful here: changing a data block's 7820 * journaling status dynamically is dangerous. If we write a 7821 * data block to the journal, change the status and then delete 7822 * that block, we risk forgetting to revoke the old log record 7823 * from the journal and so a subsequent replay can corrupt data. 7824 * So, first we make sure that the journal is empty and that 7825 * nobody is changing anything. 7826 */ 7827 7828 journal = EXT4_JOURNAL(inode); 7829 if (!journal) 7830 return 0; 7831 if (is_journal_aborted(journal)) 7832 return -EROFS; 7833 7834 /* Wait for all existing dio workers */ 7835 inode_dio_wait(inode); 7836 7837 /* 7838 * Before flushing the journal and switching inode's aops, we have 7839 * to flush all dirty data the inode has. There can be outstanding 7840 * delayed allocations, there can be unwritten extents created by 7841 * fallocate or buffered writes in dioread_nolock mode covered by 7842 * dirty data which can be converted only after flushing the dirty 7843 * data (and journalled aops don't know how to handle these cases). 7844 */ 7845 filemap_invalidate_lock(inode->i_mapping); 7846 err = filemap_write_and_wait(inode->i_mapping); 7847 if (err < 0) { 7848 filemap_invalidate_unlock(inode->i_mapping); 7849 return err; 7850 } 7851 /* Before switch the inode journalling mode evict all the page cache. */ 7852 truncate_pagecache(inode, 0); 7853 7854 alloc_ctx = ext4_writepages_down_write(inode->i_sb); 7855 jbd2_journal_lock_updates(journal); 7856 7857 /* 7858 * OK, there are no updates running now, and all cached data is 7859 * synced to disk. We are now in a completely consistent state 7860 * which doesn't have anything in the journal, and we know that 7861 * no filesystem updates are running, so it is safe to modify 7862 * the inode's in-core data-journaling state flag now. 7863 */ 7864 7865 if (val) { 7866 ext4_set_inode_flag(inode, EXT4_INODE_JOURNAL_DATA); 7867 ext4_disable_buffered_iomap(inode); 7868 } else { 7869 err = jbd2_journal_flush(journal, 0); 7870 if (err < 0) { 7871 jbd2_journal_unlock_updates(journal); 7872 ext4_writepages_up_write(inode->i_sb, alloc_ctx); 7873 filemap_invalidate_unlock(inode->i_mapping); 7874 return err; 7875 } 7876 ext4_clear_inode_flag(inode, EXT4_INODE_JOURNAL_DATA); 7877 ext4_enable_buffered_iomap(inode); 7878 } 7879 ext4_set_aops(inode); 7880 ext4_set_inode_mapping_order(inode); 7881 7882 jbd2_journal_unlock_updates(journal); 7883 ext4_writepages_up_write(inode->i_sb, alloc_ctx); 7884 filemap_invalidate_unlock(inode->i_mapping); 7885 7886 /* Finally we can mark the inode as dirty. */ 7887 7888 handle = ext4_journal_start(inode, EXT4_HT_INODE, 1); 7889 if (IS_ERR(handle)) 7890 return PTR_ERR(handle); 7891 7892 ext4_fc_mark_ineligible(inode->i_sb, 7893 EXT4_FC_REASON_JOURNAL_FLAG_CHANGE, handle); 7894 err = ext4_mark_inode_dirty(handle, inode); 7895 ext4_handle_sync(handle); 7896 ext4_journal_stop(handle); 7897 ext4_std_error(inode->i_sb, err); 7898 7899 return err; 7900 } 7901 7902 static int ext4_bh_unmapped(handle_t *handle, struct inode *inode, 7903 struct buffer_head *bh) 7904 { 7905 return !buffer_mapped(bh); 7906 } 7907 7908 static int ext4_block_page_mkwrite(struct inode *inode, struct folio *folio, 7909 get_block_t get_block) 7910 { 7911 handle_t *handle; 7912 loff_t size; 7913 unsigned long len; 7914 int credits; 7915 int ret; 7916 7917 credits = ext4_chunk_trans_extent(inode, 7918 ext4_journal_blocks_per_folio(inode)); 7919 handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE, credits); 7920 if (IS_ERR(handle)) 7921 return PTR_ERR(handle); 7922 7923 folio_lock(folio); 7924 size = i_size_read(inode); 7925 /* Page got truncated from under us? */ 7926 if (folio->mapping != inode->i_mapping || folio_pos(folio) > size) { 7927 ret = -EFAULT; 7928 goto out_error; 7929 } 7930 7931 len = folio_size(folio); 7932 if (folio_pos(folio) + len > size) 7933 len = size - folio_pos(folio); 7934 7935 ret = ext4_block_write_begin(handle, folio, 0, len, get_block); 7936 if (ret) 7937 goto out_error; 7938 7939 if (!ext4_should_journal_data(inode)) { 7940 block_commit_write(folio, 0, len); 7941 folio_mark_dirty(folio); 7942 } else { 7943 ret = ext4_journal_folio_buffers(handle, folio, len); 7944 if (ret) 7945 goto out_error; 7946 } 7947 ext4_journal_stop(handle); 7948 folio_wait_stable(folio); 7949 return ret; 7950 7951 out_error: 7952 folio_unlock(folio); 7953 ext4_journal_stop(handle); 7954 return ret; 7955 } 7956 7957 static vm_fault_t ext4_iomap_page_mkwrite(struct vm_fault *vmf) 7958 { 7959 struct inode *inode = file_inode(vmf->vma->vm_file); 7960 iomap_iter_next_fn next; 7961 7962 /* 7963 * ext4_nonda_switch() could writeback this folio, so have to 7964 * call it before lock folio. 7965 */ 7966 if (test_opt(inode->i_sb, DELALLOC) && !ext4_nonda_switch(inode->i_sb)) 7967 next = ext4_iomap_buffered_da_write_next; 7968 else 7969 next = ext4_iomap_buffered_write_next; 7970 7971 return iomap_page_mkwrite(vmf, next, NULL); 7972 } 7973 7974 vm_fault_t ext4_page_mkwrite(struct vm_fault *vmf) 7975 { 7976 struct vm_area_struct *vma = vmf->vma; 7977 struct folio *folio = page_folio(vmf->page); 7978 loff_t size; 7979 unsigned long len; 7980 int err; 7981 vm_fault_t ret; 7982 struct file *file = vma->vm_file; 7983 struct inode *inode = file_inode(file); 7984 struct address_space *mapping = inode->i_mapping; 7985 get_block_t *get_block = ext4_get_block; 7986 int retries = 0; 7987 7988 if (unlikely(IS_IMMUTABLE(inode))) 7989 return VM_FAULT_SIGBUS; 7990 7991 sb_start_pagefault(inode->i_sb); 7992 file_update_time(vma->vm_file); 7993 7994 filemap_invalidate_lock_shared(mapping); 7995 7996 err = ext4_convert_inline_data(inode); 7997 if (err) 7998 goto out_ret; 7999 8000 if (ext4_inode_buffered_iomap(inode)) { 8001 ret = ext4_iomap_page_mkwrite(vmf); 8002 goto out; 8003 } 8004 8005 /* 8006 * On data journalling we skip straight to the transaction handle: 8007 * there's no delalloc; page truncated will be checked later; the 8008 * early return w/ all buffers mapped (calculates size/len) can't 8009 * be used; and there's no dioread_nolock, so only ext4_get_block. 8010 */ 8011 if (ext4_should_journal_data(inode)) 8012 goto retry_alloc; 8013 8014 /* Delalloc case is easy... */ 8015 if (test_opt(inode->i_sb, DELALLOC) && 8016 !ext4_nonda_switch(inode->i_sb)) { 8017 do { 8018 err = block_page_mkwrite(vma, vmf, 8019 ext4_da_get_block_prep); 8020 } while (err == -ENOSPC && 8021 ext4_should_retry_alloc(inode->i_sb, &retries)); 8022 goto out_ret; 8023 } 8024 8025 folio_lock(folio); 8026 size = i_size_read(inode); 8027 /* Page got truncated from under us? */ 8028 if (folio->mapping != mapping || folio_pos(folio) > size) { 8029 folio_unlock(folio); 8030 ret = VM_FAULT_NOPAGE; 8031 goto out; 8032 } 8033 8034 len = folio_size(folio); 8035 if (folio_pos(folio) + len > size) 8036 len = size - folio_pos(folio); 8037 /* 8038 * Return if we have all the buffers mapped. This avoids the need to do 8039 * journal_start/journal_stop which can block and take a long time 8040 * 8041 * This cannot be done for data journalling, as we have to add the 8042 * inode to the transaction's list to writeprotect pages on commit. 8043 */ 8044 if (folio_buffers(folio)) { 8045 if (!ext4_walk_page_buffers(NULL, inode, folio_buffers(folio), 8046 0, len, NULL, 8047 ext4_bh_unmapped)) { 8048 /* Wait so that we don't change page under IO */ 8049 folio_wait_stable(folio); 8050 ret = VM_FAULT_LOCKED; 8051 goto out; 8052 } 8053 } 8054 folio_unlock(folio); 8055 /* OK, we need to fill the hole... */ 8056 if (ext4_should_dioread_nolock(inode)) 8057 get_block = ext4_get_block_unwritten; 8058 retry_alloc: 8059 /* Start journal and allocate blocks */ 8060 err = ext4_block_page_mkwrite(inode, folio, get_block); 8061 if (err == -EAGAIN || 8062 (err == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))) 8063 goto retry_alloc; 8064 out_ret: 8065 ret = vmf_fs_error(err); 8066 out: 8067 filemap_invalidate_unlock_shared(mapping); 8068 sb_end_pagefault(inode->i_sb); 8069 return ret; 8070 } 8071 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_page_mkwrite); 8072 8073 #if IS_ENABLED(CONFIG_EXT4_KUNIT_TESTS) 8074 int ext4_inode_csum_verify_test(struct inode *inode, struct ext4_inode *raw, 8075 struct ext4_inode_info *ei) 8076 { 8077 return ext4_inode_csum_verify(inode, raw, ei); 8078 } 8079 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_inode_csum_verify_test); 8080 8081 int ext4_inode_blocks_set_test(struct ext4_inode *raw_inode, 8082 struct ext4_inode_info *ei) 8083 { 8084 return ext4_inode_blocks_set(raw_inode, ei); 8085 } 8086 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_inode_blocks_set_test); 8087 8088 blkcnt_t ext4_inode_blocks_test(struct ext4_inode *raw_inode, 8089 struct ext4_inode_info *ei) 8090 { 8091 return ext4_inode_blocks(raw_inode, ei); 8092 } 8093 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_inode_blocks_test); 8094 8095 int ext4_fill_raw_inode_test(struct inode *inode, struct ext4_inode *raw_inode) 8096 { 8097 return ext4_fill_raw_inode(inode, raw_inode); 8098 } 8099 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_fill_raw_inode_test); 8100 8101 int ext4_expand_extra_isize_test(struct inode *inode, 8102 unsigned int new_extra_isize, 8103 struct ext4_iloc *iloc, 8104 handle_t *handle, int *no_expand) 8105 { 8106 return __ext4_expand_extra_isize(inode, new_extra_isize, iloc, 8107 handle, no_expand); 8108 } 8109 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_expand_extra_isize_test); 8110 8111 int ext4_try_to_expand_extra_isize_test(struct inode *inode, 8112 unsigned int new_extra_isize, 8113 struct ext4_iloc *iloc, 8114 handle_t *handle) 8115 { 8116 return ext4_try_to_expand_extra_isize(inode, new_extra_isize, 8117 *iloc, handle); 8118 } 8119 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_try_to_expand_extra_isize_test); 8120 8121 int ext4_da_reserve_space_test(struct inode *inode, int nr_resv) 8122 { 8123 return ext4_da_reserve_space(inode, nr_resv); 8124 } 8125 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_da_reserve_space_test); 8126 8127 int ext4_clu_alloc_state_test(struct inode *inode, ext4_lblk_t lblk) 8128 { 8129 return ext4_clu_alloc_state(inode, lblk); 8130 } 8131 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_clu_alloc_state_test); 8132 8133 int ext4_insert_delayed_blocks_test(struct inode *inode, ext4_lblk_t lblk, 8134 ext4_lblk_t len) 8135 { 8136 return ext4_insert_delayed_blocks(inode, lblk, len); 8137 } 8138 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_insert_delayed_blocks_test); 8139 8140 int ext4_da_map_blocks_test(struct inode *inode, struct ext4_map_blocks *map) 8141 { 8142 return ext4_da_map_blocks(inode, map); 8143 } 8144 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_da_map_blocks_test); 8145 8146 int ext4_nonda_switch_test(struct super_block *sb) 8147 { 8148 return ext4_nonda_switch(sb); 8149 } 8150 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_nonda_switch_test); 8151 8152 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_get_inode_loc_noio); 8153 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_get_fc_inode_loc); 8154 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_da_get_block_prep); 8155 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_da_update_reserve_space); 8156 EXPORT_SYMBOL_FOR_EXT4_TEST(ext4_da_release_space); 8157 EXPORT_SYMBOL_FOR_EXT4_TEST(__ext4_mark_inode_dirty); 8158 #endif 8159