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