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