1 // SPDX-License-Identifier: GPL-2.0 2 3 #include <linux/fsverity.h> 4 #include <linux/iomap.h> 5 #include "ctree.h" 6 #include "delalloc-space.h" 7 #include "direct-io.h" 8 #include "extent-tree.h" 9 #include "file.h" 10 #include "fs.h" 11 #include "transaction.h" 12 #include "volumes.h" 13 #include "bio.h" 14 #include "ordered-data.h" 15 16 struct btrfs_dio_data { 17 loff_t old_isize; 18 struct extent_changeset *data_reserved; 19 struct btrfs_ordered_extent *ordered; 20 bool data_space_reserved; 21 bool nocow_done; 22 bool updated_isize; 23 }; 24 25 struct btrfs_dio_private { 26 /* Range of I/O */ 27 u64 file_offset; 28 u32 bytes; 29 30 /* This must be last */ 31 struct btrfs_bio bbio; 32 }; 33 34 static struct bio_set btrfs_dio_bioset; 35 36 static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend, 37 struct extent_state **cached_state, 38 unsigned int iomap_flags) 39 { 40 const bool writing = (iomap_flags & IOMAP_WRITE); 41 const bool nowait = (iomap_flags & IOMAP_NOWAIT); 42 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree; 43 struct btrfs_ordered_extent *ordered; 44 int ret = 0; 45 46 /* Direct lock must be taken before the extent lock. */ 47 if (nowait) { 48 if (!btrfs_try_lock_dio_extent(io_tree, lockstart, lockend, cached_state)) 49 return -EAGAIN; 50 } else { 51 btrfs_lock_dio_extent(io_tree, lockstart, lockend, cached_state); 52 } 53 54 while (1) { 55 if (nowait) { 56 if (!btrfs_try_lock_extent(io_tree, lockstart, lockend, 57 cached_state)) { 58 ret = -EAGAIN; 59 break; 60 } 61 } else { 62 btrfs_lock_extent(io_tree, lockstart, lockend, cached_state); 63 } 64 /* 65 * We're concerned with the entire range that we're going to be 66 * doing DIO to, so we need to make sure there's no ordered 67 * extents in this range. 68 */ 69 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), lockstart, 70 lockend - lockstart + 1); 71 72 /* 73 * We need to make sure there are no buffered pages in this 74 * range either, we could have raced between the invalidate in 75 * generic_file_direct_write and locking the extent. The 76 * invalidate needs to happen so that reads after a write do not 77 * get stale data. 78 */ 79 if (!ordered && 80 (!writing || !filemap_range_has_page(inode->i_mapping, 81 lockstart, lockend))) 82 break; 83 84 btrfs_unlock_extent(io_tree, lockstart, lockend, cached_state); 85 86 if (ordered) { 87 if (nowait) { 88 btrfs_put_ordered_extent(ordered); 89 ret = -EAGAIN; 90 break; 91 } 92 /* 93 * If we are doing a DIO read and the ordered extent we 94 * found is for a buffered write, we can not wait for it 95 * to complete and retry, because if we do so we can 96 * deadlock with concurrent buffered writes on page 97 * locks. This happens only if our DIO read covers more 98 * than one extent map, if at this point has already 99 * created an ordered extent for a previous extent map 100 * and locked its range in the inode's io tree, and a 101 * concurrent write against that previous extent map's 102 * range and this range started (we unlock the ranges 103 * in the io tree only when the bios complete and 104 * buffered writes always lock pages before attempting 105 * to lock range in the io tree). 106 */ 107 if (writing || 108 test_bit(BTRFS_ORDERED_DIRECT, &ordered->flags)) 109 btrfs_start_ordered_extent(ordered); 110 else 111 ret = -ENOTBLK; 112 btrfs_put_ordered_extent(ordered); 113 } else { 114 /* 115 * We could trigger writeback for this range (and wait 116 * for it to complete) and then invalidate the pages for 117 * this range (through invalidate_inode_pages2_range()), 118 * but that can lead us to a deadlock with a concurrent 119 * call to readahead (a buffered read or a defrag call 120 * triggered a readahead) on a page lock due to an 121 * ordered dio extent we created before but did not have 122 * yet a corresponding bio submitted (whence it can not 123 * complete), which makes readahead wait for that 124 * ordered extent to complete while holding a lock on 125 * that page. 126 */ 127 ret = nowait ? -EAGAIN : -ENOTBLK; 128 } 129 130 if (ret) 131 break; 132 133 cond_resched(); 134 } 135 136 if (ret) 137 btrfs_unlock_dio_extent(io_tree, lockstart, lockend, cached_state); 138 return ret; 139 } 140 141 static struct extent_map *btrfs_create_dio_extent(struct btrfs_inode *inode, 142 struct btrfs_dio_data *dio_data, 143 const u64 start, 144 const struct btrfs_file_extent *file_extent, 145 const int type) 146 { 147 struct extent_map *em = NULL; 148 struct btrfs_ordered_extent *ordered; 149 150 if (type != BTRFS_ORDERED_NOCOW) { 151 em = btrfs_create_io_em(inode, start, file_extent, type); 152 if (IS_ERR(em)) 153 return em; 154 } 155 156 ordered = btrfs_alloc_ordered_extent(inode, start, file_extent, 157 (1U << type) | 158 (1U << BTRFS_ORDERED_DIRECT)); 159 if (IS_ERR(ordered)) { 160 if (em) { 161 btrfs_free_extent_map(em); 162 btrfs_drop_extent_map_range(inode, start, 163 start + file_extent->num_bytes - 1, false); 164 } 165 em = ERR_CAST(ordered); 166 } else { 167 ASSERT(!dio_data->ordered); 168 dio_data->ordered = ordered; 169 } 170 171 return em; 172 } 173 174 static struct extent_map *btrfs_new_extent_direct(struct btrfs_inode *inode, 175 struct btrfs_dio_data *dio_data, 176 u64 start, u64 len) 177 { 178 struct btrfs_root *root = inode->root; 179 struct btrfs_fs_info *fs_info = root->fs_info; 180 struct btrfs_file_extent file_extent; 181 struct extent_map *em; 182 struct btrfs_key ins; 183 u64 alloc_hint; 184 int ret; 185 186 alloc_hint = btrfs_get_extent_allocation_hint(inode, start, len); 187 again: 188 ret = btrfs_reserve_extent(root, len, len, fs_info->sectorsize, 189 0, alloc_hint, &ins, true, true); 190 if (ret == -EAGAIN) { 191 ASSERT(btrfs_is_zoned(fs_info)); 192 wait_on_bit_io(&inode->root->fs_info->flags, BTRFS_FS_NEED_ZONE_FINISH, 193 TASK_UNINTERRUPTIBLE); 194 goto again; 195 } 196 if (ret) 197 return ERR_PTR(ret); 198 199 file_extent.disk_bytenr = ins.objectid; 200 file_extent.disk_num_bytes = ins.offset; 201 file_extent.num_bytes = ins.offset; 202 file_extent.ram_bytes = ins.offset; 203 file_extent.offset = 0; 204 file_extent.compression = BTRFS_COMPRESS_NONE; 205 em = btrfs_create_dio_extent(inode, dio_data, start, &file_extent, 206 BTRFS_ORDERED_REGULAR); 207 btrfs_dec_block_group_reservations(fs_info, ins.objectid); 208 if (IS_ERR(em)) 209 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, true); 210 211 return em; 212 } 213 214 static int btrfs_get_blocks_direct_write(struct extent_map **map, 215 struct inode *inode, 216 struct btrfs_dio_data *dio_data, 217 u64 start, u64 *lenp, 218 unsigned int iomap_flags) 219 { 220 const bool nowait = (iomap_flags & IOMAP_NOWAIT); 221 struct btrfs_fs_info *fs_info = inode_to_fs_info(inode); 222 struct btrfs_file_extent file_extent; 223 struct extent_map *em = *map; 224 int type; 225 u64 block_start; 226 struct btrfs_block_group *bg; 227 bool can_nocow = false; 228 bool space_reserved = false; 229 u64 len = *lenp; 230 u64 prev_len; 231 loff_t old_isize; 232 int ret = 0; 233 234 /* 235 * We don't allocate a new extent in the following cases 236 * 237 * 1) The inode is marked as NODATACOW. In this case we'll just use the 238 * existing extent. 239 * 2) The extent is marked as PREALLOC. We're good to go here and can 240 * just use the extent. 241 * 242 */ 243 if ((em->flags & EXTENT_FLAG_PREALLOC) || 244 ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) && 245 em->disk_bytenr != EXTENT_MAP_HOLE)) { 246 if (em->flags & EXTENT_FLAG_PREALLOC) 247 type = BTRFS_ORDERED_PREALLOC; 248 else 249 type = BTRFS_ORDERED_NOCOW; 250 len = min(len, em->len - (start - em->start)); 251 block_start = btrfs_extent_map_block_start(em) + (start - em->start); 252 253 if (can_nocow_extent(BTRFS_I(inode), start, &len, &file_extent, 254 false) == 1) { 255 bg = btrfs_inc_nocow_writers(fs_info, block_start); 256 if (bg) 257 can_nocow = true; 258 } 259 } 260 261 prev_len = len; 262 if (can_nocow) { 263 struct extent_map *em2; 264 265 /* We can NOCOW, so only need to reserve metadata space. */ 266 ret = btrfs_delalloc_reserve_metadata(BTRFS_I(inode), len, len, 267 nowait); 268 if (ret < 0) { 269 /* Our caller expects us to free the input extent map. */ 270 btrfs_free_extent_map(em); 271 *map = NULL; 272 btrfs_dec_nocow_writers(bg); 273 if (nowait && (ret == -ENOSPC || ret == -EDQUOT)) 274 ret = -EAGAIN; 275 goto out; 276 } 277 space_reserved = true; 278 279 em2 = btrfs_create_dio_extent(BTRFS_I(inode), dio_data, start, 280 &file_extent, type); 281 btrfs_dec_nocow_writers(bg); 282 if (IS_ERR(em2)) { 283 ret = PTR_ERR(em2); 284 btrfs_free_extent_map(em); 285 *map = NULL; 286 goto out; 287 } 288 289 /* 290 * True NOCOW writes don't need to create a new extent map, 291 * while PREALLOC writes must replace the existing one. 292 */ 293 if (em2) { 294 ASSERT(type == BTRFS_ORDERED_PREALLOC); 295 btrfs_free_extent_map(em); 296 *map = em2; 297 em = em2; 298 } 299 300 dio_data->nocow_done = true; 301 } else { 302 /* Our caller expects us to free the input extent map. */ 303 btrfs_free_extent_map(em); 304 *map = NULL; 305 306 if (nowait) { 307 ret = -EAGAIN; 308 goto out; 309 } 310 311 /* 312 * If we could not allocate data space before locking the file 313 * range and we can't do a NOCOW write, then we have to fail. 314 */ 315 if (!dio_data->data_space_reserved) { 316 ret = -ENOSPC; 317 goto out; 318 } 319 320 /* 321 * We have to COW and we have already reserved data space before, 322 * so now we reserve only metadata. 323 */ 324 ret = btrfs_delalloc_reserve_metadata(BTRFS_I(inode), len, len, 325 false); 326 if (ret < 0) 327 goto out; 328 space_reserved = true; 329 330 em = btrfs_new_extent_direct(BTRFS_I(inode), dio_data, start, len); 331 if (IS_ERR(em)) { 332 ret = PTR_ERR(em); 333 goto out; 334 } 335 *map = em; 336 len = min(len, em->len - (start - em->start)); 337 if (len < prev_len) 338 btrfs_delalloc_release_metadata(BTRFS_I(inode), 339 prev_len - len, true); 340 } 341 342 /* 343 * We have created our ordered extent, so we can now release our reservation 344 * for an outstanding extent. 345 */ 346 btrfs_delalloc_release_extents(BTRFS_I(inode), prev_len); 347 348 /* 349 * Need to update the i_size under the extent lock so buffered 350 * readers will get the updated i_size when we unlock. 351 */ 352 old_isize = i_size_read(inode); 353 if (start + len > old_isize) { 354 if (!dio_data->updated_isize) { 355 dio_data->old_isize = old_isize; 356 dio_data->updated_isize = true; 357 } 358 i_size_write(inode, start + len); 359 } 360 out: 361 if (ret && space_reserved) { 362 btrfs_delalloc_release_extents(BTRFS_I(inode), len); 363 btrfs_delalloc_release_metadata(BTRFS_I(inode), len, true); 364 } 365 *lenp = len; 366 return ret; 367 } 368 369 static int btrfs_dio_iomap_begin(struct inode *inode, loff_t start, 370 loff_t length, unsigned int flags, struct iomap *iomap, 371 struct iomap *srcmap) 372 { 373 struct iomap_iter *iter = container_of(iomap, struct iomap_iter, iomap); 374 struct btrfs_fs_info *fs_info = inode_to_fs_info(inode); 375 struct extent_map *em; 376 struct extent_state *cached_state = NULL; 377 struct btrfs_dio_data *dio_data = iter->private; 378 u64 lockstart, lockend; 379 const bool write = !!(flags & IOMAP_WRITE); 380 int ret = 0; 381 u64 len = length; 382 const u64 data_alloc_len = length; 383 u32 unlock_bits = EXTENT_LOCKED; 384 385 /* 386 * We could potentially fault if we have a buffer > PAGE_SIZE, and if 387 * we're NOWAIT we may submit a bio for a partial range and return 388 * EIOCBQUEUED, which would result in an errant short read. 389 * 390 * The best way to handle this would be to allow for partial completions 391 * of iocb's, so we could submit the partial bio, return and fault in 392 * the rest of the pages, and then submit the io for the rest of the 393 * range. However we don't have that currently, so simply return 394 * -EAGAIN at this point so that the normal path is used. 395 */ 396 if (!write && (flags & IOMAP_NOWAIT) && length > PAGE_SIZE) 397 return -EAGAIN; 398 399 /* 400 * Cap the size of reads to that usually seen in buffered I/O as we need 401 * to allocate a contiguous array for the checksums. 402 */ 403 if (!write) 404 len = min_t(u64, len, fs_info->sectorsize * BIO_MAX_VECS); 405 406 lockstart = start; 407 lockend = start + len - 1; 408 409 /* 410 * iomap_dio_rw() only does filemap_write_and_wait_range(), which isn't 411 * enough if we've written compressed pages to this area, so we need to 412 * flush the dirty pages again to make absolutely sure that any 413 * outstanding dirty pages are on disk - the first flush only starts 414 * compression on the data, while keeping the pages locked, so by the 415 * time the second flush returns we know bios for the compressed pages 416 * were submitted and finished, and the pages no longer under writeback. 417 * 418 * If we have a NOWAIT request and we have any pages in the range that 419 * are locked, likely due to compression still in progress, we don't want 420 * to block on page locks. We also don't want to block on pages marked as 421 * dirty or under writeback (same as for the non-compression case). 422 * iomap_dio_rw() did the same check, but after that and before we got 423 * here, mmap'ed writes may have happened or buffered reads started 424 * (readpage() and readahead(), which lock pages), as we haven't locked 425 * the file range yet. 426 */ 427 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT, 428 &BTRFS_I(inode)->runtime_flags)) { 429 if (flags & IOMAP_NOWAIT) { 430 if (filemap_range_needs_writeback(inode->i_mapping, 431 lockstart, lockend)) 432 return -EAGAIN; 433 } else { 434 ret = filemap_fdatawrite_range(inode->i_mapping, start, 435 start + length - 1); 436 if (ret) 437 return ret; 438 } 439 } 440 441 memset(dio_data, 0, sizeof(*dio_data)); 442 443 /* 444 * We always try to allocate data space and must do it before locking 445 * the file range, to avoid deadlocks with concurrent writes to the same 446 * range if the range has several extents and the writes don't expand the 447 * current i_size (the inode lock is taken in shared mode). If we fail to 448 * allocate data space here we continue and later, after locking the 449 * file range, we fail with ENOSPC only if we figure out we can not do a 450 * NOCOW write. 451 */ 452 if (write && !(flags & IOMAP_NOWAIT)) { 453 ret = btrfs_check_data_free_space(BTRFS_I(inode), 454 &dio_data->data_reserved, 455 start, data_alloc_len, false); 456 if (!ret) 457 dio_data->data_space_reserved = true; 458 else if (!(BTRFS_I(inode)->flags & 459 (BTRFS_INODE_NODATACOW | BTRFS_INODE_PREALLOC))) 460 goto err; 461 } 462 463 /* 464 * If this errors out it's because we couldn't invalidate pagecache for 465 * this range and we need to fallback to buffered IO, or we are doing a 466 * NOWAIT read/write and we need to block. 467 */ 468 ret = lock_extent_direct(inode, lockstart, lockend, &cached_state, flags); 469 if (ret < 0) 470 goto err; 471 472 em = btrfs_get_extent(BTRFS_I(inode), NULL, start, len); 473 if (IS_ERR(em)) { 474 ret = PTR_ERR(em); 475 goto unlock_err; 476 } 477 478 /* 479 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered 480 * io. INLINE is special, and we could probably kludge it in here, but 481 * it's still buffered so for safety lets just fall back to the generic 482 * buffered path. 483 * 484 * For COMPRESSED we _have_ to read the entire extent in so we can 485 * decompress it, so there will be buffering required no matter what we 486 * do, so go ahead and fallback to buffered. 487 * 488 * We return -ENOTBLK because that's what makes DIO go ahead and go back 489 * to buffered IO. Don't blame me, this is the price we pay for using 490 * the generic code. 491 */ 492 if (btrfs_extent_map_is_compressed(em) || em->disk_bytenr == EXTENT_MAP_INLINE) { 493 btrfs_free_extent_map(em); 494 /* 495 * If we are in a NOWAIT context, return -EAGAIN in order to 496 * fallback to buffered IO. This is not only because we can 497 * block with buffered IO (no support for NOWAIT semantics at 498 * the moment) but also to avoid returning short reads to user 499 * space - this happens if we were able to read some data from 500 * previous non-compressed extents and then when we fallback to 501 * buffered IO, at btrfs_file_read_iter() by calling 502 * filemap_read(), we fail to fault in pages for the read buffer, 503 * in which case filemap_read() returns a short read (the number 504 * of bytes previously read is > 0, so it does not return -EFAULT). 505 */ 506 ret = (flags & IOMAP_NOWAIT) ? -EAGAIN : -ENOTBLK; 507 goto unlock_err; 508 } 509 510 len = min(len, em->len - (start - em->start)); 511 512 /* 513 * If we have a NOWAIT request and the range contains multiple extents 514 * (or a mix of extents and holes), then we return -EAGAIN to make the 515 * caller fallback to a context where it can do a blocking (without 516 * NOWAIT) request. This way we avoid doing partial IO and returning 517 * success to the caller, which is not optimal for writes and for reads 518 * it can result in unexpected behaviour for an application. 519 * 520 * When doing a read, because we use IOMAP_DIO_PARTIAL when calling 521 * iomap_dio_rw(), we can end up returning less data then what the caller 522 * asked for, resulting in an unexpected, and incorrect, short read. 523 * That is, the caller asked to read N bytes and we return less than that, 524 * which is wrong unless we are crossing EOF. This happens if we get a 525 * page fault error when trying to fault in pages for the buffer that is 526 * associated to the struct iov_iter passed to iomap_dio_rw(), and we 527 * have previously submitted bios for other extents in the range, in 528 * which case iomap_dio_rw() may return us EIOCBQUEUED if not all of 529 * those bios have completed by the time we get the page fault error, 530 * which we return back to our caller - we should only return EIOCBQUEUED 531 * after we have submitted bios for all the extents in the range. 532 */ 533 if ((flags & IOMAP_NOWAIT) && len < length) { 534 btrfs_free_extent_map(em); 535 ret = -EAGAIN; 536 goto unlock_err; 537 } 538 539 if (write) { 540 ret = btrfs_get_blocks_direct_write(&em, inode, dio_data, 541 start, &len, flags); 542 if (ret < 0) 543 goto unlock_err; 544 /* Recalc len in case the new em is smaller than requested */ 545 len = min(len, em->len - (start - em->start)); 546 if (dio_data->data_space_reserved) { 547 u64 release_offset; 548 u64 release_len = 0; 549 550 if (dio_data->nocow_done) { 551 release_offset = start; 552 release_len = data_alloc_len; 553 } else if (len < data_alloc_len) { 554 release_offset = start + len; 555 release_len = data_alloc_len - len; 556 } 557 558 if (release_len > 0) 559 btrfs_free_reserved_data_space(BTRFS_I(inode), 560 dio_data->data_reserved, 561 release_offset, 562 release_len); 563 } 564 } 565 566 /* 567 * Translate extent map information to iomap. 568 * We trim the extents (and move the addr) even though iomap code does 569 * that, since we have locked only the parts we are performing I/O in. 570 */ 571 if ((em->disk_bytenr == EXTENT_MAP_HOLE) || 572 ((em->flags & EXTENT_FLAG_PREALLOC) && !write)) { 573 iomap->addr = IOMAP_NULL_ADDR; 574 iomap->type = IOMAP_HOLE; 575 } else { 576 iomap->addr = btrfs_extent_map_block_start(em) + (start - em->start); 577 iomap->type = IOMAP_MAPPED; 578 } 579 iomap->offset = start; 580 iomap->bdev = fs_info->fs_devices->latest_dev->bdev; 581 iomap->length = len; 582 btrfs_free_extent_map(em); 583 584 /* 585 * Reads will hold the EXTENT_DIO_LOCKED bit until the io is completed, 586 * writes only hold it for this part. We hold the extent lock until 587 * we're completely done with the extent map to make sure it remains 588 * valid. 589 */ 590 if (write) 591 unlock_bits |= EXTENT_DIO_LOCKED; 592 593 btrfs_clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend, 594 unlock_bits, &cached_state); 595 596 /* We didn't use everything, unlock the dio extent for the remainder. */ 597 if (!write && (start + len) < lockend) 598 btrfs_unlock_dio_extent(&BTRFS_I(inode)->io_tree, start + len, 599 lockend, NULL); 600 601 return 0; 602 603 unlock_err: 604 /* 605 * Don't use EXTENT_LOCK_BITS here in case we extend it later and forget 606 * to update this, be explicit that we expect EXTENT_LOCKED and 607 * EXTENT_DIO_LOCKED to be set here, and so that's what we're clearing. 608 */ 609 btrfs_clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend, 610 EXTENT_LOCKED | EXTENT_DIO_LOCKED, &cached_state); 611 err: 612 if (dio_data->data_space_reserved) { 613 btrfs_free_reserved_data_space(BTRFS_I(inode), 614 dio_data->data_reserved, 615 start, data_alloc_len); 616 extent_changeset_free(dio_data->data_reserved); 617 } 618 619 return ret; 620 } 621 622 static int btrfs_dio_iomap_end(struct inode *inode, loff_t pos, loff_t length, 623 ssize_t written, unsigned int flags, struct iomap *iomap) 624 { 625 struct iomap_iter *iter = container_of(iomap, struct iomap_iter, iomap); 626 struct btrfs_dio_data *dio_data = iter->private; 627 const bool write = !!(flags & IOMAP_WRITE); 628 int ret = 0; 629 630 if (!write) { 631 /* 632 * Hole read, nothing is submitted, thus we have to unlock 633 * the whole range. 634 */ 635 if (iomap->type == IOMAP_HOLE) { 636 btrfs_unlock_dio_extent(&BTRFS_I(inode)->io_tree, pos, 637 pos + length - 1, NULL); 638 return 0; 639 } 640 /* 641 * Short read, needs to unlock the remaining range, and 642 * return -ENOTBLK so we can later fault in the pages and retry. 643 */ 644 if (written < length) { 645 btrfs_unlock_dio_extent(&BTRFS_I(inode)->io_tree, pos + written, 646 pos + length - 1, NULL); 647 return -ENOTBLK; 648 } 649 /* The full range is submitted, endio will do the unlock. */ 650 return 0; 651 } 652 653 if (written < length) { 654 /* 655 * Got a short write and have updated the i_size, need to revert 656 * the i_size change. 657 * 658 * Normally we need to update i_size with extent lock held, but 659 * we're safe due to the following factors: 660 * 661 * - Only a single writer can be enlarging i_size 662 * Enlarging i_size will take the exclusive inode lock. 663 * 664 * - Buffered readers need to wait for the OE we're holding 665 * Buffered readers will lock extent and wait for OE 666 * of the folio range, and since page cache is invalidated 667 * the OE wait cannot be skipped. 668 * 669 * So here we are safe to revert the isize before finishing the 670 * OE, and no reader of the remaining range can see the enlarged 671 * size. 672 * 673 * TODO: Extend the DIO_LOCKED lifespan for direct writes, 674 * and only enlarge isize after a successful write. 675 */ 676 if (dio_data->updated_isize) { 677 u64 new_isize; 678 679 if (written == 0) 680 new_isize = dio_data->old_isize; 681 else 682 new_isize = max(dio_data->old_isize, pos + written); 683 i_size_write(inode, new_isize); 684 dio_data->updated_isize = false; 685 } 686 /* 687 * We have a short write, if there is any range that is submitted 688 * properly, that part will have its own OE split from the 689 * original one. 690 * 691 * So for the OE at dio_data->ordered, it's the part that is not 692 * submitted, and should be marked as fully truncated. 693 */ 694 btrfs_mark_ordered_extent_truncated(dio_data->ordered, 0); 695 btrfs_finish_ordered_extent(dio_data->ordered, 696 pos + written, length - written, true); 697 ret = -ENOTBLK; 698 } 699 btrfs_put_ordered_extent(dio_data->ordered); 700 dio_data->ordered = NULL; 701 extent_changeset_free(dio_data->data_reserved); 702 return ret; 703 } 704 705 static void btrfs_dio_end_io(struct btrfs_bio *bbio) 706 { 707 struct btrfs_dio_private *dip = 708 container_of(bbio, struct btrfs_dio_private, bbio); 709 struct btrfs_inode *inode = bbio->inode; 710 struct bio *bio = &bbio->bio; 711 712 if (bio->bi_status) { 713 btrfs_warn(inode->root->fs_info, 714 "direct IO failed ino %llu op 0x%0x offset %#llx len %u err no %d", 715 btrfs_ino(inode), bio->bi_opf, 716 dip->file_offset, dip->bytes, bio->bi_status); 717 } 718 719 if (btrfs_op(bio) == BTRFS_MAP_WRITE) { 720 btrfs_finish_ordered_extent(bbio->ordered, dip->file_offset, 721 dip->bytes, !bio->bi_status); 722 } else { 723 btrfs_unlock_dio_extent(&inode->io_tree, dip->file_offset, 724 dip->file_offset + dip->bytes - 1, NULL); 725 } 726 727 bbio->bio.bi_private = bbio->private; 728 iomap_dio_bio_end_io(bio); 729 } 730 731 static int btrfs_extract_ordered_extent(struct btrfs_bio *bbio, 732 struct btrfs_ordered_extent *ordered) 733 { 734 u64 start = (u64)bbio->bio.bi_iter.bi_sector << SECTOR_SHIFT; 735 u64 len = bbio->bio.bi_iter.bi_size; 736 struct btrfs_ordered_extent *new; 737 int ret; 738 739 /* Must always be called for the beginning of an ordered extent. */ 740 if (WARN_ON_ONCE(start != ordered->disk_bytenr)) 741 return -EINVAL; 742 743 /* No need to split if the ordered extent covers the entire bio. */ 744 if (ordered->disk_num_bytes == len) { 745 refcount_inc(&ordered->refs); 746 bbio->ordered = ordered; 747 return 0; 748 } 749 750 /* 751 * Don't split the extent_map for NOCOW extents, as we're writing into 752 * a pre-existing one. 753 */ 754 if (!test_bit(BTRFS_ORDERED_NOCOW, &ordered->flags)) { 755 ret = btrfs_split_extent_map(bbio->inode, bbio->file_offset, 756 ordered->num_bytes, len, 757 ordered->disk_bytenr); 758 if (ret) 759 return ret; 760 } 761 762 new = btrfs_split_ordered_extent(ordered, len); 763 if (IS_ERR(new)) 764 return PTR_ERR(new); 765 bbio->ordered = new; 766 return 0; 767 } 768 769 static void btrfs_dio_submit_io(const struct iomap_iter *iter, struct bio *bio, 770 loff_t file_offset) 771 { 772 struct btrfs_bio *bbio = btrfs_bio(bio); 773 struct btrfs_dio_private *dip = 774 container_of(bbio, struct btrfs_dio_private, bbio); 775 struct btrfs_dio_data *dio_data = iter->private; 776 777 btrfs_bio_init(bbio, BTRFS_I(iter->inode), file_offset, 778 btrfs_dio_end_io, bio->bi_private); 779 780 dip->file_offset = file_offset; 781 dip->bytes = bio->bi_iter.bi_size; 782 783 /* 784 * Check if we are doing a partial write. If we are, we need to split 785 * the ordered extent to match the submitted bio. Hang on to the 786 * remaining unfinishable ordered_extent in dio_data so that it can be 787 * cancelled in iomap_end to avoid a deadlock wherein faulting the 788 * remaining pages is blocked on the outstanding ordered extent. 789 */ 790 if (iter->flags & IOMAP_WRITE) { 791 int ret; 792 793 ret = btrfs_extract_ordered_extent(bbio, dio_data->ordered); 794 if (ret) { 795 btrfs_finish_ordered_extent(dio_data->ordered, 796 file_offset, dip->bytes, 797 !ret); 798 bio->bi_status = errno_to_blk_status(ret); 799 iomap_dio_bio_end_io(bio); 800 return; 801 } 802 } 803 804 btrfs_submit_bbio(bbio, 0); 805 } 806 807 static DEFINE_IOMAP_ITER_NEXT_END(btrfs_dio_iomap_next, btrfs_dio_iomap_begin, 808 btrfs_dio_iomap_end); 809 810 static const struct iomap_ops btrfs_dio_iomap_ops = { 811 .iomap_next = btrfs_dio_iomap_next, 812 }; 813 814 static const struct iomap_dio_ops btrfs_dio_ops = { 815 .submit_io = btrfs_dio_submit_io, 816 .bio_set = &btrfs_dio_bioset, 817 }; 818 819 static ssize_t btrfs_dio_read(struct kiocb *iocb, struct iov_iter *iter, 820 size_t done_before) 821 { 822 struct btrfs_dio_data data = { 0 }; 823 824 return iomap_dio_rw(iocb, iter, &btrfs_dio_iomap_ops, &btrfs_dio_ops, 825 IOMAP_DIO_PARTIAL | IOMAP_DIO_FSBLOCK_ALIGNED, &data, done_before); 826 } 827 828 static bool need_stable_write(struct btrfs_inode *inode) 829 { 830 const u64 data_profile = btrfs_data_alloc_profile(inode->root->fs_info) & 831 BTRFS_BLOCK_GROUP_PROFILE_MASK; 832 833 /* Data checksum requires stable buffer. */ 834 if (!(inode->flags & BTRFS_INODE_NODATASUM)) 835 return true; 836 /* 837 * Any profile with mirror/parity will require stable buffer. 838 * Otherwise the mirror may differ from each other. 839 * 840 * Thus only SINGLE and RAID0 doesn't require stable buffer. 841 */ 842 if (data_profile != 0 && data_profile != BTRFS_BLOCK_GROUP_RAID0) 843 return true; 844 return false; 845 } 846 847 static struct iomap_dio *btrfs_dio_write(struct kiocb *iocb, struct iov_iter *iter, 848 size_t done_before) 849 { 850 struct btrfs_dio_data data = { 0 }; 851 unsigned int dio_flags = IOMAP_DIO_PARTIAL | IOMAP_DIO_FSBLOCK_ALIGNED; 852 853 if (need_stable_write(BTRFS_I(file_inode(iocb->ki_filp)))) { 854 /* For now no support for BOUNCE and NOWAIT direct write. */ 855 if (iocb->ki_flags & IOCB_NOWAIT) 856 return ERR_PTR(-EAGAIN); 857 858 dio_flags |= IOMAP_DIO_BOUNCE; 859 } 860 861 return __iomap_dio_rw(iocb, iter, &btrfs_dio_iomap_ops, &btrfs_dio_ops, 862 dio_flags, &data, done_before); 863 } 864 865 static ssize_t check_direct_IO(struct btrfs_fs_info *fs_info, 866 const struct iov_iter *iter, loff_t offset) 867 { 868 const u32 blocksize_mask = fs_info->sectorsize - 1; 869 870 if (offset & blocksize_mask) 871 return -EINVAL; 872 873 if (iov_iter_alignment(iter) & blocksize_mask) 874 return -EINVAL; 875 return 0; 876 } 877 878 ssize_t btrfs_direct_write(struct kiocb *iocb, struct iov_iter *from) 879 { 880 struct file *file = iocb->ki_filp; 881 struct inode *inode = file_inode(file); 882 struct btrfs_fs_info *fs_info = inode_to_fs_info(inode); 883 loff_t pos; 884 ssize_t written = 0; 885 ssize_t written_buffered; 886 size_t prev_left = 0; 887 loff_t endbyte; 888 ssize_t ret; 889 unsigned int ilock_flags = 0; 890 struct iomap_dio *dio; 891 892 if (iocb->ki_flags & IOCB_NOWAIT) 893 ilock_flags |= BTRFS_ILOCK_TRY; 894 895 /* 896 * If the write DIO is within EOF, use a shared lock and also only if 897 * security bits will likely not be dropped by file_remove_privs() called 898 * from btrfs_write_check(). Either will need to be rechecked after the 899 * lock was acquired. 900 */ 901 if (iocb->ki_pos + iov_iter_count(from) <= i_size_read(inode) && IS_NOSEC(inode)) 902 ilock_flags |= BTRFS_ILOCK_SHARED; 903 904 relock: 905 ret = btrfs_inode_lock(BTRFS_I(inode), ilock_flags); 906 if (ret < 0) 907 return ret; 908 909 /* Shared lock cannot be used with security bits set. */ 910 if ((ilock_flags & BTRFS_ILOCK_SHARED) && !IS_NOSEC(inode)) { 911 btrfs_inode_unlock(BTRFS_I(inode), ilock_flags); 912 ilock_flags &= ~BTRFS_ILOCK_SHARED; 913 goto relock; 914 } 915 916 if ((ilock_flags & BTRFS_ILOCK_SHARED) && 917 test_bit(BTRFS_INODE_REFLINK_SRC, &BTRFS_I(inode)->runtime_flags)) { 918 btrfs_inode_unlock(BTRFS_I(inode), ilock_flags); 919 ilock_flags &= ~BTRFS_ILOCK_SHARED; 920 goto relock; 921 } 922 923 ret = generic_write_checks(iocb, from); 924 if (ret <= 0) { 925 btrfs_inode_unlock(BTRFS_I(inode), ilock_flags); 926 return ret; 927 } 928 929 ret = btrfs_write_check(iocb, ret); 930 if (ret < 0) { 931 btrfs_inode_unlock(BTRFS_I(inode), ilock_flags); 932 goto out; 933 } 934 935 pos = iocb->ki_pos; 936 /* 937 * Re-check since file size may have changed just before taking the 938 * lock or pos may have changed because of O_APPEND in generic_write_check() 939 */ 940 if ((ilock_flags & BTRFS_ILOCK_SHARED) && 941 pos + iov_iter_count(from) > i_size_read(inode)) { 942 btrfs_inode_unlock(BTRFS_I(inode), ilock_flags); 943 ilock_flags &= ~BTRFS_ILOCK_SHARED; 944 goto relock; 945 } 946 947 if (check_direct_IO(fs_info, from, pos)) { 948 btrfs_inode_unlock(BTRFS_I(inode), ilock_flags); 949 goto buffered; 950 } 951 952 /* 953 * The iov_iter can be mapped to the same file range we are writing to. 954 * If that's the case, then we will deadlock in the iomap code, because 955 * it first calls our callback btrfs_dio_iomap_begin(), which will create 956 * an ordered extent, and after that it will fault in the pages that the 957 * iov_iter refers to. During the fault in we end up in the readahead 958 * pages code (starting at btrfs_readahead()), which will lock the range, 959 * find that ordered extent and then wait for it to complete (at 960 * btrfs_lock_and_flush_ordered_range()), resulting in a deadlock since 961 * obviously the ordered extent can never complete as we didn't submit 962 * yet the respective bio(s). This always happens when the buffer is 963 * memory mapped to the same file range, since the iomap DIO code always 964 * invalidates pages in the target file range (after starting and waiting 965 * for any writeback). 966 * 967 * So here we disable page faults in the iov_iter and then retry if we 968 * got -EFAULT, faulting in the pages before the retry. 969 */ 970 again: 971 from->nofault = true; 972 dio = btrfs_dio_write(iocb, from, written); 973 from->nofault = false; 974 975 if (IS_ERR_OR_NULL(dio)) { 976 ret = PTR_ERR_OR_ZERO(dio); 977 } else { 978 /* 979 * If we have a synchronous write, we must make sure the fsync 980 * triggered by the iomap_dio_complete() call below doesn't 981 * deadlock on the inode lock - we are already holding it and we 982 * can't call it after unlocking because we may need to complete 983 * partial writes due to the input buffer (or parts of it) not 984 * being already faulted in. 985 */ 986 ASSERT(current->journal_info == NULL); 987 current->journal_info = BTRFS_TRANS_DIO_WRITE_STUB; 988 ret = iomap_dio_complete(dio); 989 current->journal_info = NULL; 990 } 991 992 /* No increment (+=) because iomap returns a cumulative value. */ 993 if (ret > 0) 994 written = ret; 995 996 if (iov_iter_count(from) > 0 && (ret == -EFAULT || ret >= 0)) { 997 const size_t left = iov_iter_count(from); 998 /* 999 * We have more data left to write. Try to fault in as many as 1000 * possible of the remainder pages and retry. We do this without 1001 * releasing and locking again the inode, to prevent races with 1002 * truncate. 1003 * 1004 * Also, in case the iov refers to pages in the file range of the 1005 * file we want to write to (due to a mmap), we could enter an 1006 * infinite loop if we retry after faulting the pages in, since 1007 * iomap will invalidate any pages in the range early on, before 1008 * it tries to fault in the pages of the iov. So we keep track of 1009 * how much was left of iov in the previous EFAULT and fallback 1010 * to buffered IO in case we haven't made any progress. 1011 */ 1012 if (left == prev_left) { 1013 ret = -ENOTBLK; 1014 } else { 1015 fault_in_iov_iter_readable(from, left); 1016 prev_left = left; 1017 goto again; 1018 } 1019 } 1020 1021 btrfs_inode_unlock(BTRFS_I(inode), ilock_flags); 1022 1023 /* 1024 * If 'ret' is -ENOTBLK or we have not written all data, then it means 1025 * we must fallback to buffered IO. 1026 */ 1027 if ((ret < 0 && ret != -ENOTBLK) || !iov_iter_count(from)) 1028 goto out; 1029 1030 buffered: 1031 /* 1032 * If we are in a NOWAIT context, then return -EAGAIN to signal the caller 1033 * it must retry the operation in a context where blocking is acceptable, 1034 * because even if we end up not blocking during the buffered IO attempt 1035 * below, we will block when flushing and waiting for the IO. 1036 */ 1037 if (iocb->ki_flags & IOCB_NOWAIT) { 1038 ret = -EAGAIN; 1039 goto out; 1040 } 1041 1042 pos = iocb->ki_pos; 1043 written_buffered = btrfs_buffered_write(iocb, from); 1044 if (written_buffered < 0) { 1045 ret = written_buffered; 1046 goto out; 1047 } 1048 /* 1049 * Ensure all data is persisted. We want the next direct IO read to be 1050 * able to read what was just written. 1051 */ 1052 endbyte = pos + written_buffered - 1; 1053 ret = btrfs_fdatawrite_range(BTRFS_I(inode), pos, endbyte); 1054 if (ret) 1055 goto out; 1056 ret = filemap_fdatawait_range(inode->i_mapping, pos, endbyte); 1057 if (ret) 1058 goto out; 1059 written += written_buffered; 1060 iocb->ki_pos = pos + written_buffered; 1061 invalidate_mapping_pages(file->f_mapping, pos >> PAGE_SHIFT, 1062 endbyte >> PAGE_SHIFT); 1063 out: 1064 return ret < 0 ? ret : written; 1065 } 1066 1067 static int check_direct_read(struct btrfs_fs_info *fs_info, 1068 const struct iov_iter *iter, loff_t offset) 1069 { 1070 int ret; 1071 int i, seg; 1072 1073 ret = check_direct_IO(fs_info, iter, offset); 1074 if (ret < 0) 1075 return ret; 1076 1077 if (!iter_is_iovec(iter)) 1078 return 0; 1079 1080 for (seg = 0; seg < iter->nr_segs; seg++) { 1081 for (i = seg + 1; i < iter->nr_segs; i++) { 1082 const struct iovec *iov1 = iter_iov(iter) + seg; 1083 const struct iovec *iov2 = iter_iov(iter) + i; 1084 1085 if (iov1->iov_base == iov2->iov_base) 1086 return -EINVAL; 1087 } 1088 } 1089 return 0; 1090 } 1091 1092 ssize_t btrfs_direct_read(struct kiocb *iocb, struct iov_iter *to) 1093 { 1094 struct inode *inode = file_inode(iocb->ki_filp); 1095 size_t prev_left = 0; 1096 ssize_t read = 0; 1097 ssize_t ret; 1098 1099 if (fsverity_active(inode)) 1100 return 0; 1101 1102 if (check_direct_read(inode_to_fs_info(inode), to, iocb->ki_pos)) 1103 return 0; 1104 1105 btrfs_inode_lock(BTRFS_I(inode), BTRFS_ILOCK_SHARED); 1106 again: 1107 /* 1108 * This is similar to what we do for direct IO writes, see the comment 1109 * at btrfs_direct_write(), but we also disable page faults in addition 1110 * to disabling them only at the iov_iter level. This is because when 1111 * reading from a hole or prealloc extent, iomap calls iov_iter_zero(), 1112 * which can still trigger page fault ins despite having set ->nofault 1113 * to true of our 'to' iov_iter. 1114 * 1115 * The difference to direct IO writes is that we deadlock when trying 1116 * to lock the extent range in the inode's tree during he page reads 1117 * triggered by the fault in (while for writes it is due to waiting for 1118 * our own ordered extent). This is because for direct IO reads, 1119 * btrfs_dio_iomap_begin() returns with the extent range locked, which 1120 * is only unlocked in the endio callback (end_bio_extent_readpage()). 1121 */ 1122 pagefault_disable(); 1123 to->nofault = true; 1124 ret = btrfs_dio_read(iocb, to, read); 1125 to->nofault = false; 1126 pagefault_enable(); 1127 1128 /* No increment (+=) because iomap returns a cumulative value. */ 1129 if (ret > 0) 1130 read = ret; 1131 1132 if (iov_iter_count(to) > 0 && (ret == -EFAULT || ret > 0)) { 1133 const size_t left = iov_iter_count(to); 1134 1135 if (left == prev_left) { 1136 /* 1137 * We didn't make any progress since the last attempt, 1138 * fallback to a buffered read for the remainder of the 1139 * range. This is just to avoid any possibility of looping 1140 * for too long. 1141 */ 1142 ret = read; 1143 } else { 1144 /* 1145 * We made some progress since the last retry or this is 1146 * the first time we are retrying. Fault in as many pages 1147 * as possible and retry. 1148 */ 1149 fault_in_iov_iter_writeable(to, left); 1150 prev_left = left; 1151 goto again; 1152 } 1153 } 1154 btrfs_inode_unlock(BTRFS_I(inode), BTRFS_ILOCK_SHARED); 1155 return ret < 0 ? ret : read; 1156 } 1157 1158 int __init btrfs_init_dio(void) 1159 { 1160 if (bioset_init(&btrfs_dio_bioset, BIO_POOL_SIZE, 1161 offsetof(struct btrfs_dio_private, bbio.bio), 1162 BIOSET_NEED_BVECS)) 1163 return -ENOMEM; 1164 1165 return 0; 1166 } 1167 1168 void __cold btrfs_destroy_dio(void) 1169 { 1170 bioset_exit(&btrfs_dio_bioset); 1171 } 1172