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