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