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