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