1 // SPDX-License-Identifier: GPL-2.0 2 /* 3 * Copyright (C) 2007 Oracle. All rights reserved. 4 */ 5 6 #include <linux/sched.h> 7 #include <linux/sched/mm.h> 8 #include <linux/slab.h> 9 #include <linux/ratelimit.h> 10 #include <linux/kthread.h> 11 #include <linux/semaphore.h> 12 #include <linux/uuid.h> 13 #include <linux/list_sort.h> 14 #include <linux/namei.h> 15 #include "misc.h" 16 #include "ctree.h" 17 #include "extent_map.h" 18 #include "disk-io.h" 19 #include "transaction.h" 20 #include "print-tree.h" 21 #include "volumes.h" 22 #include "raid56.h" 23 #include "rcu-string.h" 24 #include "dev-replace.h" 25 #include "sysfs.h" 26 #include "tree-checker.h" 27 #include "space-info.h" 28 #include "block-group.h" 29 #include "discard.h" 30 #include "zoned.h" 31 #include "fs.h" 32 #include "accessors.h" 33 #include "uuid-tree.h" 34 #include "ioctl.h" 35 #include "relocation.h" 36 #include "scrub.h" 37 #include "super.h" 38 39 #define BTRFS_BLOCK_GROUP_STRIPE_MASK (BTRFS_BLOCK_GROUP_RAID0 | \ 40 BTRFS_BLOCK_GROUP_RAID10 | \ 41 BTRFS_BLOCK_GROUP_RAID56_MASK) 42 43 const struct btrfs_raid_attr btrfs_raid_array[BTRFS_NR_RAID_TYPES] = { 44 [BTRFS_RAID_RAID10] = { 45 .sub_stripes = 2, 46 .dev_stripes = 1, 47 .devs_max = 0, /* 0 == as many as possible */ 48 .devs_min = 2, 49 .tolerated_failures = 1, 50 .devs_increment = 2, 51 .ncopies = 2, 52 .nparity = 0, 53 .raid_name = "raid10", 54 .bg_flag = BTRFS_BLOCK_GROUP_RAID10, 55 .mindev_error = BTRFS_ERROR_DEV_RAID10_MIN_NOT_MET, 56 }, 57 [BTRFS_RAID_RAID1] = { 58 .sub_stripes = 1, 59 .dev_stripes = 1, 60 .devs_max = 2, 61 .devs_min = 2, 62 .tolerated_failures = 1, 63 .devs_increment = 2, 64 .ncopies = 2, 65 .nparity = 0, 66 .raid_name = "raid1", 67 .bg_flag = BTRFS_BLOCK_GROUP_RAID1, 68 .mindev_error = BTRFS_ERROR_DEV_RAID1_MIN_NOT_MET, 69 }, 70 [BTRFS_RAID_RAID1C3] = { 71 .sub_stripes = 1, 72 .dev_stripes = 1, 73 .devs_max = 3, 74 .devs_min = 3, 75 .tolerated_failures = 2, 76 .devs_increment = 3, 77 .ncopies = 3, 78 .nparity = 0, 79 .raid_name = "raid1c3", 80 .bg_flag = BTRFS_BLOCK_GROUP_RAID1C3, 81 .mindev_error = BTRFS_ERROR_DEV_RAID1C3_MIN_NOT_MET, 82 }, 83 [BTRFS_RAID_RAID1C4] = { 84 .sub_stripes = 1, 85 .dev_stripes = 1, 86 .devs_max = 4, 87 .devs_min = 4, 88 .tolerated_failures = 3, 89 .devs_increment = 4, 90 .ncopies = 4, 91 .nparity = 0, 92 .raid_name = "raid1c4", 93 .bg_flag = BTRFS_BLOCK_GROUP_RAID1C4, 94 .mindev_error = BTRFS_ERROR_DEV_RAID1C4_MIN_NOT_MET, 95 }, 96 [BTRFS_RAID_DUP] = { 97 .sub_stripes = 1, 98 .dev_stripes = 2, 99 .devs_max = 1, 100 .devs_min = 1, 101 .tolerated_failures = 0, 102 .devs_increment = 1, 103 .ncopies = 2, 104 .nparity = 0, 105 .raid_name = "dup", 106 .bg_flag = BTRFS_BLOCK_GROUP_DUP, 107 .mindev_error = 0, 108 }, 109 [BTRFS_RAID_RAID0] = { 110 .sub_stripes = 1, 111 .dev_stripes = 1, 112 .devs_max = 0, 113 .devs_min = 1, 114 .tolerated_failures = 0, 115 .devs_increment = 1, 116 .ncopies = 1, 117 .nparity = 0, 118 .raid_name = "raid0", 119 .bg_flag = BTRFS_BLOCK_GROUP_RAID0, 120 .mindev_error = 0, 121 }, 122 [BTRFS_RAID_SINGLE] = { 123 .sub_stripes = 1, 124 .dev_stripes = 1, 125 .devs_max = 1, 126 .devs_min = 1, 127 .tolerated_failures = 0, 128 .devs_increment = 1, 129 .ncopies = 1, 130 .nparity = 0, 131 .raid_name = "single", 132 .bg_flag = 0, 133 .mindev_error = 0, 134 }, 135 [BTRFS_RAID_RAID5] = { 136 .sub_stripes = 1, 137 .dev_stripes = 1, 138 .devs_max = 0, 139 .devs_min = 2, 140 .tolerated_failures = 1, 141 .devs_increment = 1, 142 .ncopies = 1, 143 .nparity = 1, 144 .raid_name = "raid5", 145 .bg_flag = BTRFS_BLOCK_GROUP_RAID5, 146 .mindev_error = BTRFS_ERROR_DEV_RAID5_MIN_NOT_MET, 147 }, 148 [BTRFS_RAID_RAID6] = { 149 .sub_stripes = 1, 150 .dev_stripes = 1, 151 .devs_max = 0, 152 .devs_min = 3, 153 .tolerated_failures = 2, 154 .devs_increment = 1, 155 .ncopies = 1, 156 .nparity = 2, 157 .raid_name = "raid6", 158 .bg_flag = BTRFS_BLOCK_GROUP_RAID6, 159 .mindev_error = BTRFS_ERROR_DEV_RAID6_MIN_NOT_MET, 160 }, 161 }; 162 163 /* 164 * Convert block group flags (BTRFS_BLOCK_GROUP_*) to btrfs_raid_types, which 165 * can be used as index to access btrfs_raid_array[]. 166 */ 167 enum btrfs_raid_types __attribute_const__ btrfs_bg_flags_to_raid_index(u64 flags) 168 { 169 const u64 profile = (flags & BTRFS_BLOCK_GROUP_PROFILE_MASK); 170 171 if (!profile) 172 return BTRFS_RAID_SINGLE; 173 174 return BTRFS_BG_FLAG_TO_INDEX(profile); 175 } 176 177 const char *btrfs_bg_type_to_raid_name(u64 flags) 178 { 179 const int index = btrfs_bg_flags_to_raid_index(flags); 180 181 if (index >= BTRFS_NR_RAID_TYPES) 182 return NULL; 183 184 return btrfs_raid_array[index].raid_name; 185 } 186 187 int btrfs_nr_parity_stripes(u64 type) 188 { 189 enum btrfs_raid_types index = btrfs_bg_flags_to_raid_index(type); 190 191 return btrfs_raid_array[index].nparity; 192 } 193 194 /* 195 * Fill @buf with textual description of @bg_flags, no more than @size_buf 196 * bytes including terminating null byte. 197 */ 198 void btrfs_describe_block_groups(u64 bg_flags, char *buf, u32 size_buf) 199 { 200 int i; 201 int ret; 202 char *bp = buf; 203 u64 flags = bg_flags; 204 u32 size_bp = size_buf; 205 206 if (!flags) { 207 strcpy(bp, "NONE"); 208 return; 209 } 210 211 #define DESCRIBE_FLAG(flag, desc) \ 212 do { \ 213 if (flags & (flag)) { \ 214 ret = snprintf(bp, size_bp, "%s|", (desc)); \ 215 if (ret < 0 || ret >= size_bp) \ 216 goto out_overflow; \ 217 size_bp -= ret; \ 218 bp += ret; \ 219 flags &= ~(flag); \ 220 } \ 221 } while (0) 222 223 DESCRIBE_FLAG(BTRFS_BLOCK_GROUP_DATA, "data"); 224 DESCRIBE_FLAG(BTRFS_BLOCK_GROUP_SYSTEM, "system"); 225 DESCRIBE_FLAG(BTRFS_BLOCK_GROUP_METADATA, "metadata"); 226 227 DESCRIBE_FLAG(BTRFS_AVAIL_ALLOC_BIT_SINGLE, "single"); 228 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) 229 DESCRIBE_FLAG(btrfs_raid_array[i].bg_flag, 230 btrfs_raid_array[i].raid_name); 231 #undef DESCRIBE_FLAG 232 233 if (flags) { 234 ret = snprintf(bp, size_bp, "0x%llx|", flags); 235 size_bp -= ret; 236 } 237 238 if (size_bp < size_buf) 239 buf[size_buf - size_bp - 1] = '\0'; /* remove last | */ 240 241 /* 242 * The text is trimmed, it's up to the caller to provide sufficiently 243 * large buffer 244 */ 245 out_overflow:; 246 } 247 248 static int init_first_rw_device(struct btrfs_trans_handle *trans); 249 static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info); 250 static void btrfs_dev_stat_print_on_load(struct btrfs_device *device); 251 252 /* 253 * Device locking 254 * ============== 255 * 256 * There are several mutexes that protect manipulation of devices and low-level 257 * structures like chunks but not block groups, extents or files 258 * 259 * uuid_mutex (global lock) 260 * ------------------------ 261 * protects the fs_uuids list that tracks all per-fs fs_devices, resulting from 262 * the SCAN_DEV ioctl registration or from mount either implicitly (the first 263 * device) or requested by the device= mount option 264 * 265 * the mutex can be very coarse and can cover long-running operations 266 * 267 * protects: updates to fs_devices counters like missing devices, rw devices, 268 * seeding, structure cloning, opening/closing devices at mount/umount time 269 * 270 * global::fs_devs - add, remove, updates to the global list 271 * 272 * does not protect: manipulation of the fs_devices::devices list in general 273 * but in mount context it could be used to exclude list modifications by eg. 274 * scan ioctl 275 * 276 * btrfs_device::name - renames (write side), read is RCU 277 * 278 * fs_devices::device_list_mutex (per-fs, with RCU) 279 * ------------------------------------------------ 280 * protects updates to fs_devices::devices, ie. adding and deleting 281 * 282 * simple list traversal with read-only actions can be done with RCU protection 283 * 284 * may be used to exclude some operations from running concurrently without any 285 * modifications to the list (see write_all_supers) 286 * 287 * Is not required at mount and close times, because our device list is 288 * protected by the uuid_mutex at that point. 289 * 290 * balance_mutex 291 * ------------- 292 * protects balance structures (status, state) and context accessed from 293 * several places (internally, ioctl) 294 * 295 * chunk_mutex 296 * ----------- 297 * protects chunks, adding or removing during allocation, trim or when a new 298 * device is added/removed. Additionally it also protects post_commit_list of 299 * individual devices, since they can be added to the transaction's 300 * post_commit_list only with chunk_mutex held. 301 * 302 * cleaner_mutex 303 * ------------- 304 * a big lock that is held by the cleaner thread and prevents running subvolume 305 * cleaning together with relocation or delayed iputs 306 * 307 * 308 * Lock nesting 309 * ============ 310 * 311 * uuid_mutex 312 * device_list_mutex 313 * chunk_mutex 314 * balance_mutex 315 * 316 * 317 * Exclusive operations 318 * ==================== 319 * 320 * Maintains the exclusivity of the following operations that apply to the 321 * whole filesystem and cannot run in parallel. 322 * 323 * - Balance (*) 324 * - Device add 325 * - Device remove 326 * - Device replace (*) 327 * - Resize 328 * 329 * The device operations (as above) can be in one of the following states: 330 * 331 * - Running state 332 * - Paused state 333 * - Completed state 334 * 335 * Only device operations marked with (*) can go into the Paused state for the 336 * following reasons: 337 * 338 * - ioctl (only Balance can be Paused through ioctl) 339 * - filesystem remounted as read-only 340 * - filesystem unmounted and mounted as read-only 341 * - system power-cycle and filesystem mounted as read-only 342 * - filesystem or device errors leading to forced read-only 343 * 344 * The status of exclusive operation is set and cleared atomically. 345 * During the course of Paused state, fs_info::exclusive_operation remains set. 346 * A device operation in Paused or Running state can be canceled or resumed 347 * either by ioctl (Balance only) or when remounted as read-write. 348 * The exclusive status is cleared when the device operation is canceled or 349 * completed. 350 */ 351 352 DEFINE_MUTEX(uuid_mutex); 353 static LIST_HEAD(fs_uuids); 354 struct list_head * __attribute_const__ btrfs_get_fs_uuids(void) 355 { 356 return &fs_uuids; 357 } 358 359 /* 360 * alloc_fs_devices - allocate struct btrfs_fs_devices 361 * @fsid: if not NULL, copy the UUID to fs_devices::fsid 362 * @metadata_fsid: if not NULL, copy the UUID to fs_devices::metadata_fsid 363 * 364 * Return a pointer to a new struct btrfs_fs_devices on success, or ERR_PTR(). 365 * The returned struct is not linked onto any lists and can be destroyed with 366 * kfree() right away. 367 */ 368 static struct btrfs_fs_devices *alloc_fs_devices(const u8 *fsid, 369 const u8 *metadata_fsid) 370 { 371 struct btrfs_fs_devices *fs_devs; 372 373 ASSERT(fsid || !metadata_fsid); 374 375 fs_devs = kzalloc(sizeof(*fs_devs), GFP_KERNEL); 376 if (!fs_devs) 377 return ERR_PTR(-ENOMEM); 378 379 mutex_init(&fs_devs->device_list_mutex); 380 381 INIT_LIST_HEAD(&fs_devs->devices); 382 INIT_LIST_HEAD(&fs_devs->alloc_list); 383 INIT_LIST_HEAD(&fs_devs->fs_list); 384 INIT_LIST_HEAD(&fs_devs->seed_list); 385 386 if (fsid) { 387 memcpy(fs_devs->fsid, fsid, BTRFS_FSID_SIZE); 388 memcpy(fs_devs->metadata_uuid, 389 metadata_fsid ?: fsid, BTRFS_FSID_SIZE); 390 } 391 392 return fs_devs; 393 } 394 395 static void btrfs_free_device(struct btrfs_device *device) 396 { 397 WARN_ON(!list_empty(&device->post_commit_list)); 398 rcu_string_free(device->name); 399 extent_io_tree_release(&device->alloc_state); 400 btrfs_destroy_dev_zone_info(device); 401 kfree(device); 402 } 403 404 static void free_fs_devices(struct btrfs_fs_devices *fs_devices) 405 { 406 struct btrfs_device *device; 407 408 WARN_ON(fs_devices->opened); 409 while (!list_empty(&fs_devices->devices)) { 410 device = list_entry(fs_devices->devices.next, 411 struct btrfs_device, dev_list); 412 list_del(&device->dev_list); 413 btrfs_free_device(device); 414 } 415 kfree(fs_devices); 416 } 417 418 void __exit btrfs_cleanup_fs_uuids(void) 419 { 420 struct btrfs_fs_devices *fs_devices; 421 422 while (!list_empty(&fs_uuids)) { 423 fs_devices = list_entry(fs_uuids.next, 424 struct btrfs_fs_devices, fs_list); 425 list_del(&fs_devices->fs_list); 426 free_fs_devices(fs_devices); 427 } 428 } 429 430 static bool match_fsid_fs_devices(const struct btrfs_fs_devices *fs_devices, 431 const u8 *fsid, const u8 *metadata_fsid) 432 { 433 if (memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE) != 0) 434 return false; 435 436 if (!metadata_fsid) 437 return true; 438 439 if (memcmp(metadata_fsid, fs_devices->metadata_uuid, BTRFS_FSID_SIZE) != 0) 440 return false; 441 442 return true; 443 } 444 445 static noinline struct btrfs_fs_devices *find_fsid( 446 const u8 *fsid, const u8 *metadata_fsid) 447 { 448 struct btrfs_fs_devices *fs_devices; 449 450 ASSERT(fsid); 451 452 /* Handle non-split brain cases */ 453 list_for_each_entry(fs_devices, &fs_uuids, fs_list) { 454 if (match_fsid_fs_devices(fs_devices, fsid, metadata_fsid)) 455 return fs_devices; 456 } 457 return NULL; 458 } 459 460 /* 461 * First check if the metadata_uuid is different from the fsid in the given 462 * fs_devices. Then check if the given fsid is the same as the metadata_uuid 463 * in the fs_devices. If it is, return true; otherwise, return false. 464 */ 465 static inline bool check_fsid_changed(const struct btrfs_fs_devices *fs_devices, 466 const u8 *fsid) 467 { 468 return memcmp(fs_devices->fsid, fs_devices->metadata_uuid, 469 BTRFS_FSID_SIZE) != 0 && 470 memcmp(fs_devices->metadata_uuid, fsid, BTRFS_FSID_SIZE) == 0; 471 } 472 473 static struct btrfs_fs_devices *find_fsid_with_metadata_uuid( 474 struct btrfs_super_block *disk_super) 475 { 476 477 struct btrfs_fs_devices *fs_devices; 478 479 /* 480 * Handle scanned device having completed its fsid change but 481 * belonging to a fs_devices that was created by first scanning 482 * a device which didn't have its fsid/metadata_uuid changed 483 * at all and the CHANGING_FSID_V2 flag set. 484 */ 485 list_for_each_entry(fs_devices, &fs_uuids, fs_list) { 486 if (!fs_devices->fsid_change) 487 continue; 488 489 if (match_fsid_fs_devices(fs_devices, disk_super->metadata_uuid, 490 fs_devices->fsid)) 491 return fs_devices; 492 } 493 494 /* 495 * Handle scanned device having completed its fsid change but 496 * belonging to a fs_devices that was created by a device that 497 * has an outdated pair of fsid/metadata_uuid and 498 * CHANGING_FSID_V2 flag set. 499 */ 500 list_for_each_entry(fs_devices, &fs_uuids, fs_list) { 501 if (!fs_devices->fsid_change) 502 continue; 503 504 if (check_fsid_changed(fs_devices, disk_super->metadata_uuid)) 505 return fs_devices; 506 } 507 508 return find_fsid(disk_super->fsid, disk_super->metadata_uuid); 509 } 510 511 512 static int 513 btrfs_get_bdev_and_sb(const char *device_path, blk_mode_t flags, void *holder, 514 int flush, struct block_device **bdev, 515 struct btrfs_super_block **disk_super) 516 { 517 int ret; 518 519 *bdev = blkdev_get_by_path(device_path, flags, holder, NULL); 520 521 if (IS_ERR(*bdev)) { 522 ret = PTR_ERR(*bdev); 523 goto error; 524 } 525 526 if (flush) 527 sync_blockdev(*bdev); 528 ret = set_blocksize(*bdev, BTRFS_BDEV_BLOCKSIZE); 529 if (ret) { 530 blkdev_put(*bdev, holder); 531 goto error; 532 } 533 invalidate_bdev(*bdev); 534 *disk_super = btrfs_read_dev_super(*bdev); 535 if (IS_ERR(*disk_super)) { 536 ret = PTR_ERR(*disk_super); 537 blkdev_put(*bdev, holder); 538 goto error; 539 } 540 541 return 0; 542 543 error: 544 *bdev = NULL; 545 return ret; 546 } 547 548 /* 549 * Search and remove all stale devices (which are not mounted). When both 550 * inputs are NULL, it will search and release all stale devices. 551 * 552 * @devt: Optional. When provided will it release all unmounted devices 553 * matching this devt only. 554 * @skip_device: Optional. Will skip this device when searching for the stale 555 * devices. 556 * 557 * Return: 0 for success or if @devt is 0. 558 * -EBUSY if @devt is a mounted device. 559 * -ENOENT if @devt does not match any device in the list. 560 */ 561 static int btrfs_free_stale_devices(dev_t devt, struct btrfs_device *skip_device) 562 { 563 struct btrfs_fs_devices *fs_devices, *tmp_fs_devices; 564 struct btrfs_device *device, *tmp_device; 565 int ret = 0; 566 567 lockdep_assert_held(&uuid_mutex); 568 569 if (devt) 570 ret = -ENOENT; 571 572 list_for_each_entry_safe(fs_devices, tmp_fs_devices, &fs_uuids, fs_list) { 573 574 mutex_lock(&fs_devices->device_list_mutex); 575 list_for_each_entry_safe(device, tmp_device, 576 &fs_devices->devices, dev_list) { 577 if (skip_device && skip_device == device) 578 continue; 579 if (devt && devt != device->devt) 580 continue; 581 if (fs_devices->opened) { 582 /* for an already deleted device return 0 */ 583 if (devt && ret != 0) 584 ret = -EBUSY; 585 break; 586 } 587 588 /* delete the stale device */ 589 fs_devices->num_devices--; 590 list_del(&device->dev_list); 591 btrfs_free_device(device); 592 593 ret = 0; 594 } 595 mutex_unlock(&fs_devices->device_list_mutex); 596 597 if (fs_devices->num_devices == 0) { 598 btrfs_sysfs_remove_fsid(fs_devices); 599 list_del(&fs_devices->fs_list); 600 free_fs_devices(fs_devices); 601 } 602 } 603 604 return ret; 605 } 606 607 /* 608 * This is only used on mount, and we are protected from competing things 609 * messing with our fs_devices by the uuid_mutex, thus we do not need the 610 * fs_devices->device_list_mutex here. 611 */ 612 static int btrfs_open_one_device(struct btrfs_fs_devices *fs_devices, 613 struct btrfs_device *device, blk_mode_t flags, 614 void *holder) 615 { 616 struct block_device *bdev; 617 struct btrfs_super_block *disk_super; 618 u64 devid; 619 int ret; 620 621 if (device->bdev) 622 return -EINVAL; 623 if (!device->name) 624 return -EINVAL; 625 626 ret = btrfs_get_bdev_and_sb(device->name->str, flags, holder, 1, 627 &bdev, &disk_super); 628 if (ret) 629 return ret; 630 631 devid = btrfs_stack_device_id(&disk_super->dev_item); 632 if (devid != device->devid) 633 goto error_free_page; 634 635 if (memcmp(device->uuid, disk_super->dev_item.uuid, BTRFS_UUID_SIZE)) 636 goto error_free_page; 637 638 device->generation = btrfs_super_generation(disk_super); 639 640 if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_SEEDING) { 641 if (btrfs_super_incompat_flags(disk_super) & 642 BTRFS_FEATURE_INCOMPAT_METADATA_UUID) { 643 pr_err( 644 "BTRFS: Invalid seeding and uuid-changed device detected\n"); 645 goto error_free_page; 646 } 647 648 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state); 649 fs_devices->seeding = true; 650 } else { 651 if (bdev_read_only(bdev)) 652 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state); 653 else 654 set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state); 655 } 656 657 if (!bdev_nonrot(bdev)) 658 fs_devices->rotating = true; 659 660 if (bdev_max_discard_sectors(bdev)) 661 fs_devices->discardable = true; 662 663 device->bdev = bdev; 664 clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state); 665 device->holder = holder; 666 667 fs_devices->open_devices++; 668 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) && 669 device->devid != BTRFS_DEV_REPLACE_DEVID) { 670 fs_devices->rw_devices++; 671 list_add_tail(&device->dev_alloc_list, &fs_devices->alloc_list); 672 } 673 btrfs_release_disk_super(disk_super); 674 675 return 0; 676 677 error_free_page: 678 btrfs_release_disk_super(disk_super); 679 blkdev_put(bdev, holder); 680 681 return -EINVAL; 682 } 683 684 /* 685 * Handle scanned device having its CHANGING_FSID_V2 flag set and the fs_devices 686 * being created with a disk that has already completed its fsid change. Such 687 * disk can belong to an fs which has its FSID changed or to one which doesn't. 688 * Handle both cases here. 689 */ 690 static struct btrfs_fs_devices *find_fsid_inprogress( 691 struct btrfs_super_block *disk_super) 692 { 693 struct btrfs_fs_devices *fs_devices; 694 695 list_for_each_entry(fs_devices, &fs_uuids, fs_list) { 696 if (fs_devices->fsid_change) 697 continue; 698 699 if (check_fsid_changed(fs_devices, disk_super->fsid)) 700 return fs_devices; 701 } 702 703 return find_fsid(disk_super->fsid, NULL); 704 } 705 706 static struct btrfs_fs_devices *find_fsid_changed( 707 struct btrfs_super_block *disk_super) 708 { 709 struct btrfs_fs_devices *fs_devices; 710 711 /* 712 * Handles the case where scanned device is part of an fs that had 713 * multiple successful changes of FSID but currently device didn't 714 * observe it. Meaning our fsid will be different than theirs. We need 715 * to handle two subcases : 716 * 1 - The fs still continues to have different METADATA/FSID uuids. 717 * 2 - The fs is switched back to its original FSID (METADATA/FSID 718 * are equal). 719 */ 720 list_for_each_entry(fs_devices, &fs_uuids, fs_list) { 721 /* Changed UUIDs */ 722 if (check_fsid_changed(fs_devices, disk_super->metadata_uuid) && 723 memcmp(fs_devices->fsid, disk_super->fsid, 724 BTRFS_FSID_SIZE) != 0) 725 return fs_devices; 726 727 /* Unchanged UUIDs */ 728 if (memcmp(fs_devices->metadata_uuid, fs_devices->fsid, 729 BTRFS_FSID_SIZE) == 0 && 730 memcmp(fs_devices->fsid, disk_super->metadata_uuid, 731 BTRFS_FSID_SIZE) == 0) 732 return fs_devices; 733 } 734 735 return NULL; 736 } 737 738 static struct btrfs_fs_devices *find_fsid_reverted_metadata( 739 struct btrfs_super_block *disk_super) 740 { 741 struct btrfs_fs_devices *fs_devices; 742 743 /* 744 * Handle the case where the scanned device is part of an fs whose last 745 * metadata UUID change reverted it to the original FSID. At the same 746 * time fs_devices was first created by another constituent device 747 * which didn't fully observe the operation. This results in an 748 * btrfs_fs_devices created with metadata/fsid different AND 749 * btrfs_fs_devices::fsid_change set AND the metadata_uuid of the 750 * fs_devices equal to the FSID of the disk. 751 */ 752 list_for_each_entry(fs_devices, &fs_uuids, fs_list) { 753 if (!fs_devices->fsid_change) 754 continue; 755 756 if (check_fsid_changed(fs_devices, disk_super->fsid)) 757 return fs_devices; 758 } 759 760 return NULL; 761 } 762 /* 763 * Add new device to list of registered devices 764 * 765 * Returns: 766 * device pointer which was just added or updated when successful 767 * error pointer when failed 768 */ 769 static noinline struct btrfs_device *device_list_add(const char *path, 770 struct btrfs_super_block *disk_super, 771 bool *new_device_added) 772 { 773 struct btrfs_device *device; 774 struct btrfs_fs_devices *fs_devices = NULL; 775 struct rcu_string *name; 776 u64 found_transid = btrfs_super_generation(disk_super); 777 u64 devid = btrfs_stack_device_id(&disk_super->dev_item); 778 dev_t path_devt; 779 int error; 780 bool has_metadata_uuid = (btrfs_super_incompat_flags(disk_super) & 781 BTRFS_FEATURE_INCOMPAT_METADATA_UUID); 782 bool fsid_change_in_progress = (btrfs_super_flags(disk_super) & 783 BTRFS_SUPER_FLAG_CHANGING_FSID_V2); 784 785 error = lookup_bdev(path, &path_devt); 786 if (error) { 787 btrfs_err(NULL, "failed to lookup block device for path %s: %d", 788 path, error); 789 return ERR_PTR(error); 790 } 791 792 if (fsid_change_in_progress) { 793 if (!has_metadata_uuid) 794 fs_devices = find_fsid_inprogress(disk_super); 795 else 796 fs_devices = find_fsid_changed(disk_super); 797 } else if (has_metadata_uuid) { 798 fs_devices = find_fsid_with_metadata_uuid(disk_super); 799 } else { 800 fs_devices = find_fsid_reverted_metadata(disk_super); 801 if (!fs_devices) 802 fs_devices = find_fsid(disk_super->fsid, NULL); 803 } 804 805 806 if (!fs_devices) { 807 fs_devices = alloc_fs_devices(disk_super->fsid, 808 has_metadata_uuid ? disk_super->metadata_uuid : NULL); 809 if (IS_ERR(fs_devices)) 810 return ERR_CAST(fs_devices); 811 812 fs_devices->fsid_change = fsid_change_in_progress; 813 814 mutex_lock(&fs_devices->device_list_mutex); 815 list_add(&fs_devices->fs_list, &fs_uuids); 816 817 device = NULL; 818 } else { 819 struct btrfs_dev_lookup_args args = { 820 .devid = devid, 821 .uuid = disk_super->dev_item.uuid, 822 }; 823 824 mutex_lock(&fs_devices->device_list_mutex); 825 device = btrfs_find_device(fs_devices, &args); 826 827 /* 828 * If this disk has been pulled into an fs devices created by 829 * a device which had the CHANGING_FSID_V2 flag then replace the 830 * metadata_uuid/fsid values of the fs_devices. 831 */ 832 if (fs_devices->fsid_change && 833 found_transid > fs_devices->latest_generation) { 834 memcpy(fs_devices->fsid, disk_super->fsid, 835 BTRFS_FSID_SIZE); 836 837 if (has_metadata_uuid) 838 memcpy(fs_devices->metadata_uuid, 839 disk_super->metadata_uuid, 840 BTRFS_FSID_SIZE); 841 else 842 memcpy(fs_devices->metadata_uuid, 843 disk_super->fsid, BTRFS_FSID_SIZE); 844 845 fs_devices->fsid_change = false; 846 } 847 } 848 849 if (!device) { 850 unsigned int nofs_flag; 851 852 if (fs_devices->opened) { 853 btrfs_err(NULL, 854 "device %s belongs to fsid %pU, and the fs is already mounted, scanned by %s (%d)", 855 path, fs_devices->fsid, current->comm, 856 task_pid_nr(current)); 857 mutex_unlock(&fs_devices->device_list_mutex); 858 return ERR_PTR(-EBUSY); 859 } 860 861 nofs_flag = memalloc_nofs_save(); 862 device = btrfs_alloc_device(NULL, &devid, 863 disk_super->dev_item.uuid, path); 864 memalloc_nofs_restore(nofs_flag); 865 if (IS_ERR(device)) { 866 mutex_unlock(&fs_devices->device_list_mutex); 867 /* we can safely leave the fs_devices entry around */ 868 return device; 869 } 870 871 device->devt = path_devt; 872 873 list_add_rcu(&device->dev_list, &fs_devices->devices); 874 fs_devices->num_devices++; 875 876 device->fs_devices = fs_devices; 877 *new_device_added = true; 878 879 if (disk_super->label[0]) 880 pr_info( 881 "BTRFS: device label %s devid %llu transid %llu %s scanned by %s (%d)\n", 882 disk_super->label, devid, found_transid, path, 883 current->comm, task_pid_nr(current)); 884 else 885 pr_info( 886 "BTRFS: device fsid %pU devid %llu transid %llu %s scanned by %s (%d)\n", 887 disk_super->fsid, devid, found_transid, path, 888 current->comm, task_pid_nr(current)); 889 890 } else if (!device->name || strcmp(device->name->str, path)) { 891 /* 892 * When FS is already mounted. 893 * 1. If you are here and if the device->name is NULL that 894 * means this device was missing at time of FS mount. 895 * 2. If you are here and if the device->name is different 896 * from 'path' that means either 897 * a. The same device disappeared and reappeared with 898 * different name. or 899 * b. The missing-disk-which-was-replaced, has 900 * reappeared now. 901 * 902 * We must allow 1 and 2a above. But 2b would be a spurious 903 * and unintentional. 904 * 905 * Further in case of 1 and 2a above, the disk at 'path' 906 * would have missed some transaction when it was away and 907 * in case of 2a the stale bdev has to be updated as well. 908 * 2b must not be allowed at all time. 909 */ 910 911 /* 912 * For now, we do allow update to btrfs_fs_device through the 913 * btrfs dev scan cli after FS has been mounted. We're still 914 * tracking a problem where systems fail mount by subvolume id 915 * when we reject replacement on a mounted FS. 916 */ 917 if (!fs_devices->opened && found_transid < device->generation) { 918 /* 919 * That is if the FS is _not_ mounted and if you 920 * are here, that means there is more than one 921 * disk with same uuid and devid.We keep the one 922 * with larger generation number or the last-in if 923 * generation are equal. 924 */ 925 mutex_unlock(&fs_devices->device_list_mutex); 926 btrfs_err(NULL, 927 "device %s already registered with a higher generation, found %llu expect %llu", 928 path, found_transid, device->generation); 929 return ERR_PTR(-EEXIST); 930 } 931 932 /* 933 * We are going to replace the device path for a given devid, 934 * make sure it's the same device if the device is mounted 935 * 936 * NOTE: the device->fs_info may not be reliable here so pass 937 * in a NULL to message helpers instead. This avoids a possible 938 * use-after-free when the fs_info and fs_info->sb are already 939 * torn down. 940 */ 941 if (device->bdev) { 942 if (device->devt != path_devt) { 943 mutex_unlock(&fs_devices->device_list_mutex); 944 btrfs_warn_in_rcu(NULL, 945 "duplicate device %s devid %llu generation %llu scanned by %s (%d)", 946 path, devid, found_transid, 947 current->comm, 948 task_pid_nr(current)); 949 return ERR_PTR(-EEXIST); 950 } 951 btrfs_info_in_rcu(NULL, 952 "devid %llu device path %s changed to %s scanned by %s (%d)", 953 devid, btrfs_dev_name(device), 954 path, current->comm, 955 task_pid_nr(current)); 956 } 957 958 name = rcu_string_strdup(path, GFP_NOFS); 959 if (!name) { 960 mutex_unlock(&fs_devices->device_list_mutex); 961 return ERR_PTR(-ENOMEM); 962 } 963 rcu_string_free(device->name); 964 rcu_assign_pointer(device->name, name); 965 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) { 966 fs_devices->missing_devices--; 967 clear_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state); 968 } 969 device->devt = path_devt; 970 } 971 972 /* 973 * Unmount does not free the btrfs_device struct but would zero 974 * generation along with most of the other members. So just update 975 * it back. We need it to pick the disk with largest generation 976 * (as above). 977 */ 978 if (!fs_devices->opened) { 979 device->generation = found_transid; 980 fs_devices->latest_generation = max_t(u64, found_transid, 981 fs_devices->latest_generation); 982 } 983 984 fs_devices->total_devices = btrfs_super_num_devices(disk_super); 985 986 mutex_unlock(&fs_devices->device_list_mutex); 987 return device; 988 } 989 990 static struct btrfs_fs_devices *clone_fs_devices(struct btrfs_fs_devices *orig) 991 { 992 struct btrfs_fs_devices *fs_devices; 993 struct btrfs_device *device; 994 struct btrfs_device *orig_dev; 995 int ret = 0; 996 997 lockdep_assert_held(&uuid_mutex); 998 999 fs_devices = alloc_fs_devices(orig->fsid, NULL); 1000 if (IS_ERR(fs_devices)) 1001 return fs_devices; 1002 1003 fs_devices->total_devices = orig->total_devices; 1004 1005 list_for_each_entry(orig_dev, &orig->devices, dev_list) { 1006 const char *dev_path = NULL; 1007 1008 /* 1009 * This is ok to do without RCU read locked because we hold the 1010 * uuid mutex so nothing we touch in here is going to disappear. 1011 */ 1012 if (orig_dev->name) 1013 dev_path = orig_dev->name->str; 1014 1015 device = btrfs_alloc_device(NULL, &orig_dev->devid, 1016 orig_dev->uuid, dev_path); 1017 if (IS_ERR(device)) { 1018 ret = PTR_ERR(device); 1019 goto error; 1020 } 1021 1022 if (orig_dev->zone_info) { 1023 struct btrfs_zoned_device_info *zone_info; 1024 1025 zone_info = btrfs_clone_dev_zone_info(orig_dev); 1026 if (!zone_info) { 1027 btrfs_free_device(device); 1028 ret = -ENOMEM; 1029 goto error; 1030 } 1031 device->zone_info = zone_info; 1032 } 1033 1034 list_add(&device->dev_list, &fs_devices->devices); 1035 device->fs_devices = fs_devices; 1036 fs_devices->num_devices++; 1037 } 1038 return fs_devices; 1039 error: 1040 free_fs_devices(fs_devices); 1041 return ERR_PTR(ret); 1042 } 1043 1044 static void __btrfs_free_extra_devids(struct btrfs_fs_devices *fs_devices, 1045 struct btrfs_device **latest_dev) 1046 { 1047 struct btrfs_device *device, *next; 1048 1049 /* This is the initialized path, it is safe to release the devices. */ 1050 list_for_each_entry_safe(device, next, &fs_devices->devices, dev_list) { 1051 if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state)) { 1052 if (!test_bit(BTRFS_DEV_STATE_REPLACE_TGT, 1053 &device->dev_state) && 1054 !test_bit(BTRFS_DEV_STATE_MISSING, 1055 &device->dev_state) && 1056 (!*latest_dev || 1057 device->generation > (*latest_dev)->generation)) { 1058 *latest_dev = device; 1059 } 1060 continue; 1061 } 1062 1063 /* 1064 * We have already validated the presence of BTRFS_DEV_REPLACE_DEVID, 1065 * in btrfs_init_dev_replace() so just continue. 1066 */ 1067 if (device->devid == BTRFS_DEV_REPLACE_DEVID) 1068 continue; 1069 1070 if (device->bdev) { 1071 blkdev_put(device->bdev, device->holder); 1072 device->bdev = NULL; 1073 fs_devices->open_devices--; 1074 } 1075 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) { 1076 list_del_init(&device->dev_alloc_list); 1077 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state); 1078 fs_devices->rw_devices--; 1079 } 1080 list_del_init(&device->dev_list); 1081 fs_devices->num_devices--; 1082 btrfs_free_device(device); 1083 } 1084 1085 } 1086 1087 /* 1088 * After we have read the system tree and know devids belonging to this 1089 * filesystem, remove the device which does not belong there. 1090 */ 1091 void btrfs_free_extra_devids(struct btrfs_fs_devices *fs_devices) 1092 { 1093 struct btrfs_device *latest_dev = NULL; 1094 struct btrfs_fs_devices *seed_dev; 1095 1096 mutex_lock(&uuid_mutex); 1097 __btrfs_free_extra_devids(fs_devices, &latest_dev); 1098 1099 list_for_each_entry(seed_dev, &fs_devices->seed_list, seed_list) 1100 __btrfs_free_extra_devids(seed_dev, &latest_dev); 1101 1102 fs_devices->latest_dev = latest_dev; 1103 1104 mutex_unlock(&uuid_mutex); 1105 } 1106 1107 static void btrfs_close_bdev(struct btrfs_device *device) 1108 { 1109 if (!device->bdev) 1110 return; 1111 1112 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) { 1113 sync_blockdev(device->bdev); 1114 invalidate_bdev(device->bdev); 1115 } 1116 1117 blkdev_put(device->bdev, device->holder); 1118 } 1119 1120 static void btrfs_close_one_device(struct btrfs_device *device) 1121 { 1122 struct btrfs_fs_devices *fs_devices = device->fs_devices; 1123 1124 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) && 1125 device->devid != BTRFS_DEV_REPLACE_DEVID) { 1126 list_del_init(&device->dev_alloc_list); 1127 fs_devices->rw_devices--; 1128 } 1129 1130 if (device->devid == BTRFS_DEV_REPLACE_DEVID) 1131 clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state); 1132 1133 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) { 1134 clear_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state); 1135 fs_devices->missing_devices--; 1136 } 1137 1138 btrfs_close_bdev(device); 1139 if (device->bdev) { 1140 fs_devices->open_devices--; 1141 device->bdev = NULL; 1142 } 1143 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state); 1144 btrfs_destroy_dev_zone_info(device); 1145 1146 device->fs_info = NULL; 1147 atomic_set(&device->dev_stats_ccnt, 0); 1148 extent_io_tree_release(&device->alloc_state); 1149 1150 /* 1151 * Reset the flush error record. We might have a transient flush error 1152 * in this mount, and if so we aborted the current transaction and set 1153 * the fs to an error state, guaranteeing no super blocks can be further 1154 * committed. However that error might be transient and if we unmount the 1155 * filesystem and mount it again, we should allow the mount to succeed 1156 * (btrfs_check_rw_degradable() should not fail) - if after mounting the 1157 * filesystem again we still get flush errors, then we will again abort 1158 * any transaction and set the error state, guaranteeing no commits of 1159 * unsafe super blocks. 1160 */ 1161 device->last_flush_error = 0; 1162 1163 /* Verify the device is back in a pristine state */ 1164 WARN_ON(test_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state)); 1165 WARN_ON(test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)); 1166 WARN_ON(!list_empty(&device->dev_alloc_list)); 1167 WARN_ON(!list_empty(&device->post_commit_list)); 1168 } 1169 1170 static void close_fs_devices(struct btrfs_fs_devices *fs_devices) 1171 { 1172 struct btrfs_device *device, *tmp; 1173 1174 lockdep_assert_held(&uuid_mutex); 1175 1176 if (--fs_devices->opened > 0) 1177 return; 1178 1179 list_for_each_entry_safe(device, tmp, &fs_devices->devices, dev_list) 1180 btrfs_close_one_device(device); 1181 1182 WARN_ON(fs_devices->open_devices); 1183 WARN_ON(fs_devices->rw_devices); 1184 fs_devices->opened = 0; 1185 fs_devices->seeding = false; 1186 fs_devices->fs_info = NULL; 1187 } 1188 1189 void btrfs_close_devices(struct btrfs_fs_devices *fs_devices) 1190 { 1191 LIST_HEAD(list); 1192 struct btrfs_fs_devices *tmp; 1193 1194 mutex_lock(&uuid_mutex); 1195 close_fs_devices(fs_devices); 1196 if (!fs_devices->opened) { 1197 list_splice_init(&fs_devices->seed_list, &list); 1198 1199 /* 1200 * If the struct btrfs_fs_devices is not assembled with any 1201 * other device, it can be re-initialized during the next mount 1202 * without the needing device-scan step. Therefore, it can be 1203 * fully freed. 1204 */ 1205 if (fs_devices->num_devices == 1) { 1206 list_del(&fs_devices->fs_list); 1207 free_fs_devices(fs_devices); 1208 } 1209 } 1210 1211 1212 list_for_each_entry_safe(fs_devices, tmp, &list, seed_list) { 1213 close_fs_devices(fs_devices); 1214 list_del(&fs_devices->seed_list); 1215 free_fs_devices(fs_devices); 1216 } 1217 mutex_unlock(&uuid_mutex); 1218 } 1219 1220 static int open_fs_devices(struct btrfs_fs_devices *fs_devices, 1221 blk_mode_t flags, void *holder) 1222 { 1223 struct btrfs_device *device; 1224 struct btrfs_device *latest_dev = NULL; 1225 struct btrfs_device *tmp_device; 1226 1227 list_for_each_entry_safe(device, tmp_device, &fs_devices->devices, 1228 dev_list) { 1229 int ret; 1230 1231 ret = btrfs_open_one_device(fs_devices, device, flags, holder); 1232 if (ret == 0 && 1233 (!latest_dev || device->generation > latest_dev->generation)) { 1234 latest_dev = device; 1235 } else if (ret == -ENODATA) { 1236 fs_devices->num_devices--; 1237 list_del(&device->dev_list); 1238 btrfs_free_device(device); 1239 } 1240 } 1241 if (fs_devices->open_devices == 0) 1242 return -EINVAL; 1243 1244 fs_devices->opened = 1; 1245 fs_devices->latest_dev = latest_dev; 1246 fs_devices->total_rw_bytes = 0; 1247 fs_devices->chunk_alloc_policy = BTRFS_CHUNK_ALLOC_REGULAR; 1248 fs_devices->read_policy = BTRFS_READ_POLICY_PID; 1249 1250 return 0; 1251 } 1252 1253 static int devid_cmp(void *priv, const struct list_head *a, 1254 const struct list_head *b) 1255 { 1256 const struct btrfs_device *dev1, *dev2; 1257 1258 dev1 = list_entry(a, struct btrfs_device, dev_list); 1259 dev2 = list_entry(b, struct btrfs_device, dev_list); 1260 1261 if (dev1->devid < dev2->devid) 1262 return -1; 1263 else if (dev1->devid > dev2->devid) 1264 return 1; 1265 return 0; 1266 } 1267 1268 int btrfs_open_devices(struct btrfs_fs_devices *fs_devices, 1269 blk_mode_t flags, void *holder) 1270 { 1271 int ret; 1272 1273 lockdep_assert_held(&uuid_mutex); 1274 /* 1275 * The device_list_mutex cannot be taken here in case opening the 1276 * underlying device takes further locks like open_mutex. 1277 * 1278 * We also don't need the lock here as this is called during mount and 1279 * exclusion is provided by uuid_mutex 1280 */ 1281 1282 if (fs_devices->opened) { 1283 fs_devices->opened++; 1284 ret = 0; 1285 } else { 1286 list_sort(NULL, &fs_devices->devices, devid_cmp); 1287 ret = open_fs_devices(fs_devices, flags, holder); 1288 } 1289 1290 return ret; 1291 } 1292 1293 void btrfs_release_disk_super(struct btrfs_super_block *super) 1294 { 1295 struct page *page = virt_to_page(super); 1296 1297 put_page(page); 1298 } 1299 1300 static struct btrfs_super_block *btrfs_read_disk_super(struct block_device *bdev, 1301 u64 bytenr, u64 bytenr_orig) 1302 { 1303 struct btrfs_super_block *disk_super; 1304 struct page *page; 1305 void *p; 1306 pgoff_t index; 1307 1308 /* make sure our super fits in the device */ 1309 if (bytenr + PAGE_SIZE >= bdev_nr_bytes(bdev)) 1310 return ERR_PTR(-EINVAL); 1311 1312 /* make sure our super fits in the page */ 1313 if (sizeof(*disk_super) > PAGE_SIZE) 1314 return ERR_PTR(-EINVAL); 1315 1316 /* make sure our super doesn't straddle pages on disk */ 1317 index = bytenr >> PAGE_SHIFT; 1318 if ((bytenr + sizeof(*disk_super) - 1) >> PAGE_SHIFT != index) 1319 return ERR_PTR(-EINVAL); 1320 1321 /* pull in the page with our super */ 1322 page = read_cache_page_gfp(bdev->bd_inode->i_mapping, index, GFP_KERNEL); 1323 1324 if (IS_ERR(page)) 1325 return ERR_CAST(page); 1326 1327 p = page_address(page); 1328 1329 /* align our pointer to the offset of the super block */ 1330 disk_super = p + offset_in_page(bytenr); 1331 1332 if (btrfs_super_bytenr(disk_super) != bytenr_orig || 1333 btrfs_super_magic(disk_super) != BTRFS_MAGIC) { 1334 btrfs_release_disk_super(p); 1335 return ERR_PTR(-EINVAL); 1336 } 1337 1338 if (disk_super->label[0] && disk_super->label[BTRFS_LABEL_SIZE - 1]) 1339 disk_super->label[BTRFS_LABEL_SIZE - 1] = 0; 1340 1341 return disk_super; 1342 } 1343 1344 int btrfs_forget_devices(dev_t devt) 1345 { 1346 int ret; 1347 1348 mutex_lock(&uuid_mutex); 1349 ret = btrfs_free_stale_devices(devt, NULL); 1350 mutex_unlock(&uuid_mutex); 1351 1352 return ret; 1353 } 1354 1355 /* 1356 * Look for a btrfs signature on a device. This may be called out of the mount path 1357 * and we are not allowed to call set_blocksize during the scan. The superblock 1358 * is read via pagecache 1359 */ 1360 struct btrfs_device *btrfs_scan_one_device(const char *path, blk_mode_t flags) 1361 { 1362 struct btrfs_super_block *disk_super; 1363 bool new_device_added = false; 1364 struct btrfs_device *device = NULL; 1365 struct block_device *bdev; 1366 u64 bytenr, bytenr_orig; 1367 int ret; 1368 1369 lockdep_assert_held(&uuid_mutex); 1370 1371 /* 1372 * we would like to check all the supers, but that would make 1373 * a btrfs mount succeed after a mkfs from a different FS. 1374 * So, we need to add a special mount option to scan for 1375 * later supers, using BTRFS_SUPER_MIRROR_MAX instead 1376 */ 1377 1378 /* 1379 * Avoid an exclusive open here, as the systemd-udev may initiate the 1380 * device scan which may race with the user's mount or mkfs command, 1381 * resulting in failure. 1382 * Since the device scan is solely for reading purposes, there is no 1383 * need for an exclusive open. Additionally, the devices are read again 1384 * during the mount process. It is ok to get some inconsistent 1385 * values temporarily, as the device paths of the fsid are the only 1386 * required information for assembling the volume. 1387 */ 1388 bdev = blkdev_get_by_path(path, flags, NULL, NULL); 1389 if (IS_ERR(bdev)) 1390 return ERR_CAST(bdev); 1391 1392 bytenr_orig = btrfs_sb_offset(0); 1393 ret = btrfs_sb_log_location_bdev(bdev, 0, READ, &bytenr); 1394 if (ret) { 1395 device = ERR_PTR(ret); 1396 goto error_bdev_put; 1397 } 1398 1399 disk_super = btrfs_read_disk_super(bdev, bytenr, bytenr_orig); 1400 if (IS_ERR(disk_super)) { 1401 device = ERR_CAST(disk_super); 1402 goto error_bdev_put; 1403 } 1404 1405 device = device_list_add(path, disk_super, &new_device_added); 1406 if (!IS_ERR(device) && new_device_added) 1407 btrfs_free_stale_devices(device->devt, device); 1408 1409 btrfs_release_disk_super(disk_super); 1410 1411 error_bdev_put: 1412 blkdev_put(bdev, NULL); 1413 1414 return device; 1415 } 1416 1417 /* 1418 * Try to find a chunk that intersects [start, start + len] range and when one 1419 * such is found, record the end of it in *start 1420 */ 1421 static bool contains_pending_extent(struct btrfs_device *device, u64 *start, 1422 u64 len) 1423 { 1424 u64 physical_start, physical_end; 1425 1426 lockdep_assert_held(&device->fs_info->chunk_mutex); 1427 1428 if (find_first_extent_bit(&device->alloc_state, *start, 1429 &physical_start, &physical_end, 1430 CHUNK_ALLOCATED, NULL)) { 1431 1432 if (in_range(physical_start, *start, len) || 1433 in_range(*start, physical_start, 1434 physical_end - physical_start)) { 1435 *start = physical_end + 1; 1436 return true; 1437 } 1438 } 1439 return false; 1440 } 1441 1442 static u64 dev_extent_search_start(struct btrfs_device *device, u64 start) 1443 { 1444 switch (device->fs_devices->chunk_alloc_policy) { 1445 case BTRFS_CHUNK_ALLOC_REGULAR: 1446 return max_t(u64, start, BTRFS_DEVICE_RANGE_RESERVED); 1447 case BTRFS_CHUNK_ALLOC_ZONED: 1448 /* 1449 * We don't care about the starting region like regular 1450 * allocator, because we anyway use/reserve the first two zones 1451 * for superblock logging. 1452 */ 1453 return ALIGN(start, device->zone_info->zone_size); 1454 default: 1455 BUG(); 1456 } 1457 } 1458 1459 static bool dev_extent_hole_check_zoned(struct btrfs_device *device, 1460 u64 *hole_start, u64 *hole_size, 1461 u64 num_bytes) 1462 { 1463 u64 zone_size = device->zone_info->zone_size; 1464 u64 pos; 1465 int ret; 1466 bool changed = false; 1467 1468 ASSERT(IS_ALIGNED(*hole_start, zone_size)); 1469 1470 while (*hole_size > 0) { 1471 pos = btrfs_find_allocatable_zones(device, *hole_start, 1472 *hole_start + *hole_size, 1473 num_bytes); 1474 if (pos != *hole_start) { 1475 *hole_size = *hole_start + *hole_size - pos; 1476 *hole_start = pos; 1477 changed = true; 1478 if (*hole_size < num_bytes) 1479 break; 1480 } 1481 1482 ret = btrfs_ensure_empty_zones(device, pos, num_bytes); 1483 1484 /* Range is ensured to be empty */ 1485 if (!ret) 1486 return changed; 1487 1488 /* Given hole range was invalid (outside of device) */ 1489 if (ret == -ERANGE) { 1490 *hole_start += *hole_size; 1491 *hole_size = 0; 1492 return true; 1493 } 1494 1495 *hole_start += zone_size; 1496 *hole_size -= zone_size; 1497 changed = true; 1498 } 1499 1500 return changed; 1501 } 1502 1503 /* 1504 * Check if specified hole is suitable for allocation. 1505 * 1506 * @device: the device which we have the hole 1507 * @hole_start: starting position of the hole 1508 * @hole_size: the size of the hole 1509 * @num_bytes: the size of the free space that we need 1510 * 1511 * This function may modify @hole_start and @hole_size to reflect the suitable 1512 * position for allocation. Returns 1 if hole position is updated, 0 otherwise. 1513 */ 1514 static bool dev_extent_hole_check(struct btrfs_device *device, u64 *hole_start, 1515 u64 *hole_size, u64 num_bytes) 1516 { 1517 bool changed = false; 1518 u64 hole_end = *hole_start + *hole_size; 1519 1520 for (;;) { 1521 /* 1522 * Check before we set max_hole_start, otherwise we could end up 1523 * sending back this offset anyway. 1524 */ 1525 if (contains_pending_extent(device, hole_start, *hole_size)) { 1526 if (hole_end >= *hole_start) 1527 *hole_size = hole_end - *hole_start; 1528 else 1529 *hole_size = 0; 1530 changed = true; 1531 } 1532 1533 switch (device->fs_devices->chunk_alloc_policy) { 1534 case BTRFS_CHUNK_ALLOC_REGULAR: 1535 /* No extra check */ 1536 break; 1537 case BTRFS_CHUNK_ALLOC_ZONED: 1538 if (dev_extent_hole_check_zoned(device, hole_start, 1539 hole_size, num_bytes)) { 1540 changed = true; 1541 /* 1542 * The changed hole can contain pending extent. 1543 * Loop again to check that. 1544 */ 1545 continue; 1546 } 1547 break; 1548 default: 1549 BUG(); 1550 } 1551 1552 break; 1553 } 1554 1555 return changed; 1556 } 1557 1558 /* 1559 * Find free space in the specified device. 1560 * 1561 * @device: the device which we search the free space in 1562 * @num_bytes: the size of the free space that we need 1563 * @search_start: the position from which to begin the search 1564 * @start: store the start of the free space. 1565 * @len: the size of the free space. that we find, or the size 1566 * of the max free space if we don't find suitable free space 1567 * 1568 * This does a pretty simple search, the expectation is that it is called very 1569 * infrequently and that a given device has a small number of extents. 1570 * 1571 * @start is used to store the start of the free space if we find. But if we 1572 * don't find suitable free space, it will be used to store the start position 1573 * of the max free space. 1574 * 1575 * @len is used to store the size of the free space that we find. 1576 * But if we don't find suitable free space, it is used to store the size of 1577 * the max free space. 1578 * 1579 * NOTE: This function will search *commit* root of device tree, and does extra 1580 * check to ensure dev extents are not double allocated. 1581 * This makes the function safe to allocate dev extents but may not report 1582 * correct usable device space, as device extent freed in current transaction 1583 * is not reported as available. 1584 */ 1585 static int find_free_dev_extent_start(struct btrfs_device *device, 1586 u64 num_bytes, u64 search_start, u64 *start, 1587 u64 *len) 1588 { 1589 struct btrfs_fs_info *fs_info = device->fs_info; 1590 struct btrfs_root *root = fs_info->dev_root; 1591 struct btrfs_key key; 1592 struct btrfs_dev_extent *dev_extent; 1593 struct btrfs_path *path; 1594 u64 hole_size; 1595 u64 max_hole_start; 1596 u64 max_hole_size; 1597 u64 extent_end; 1598 u64 search_end = device->total_bytes; 1599 int ret; 1600 int slot; 1601 struct extent_buffer *l; 1602 1603 search_start = dev_extent_search_start(device, search_start); 1604 1605 WARN_ON(device->zone_info && 1606 !IS_ALIGNED(num_bytes, device->zone_info->zone_size)); 1607 1608 path = btrfs_alloc_path(); 1609 if (!path) 1610 return -ENOMEM; 1611 1612 max_hole_start = search_start; 1613 max_hole_size = 0; 1614 1615 again: 1616 if (search_start >= search_end || 1617 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) { 1618 ret = -ENOSPC; 1619 goto out; 1620 } 1621 1622 path->reada = READA_FORWARD; 1623 path->search_commit_root = 1; 1624 path->skip_locking = 1; 1625 1626 key.objectid = device->devid; 1627 key.offset = search_start; 1628 key.type = BTRFS_DEV_EXTENT_KEY; 1629 1630 ret = btrfs_search_backwards(root, &key, path); 1631 if (ret < 0) 1632 goto out; 1633 1634 while (search_start < search_end) { 1635 l = path->nodes[0]; 1636 slot = path->slots[0]; 1637 if (slot >= btrfs_header_nritems(l)) { 1638 ret = btrfs_next_leaf(root, path); 1639 if (ret == 0) 1640 continue; 1641 if (ret < 0) 1642 goto out; 1643 1644 break; 1645 } 1646 btrfs_item_key_to_cpu(l, &key, slot); 1647 1648 if (key.objectid < device->devid) 1649 goto next; 1650 1651 if (key.objectid > device->devid) 1652 break; 1653 1654 if (key.type != BTRFS_DEV_EXTENT_KEY) 1655 goto next; 1656 1657 if (key.offset > search_end) 1658 break; 1659 1660 if (key.offset > search_start) { 1661 hole_size = key.offset - search_start; 1662 dev_extent_hole_check(device, &search_start, &hole_size, 1663 num_bytes); 1664 1665 if (hole_size > max_hole_size) { 1666 max_hole_start = search_start; 1667 max_hole_size = hole_size; 1668 } 1669 1670 /* 1671 * If this free space is greater than which we need, 1672 * it must be the max free space that we have found 1673 * until now, so max_hole_start must point to the start 1674 * of this free space and the length of this free space 1675 * is stored in max_hole_size. Thus, we return 1676 * max_hole_start and max_hole_size and go back to the 1677 * caller. 1678 */ 1679 if (hole_size >= num_bytes) { 1680 ret = 0; 1681 goto out; 1682 } 1683 } 1684 1685 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent); 1686 extent_end = key.offset + btrfs_dev_extent_length(l, 1687 dev_extent); 1688 if (extent_end > search_start) 1689 search_start = extent_end; 1690 next: 1691 path->slots[0]++; 1692 cond_resched(); 1693 } 1694 1695 /* 1696 * At this point, search_start should be the end of 1697 * allocated dev extents, and when shrinking the device, 1698 * search_end may be smaller than search_start. 1699 */ 1700 if (search_end > search_start) { 1701 hole_size = search_end - search_start; 1702 if (dev_extent_hole_check(device, &search_start, &hole_size, 1703 num_bytes)) { 1704 btrfs_release_path(path); 1705 goto again; 1706 } 1707 1708 if (hole_size > max_hole_size) { 1709 max_hole_start = search_start; 1710 max_hole_size = hole_size; 1711 } 1712 } 1713 1714 /* See above. */ 1715 if (max_hole_size < num_bytes) 1716 ret = -ENOSPC; 1717 else 1718 ret = 0; 1719 1720 ASSERT(max_hole_start + max_hole_size <= search_end); 1721 out: 1722 btrfs_free_path(path); 1723 *start = max_hole_start; 1724 if (len) 1725 *len = max_hole_size; 1726 return ret; 1727 } 1728 1729 int find_free_dev_extent(struct btrfs_device *device, u64 num_bytes, 1730 u64 *start, u64 *len) 1731 { 1732 /* FIXME use last free of some kind */ 1733 return find_free_dev_extent_start(device, num_bytes, 0, start, len); 1734 } 1735 1736 static int btrfs_free_dev_extent(struct btrfs_trans_handle *trans, 1737 struct btrfs_device *device, 1738 u64 start, u64 *dev_extent_len) 1739 { 1740 struct btrfs_fs_info *fs_info = device->fs_info; 1741 struct btrfs_root *root = fs_info->dev_root; 1742 int ret; 1743 struct btrfs_path *path; 1744 struct btrfs_key key; 1745 struct btrfs_key found_key; 1746 struct extent_buffer *leaf = NULL; 1747 struct btrfs_dev_extent *extent = NULL; 1748 1749 path = btrfs_alloc_path(); 1750 if (!path) 1751 return -ENOMEM; 1752 1753 key.objectid = device->devid; 1754 key.offset = start; 1755 key.type = BTRFS_DEV_EXTENT_KEY; 1756 again: 1757 ret = btrfs_search_slot(trans, root, &key, path, -1, 1); 1758 if (ret > 0) { 1759 ret = btrfs_previous_item(root, path, key.objectid, 1760 BTRFS_DEV_EXTENT_KEY); 1761 if (ret) 1762 goto out; 1763 leaf = path->nodes[0]; 1764 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]); 1765 extent = btrfs_item_ptr(leaf, path->slots[0], 1766 struct btrfs_dev_extent); 1767 BUG_ON(found_key.offset > start || found_key.offset + 1768 btrfs_dev_extent_length(leaf, extent) < start); 1769 key = found_key; 1770 btrfs_release_path(path); 1771 goto again; 1772 } else if (ret == 0) { 1773 leaf = path->nodes[0]; 1774 extent = btrfs_item_ptr(leaf, path->slots[0], 1775 struct btrfs_dev_extent); 1776 } else { 1777 goto out; 1778 } 1779 1780 *dev_extent_len = btrfs_dev_extent_length(leaf, extent); 1781 1782 ret = btrfs_del_item(trans, root, path); 1783 if (ret == 0) 1784 set_bit(BTRFS_TRANS_HAVE_FREE_BGS, &trans->transaction->flags); 1785 out: 1786 btrfs_free_path(path); 1787 return ret; 1788 } 1789 1790 static u64 find_next_chunk(struct btrfs_fs_info *fs_info) 1791 { 1792 struct extent_map_tree *em_tree; 1793 struct extent_map *em; 1794 struct rb_node *n; 1795 u64 ret = 0; 1796 1797 em_tree = &fs_info->mapping_tree; 1798 read_lock(&em_tree->lock); 1799 n = rb_last(&em_tree->map.rb_root); 1800 if (n) { 1801 em = rb_entry(n, struct extent_map, rb_node); 1802 ret = em->start + em->len; 1803 } 1804 read_unlock(&em_tree->lock); 1805 1806 return ret; 1807 } 1808 1809 static noinline int find_next_devid(struct btrfs_fs_info *fs_info, 1810 u64 *devid_ret) 1811 { 1812 int ret; 1813 struct btrfs_key key; 1814 struct btrfs_key found_key; 1815 struct btrfs_path *path; 1816 1817 path = btrfs_alloc_path(); 1818 if (!path) 1819 return -ENOMEM; 1820 1821 key.objectid = BTRFS_DEV_ITEMS_OBJECTID; 1822 key.type = BTRFS_DEV_ITEM_KEY; 1823 key.offset = (u64)-1; 1824 1825 ret = btrfs_search_slot(NULL, fs_info->chunk_root, &key, path, 0, 0); 1826 if (ret < 0) 1827 goto error; 1828 1829 if (ret == 0) { 1830 /* Corruption */ 1831 btrfs_err(fs_info, "corrupted chunk tree devid -1 matched"); 1832 ret = -EUCLEAN; 1833 goto error; 1834 } 1835 1836 ret = btrfs_previous_item(fs_info->chunk_root, path, 1837 BTRFS_DEV_ITEMS_OBJECTID, 1838 BTRFS_DEV_ITEM_KEY); 1839 if (ret) { 1840 *devid_ret = 1; 1841 } else { 1842 btrfs_item_key_to_cpu(path->nodes[0], &found_key, 1843 path->slots[0]); 1844 *devid_ret = found_key.offset + 1; 1845 } 1846 ret = 0; 1847 error: 1848 btrfs_free_path(path); 1849 return ret; 1850 } 1851 1852 /* 1853 * the device information is stored in the chunk root 1854 * the btrfs_device struct should be fully filled in 1855 */ 1856 static int btrfs_add_dev_item(struct btrfs_trans_handle *trans, 1857 struct btrfs_device *device) 1858 { 1859 int ret; 1860 struct btrfs_path *path; 1861 struct btrfs_dev_item *dev_item; 1862 struct extent_buffer *leaf; 1863 struct btrfs_key key; 1864 unsigned long ptr; 1865 1866 path = btrfs_alloc_path(); 1867 if (!path) 1868 return -ENOMEM; 1869 1870 key.objectid = BTRFS_DEV_ITEMS_OBJECTID; 1871 key.type = BTRFS_DEV_ITEM_KEY; 1872 key.offset = device->devid; 1873 1874 btrfs_reserve_chunk_metadata(trans, true); 1875 ret = btrfs_insert_empty_item(trans, trans->fs_info->chunk_root, path, 1876 &key, sizeof(*dev_item)); 1877 btrfs_trans_release_chunk_metadata(trans); 1878 if (ret) 1879 goto out; 1880 1881 leaf = path->nodes[0]; 1882 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item); 1883 1884 btrfs_set_device_id(leaf, dev_item, device->devid); 1885 btrfs_set_device_generation(leaf, dev_item, 0); 1886 btrfs_set_device_type(leaf, dev_item, device->type); 1887 btrfs_set_device_io_align(leaf, dev_item, device->io_align); 1888 btrfs_set_device_io_width(leaf, dev_item, device->io_width); 1889 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size); 1890 btrfs_set_device_total_bytes(leaf, dev_item, 1891 btrfs_device_get_disk_total_bytes(device)); 1892 btrfs_set_device_bytes_used(leaf, dev_item, 1893 btrfs_device_get_bytes_used(device)); 1894 btrfs_set_device_group(leaf, dev_item, 0); 1895 btrfs_set_device_seek_speed(leaf, dev_item, 0); 1896 btrfs_set_device_bandwidth(leaf, dev_item, 0); 1897 btrfs_set_device_start_offset(leaf, dev_item, 0); 1898 1899 ptr = btrfs_device_uuid(dev_item); 1900 write_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE); 1901 ptr = btrfs_device_fsid(dev_item); 1902 write_extent_buffer(leaf, trans->fs_info->fs_devices->metadata_uuid, 1903 ptr, BTRFS_FSID_SIZE); 1904 btrfs_mark_buffer_dirty(leaf); 1905 1906 ret = 0; 1907 out: 1908 btrfs_free_path(path); 1909 return ret; 1910 } 1911 1912 /* 1913 * Function to update ctime/mtime for a given device path. 1914 * Mainly used for ctime/mtime based probe like libblkid. 1915 * 1916 * We don't care about errors here, this is just to be kind to userspace. 1917 */ 1918 static void update_dev_time(const char *device_path) 1919 { 1920 struct path path; 1921 struct timespec64 now; 1922 int ret; 1923 1924 ret = kern_path(device_path, LOOKUP_FOLLOW, &path); 1925 if (ret) 1926 return; 1927 1928 now = current_time(d_inode(path.dentry)); 1929 inode_update_time(d_inode(path.dentry), &now, S_MTIME | S_CTIME | S_VERSION); 1930 path_put(&path); 1931 } 1932 1933 static int btrfs_rm_dev_item(struct btrfs_trans_handle *trans, 1934 struct btrfs_device *device) 1935 { 1936 struct btrfs_root *root = device->fs_info->chunk_root; 1937 int ret; 1938 struct btrfs_path *path; 1939 struct btrfs_key key; 1940 1941 path = btrfs_alloc_path(); 1942 if (!path) 1943 return -ENOMEM; 1944 1945 key.objectid = BTRFS_DEV_ITEMS_OBJECTID; 1946 key.type = BTRFS_DEV_ITEM_KEY; 1947 key.offset = device->devid; 1948 1949 btrfs_reserve_chunk_metadata(trans, false); 1950 ret = btrfs_search_slot(trans, root, &key, path, -1, 1); 1951 btrfs_trans_release_chunk_metadata(trans); 1952 if (ret) { 1953 if (ret > 0) 1954 ret = -ENOENT; 1955 goto out; 1956 } 1957 1958 ret = btrfs_del_item(trans, root, path); 1959 out: 1960 btrfs_free_path(path); 1961 return ret; 1962 } 1963 1964 /* 1965 * Verify that @num_devices satisfies the RAID profile constraints in the whole 1966 * filesystem. It's up to the caller to adjust that number regarding eg. device 1967 * replace. 1968 */ 1969 static int btrfs_check_raid_min_devices(struct btrfs_fs_info *fs_info, 1970 u64 num_devices) 1971 { 1972 u64 all_avail; 1973 unsigned seq; 1974 int i; 1975 1976 do { 1977 seq = read_seqbegin(&fs_info->profiles_lock); 1978 1979 all_avail = fs_info->avail_data_alloc_bits | 1980 fs_info->avail_system_alloc_bits | 1981 fs_info->avail_metadata_alloc_bits; 1982 } while (read_seqretry(&fs_info->profiles_lock, seq)); 1983 1984 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) { 1985 if (!(all_avail & btrfs_raid_array[i].bg_flag)) 1986 continue; 1987 1988 if (num_devices < btrfs_raid_array[i].devs_min) 1989 return btrfs_raid_array[i].mindev_error; 1990 } 1991 1992 return 0; 1993 } 1994 1995 static struct btrfs_device * btrfs_find_next_active_device( 1996 struct btrfs_fs_devices *fs_devs, struct btrfs_device *device) 1997 { 1998 struct btrfs_device *next_device; 1999 2000 list_for_each_entry(next_device, &fs_devs->devices, dev_list) { 2001 if (next_device != device && 2002 !test_bit(BTRFS_DEV_STATE_MISSING, &next_device->dev_state) 2003 && next_device->bdev) 2004 return next_device; 2005 } 2006 2007 return NULL; 2008 } 2009 2010 /* 2011 * Helper function to check if the given device is part of s_bdev / latest_dev 2012 * and replace it with the provided or the next active device, in the context 2013 * where this function called, there should be always be another device (or 2014 * this_dev) which is active. 2015 */ 2016 void __cold btrfs_assign_next_active_device(struct btrfs_device *device, 2017 struct btrfs_device *next_device) 2018 { 2019 struct btrfs_fs_info *fs_info = device->fs_info; 2020 2021 if (!next_device) 2022 next_device = btrfs_find_next_active_device(fs_info->fs_devices, 2023 device); 2024 ASSERT(next_device); 2025 2026 if (fs_info->sb->s_bdev && 2027 (fs_info->sb->s_bdev == device->bdev)) 2028 fs_info->sb->s_bdev = next_device->bdev; 2029 2030 if (fs_info->fs_devices->latest_dev->bdev == device->bdev) 2031 fs_info->fs_devices->latest_dev = next_device; 2032 } 2033 2034 /* 2035 * Return btrfs_fs_devices::num_devices excluding the device that's being 2036 * currently replaced. 2037 */ 2038 static u64 btrfs_num_devices(struct btrfs_fs_info *fs_info) 2039 { 2040 u64 num_devices = fs_info->fs_devices->num_devices; 2041 2042 down_read(&fs_info->dev_replace.rwsem); 2043 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace)) { 2044 ASSERT(num_devices > 1); 2045 num_devices--; 2046 } 2047 up_read(&fs_info->dev_replace.rwsem); 2048 2049 return num_devices; 2050 } 2051 2052 static void btrfs_scratch_superblock(struct btrfs_fs_info *fs_info, 2053 struct block_device *bdev, int copy_num) 2054 { 2055 struct btrfs_super_block *disk_super; 2056 const size_t len = sizeof(disk_super->magic); 2057 const u64 bytenr = btrfs_sb_offset(copy_num); 2058 int ret; 2059 2060 disk_super = btrfs_read_disk_super(bdev, bytenr, bytenr); 2061 if (IS_ERR(disk_super)) 2062 return; 2063 2064 memset(&disk_super->magic, 0, len); 2065 folio_mark_dirty(virt_to_folio(disk_super)); 2066 btrfs_release_disk_super(disk_super); 2067 2068 ret = sync_blockdev_range(bdev, bytenr, bytenr + len - 1); 2069 if (ret) 2070 btrfs_warn(fs_info, "error clearing superblock number %d (%d)", 2071 copy_num, ret); 2072 } 2073 2074 void btrfs_scratch_superblocks(struct btrfs_fs_info *fs_info, 2075 struct block_device *bdev, 2076 const char *device_path) 2077 { 2078 int copy_num; 2079 2080 if (!bdev) 2081 return; 2082 2083 for (copy_num = 0; copy_num < BTRFS_SUPER_MIRROR_MAX; copy_num++) { 2084 if (bdev_is_zoned(bdev)) 2085 btrfs_reset_sb_log_zones(bdev, copy_num); 2086 else 2087 btrfs_scratch_superblock(fs_info, bdev, copy_num); 2088 } 2089 2090 /* Notify udev that device has changed */ 2091 btrfs_kobject_uevent(bdev, KOBJ_CHANGE); 2092 2093 /* Update ctime/mtime for device path for libblkid */ 2094 update_dev_time(device_path); 2095 } 2096 2097 int btrfs_rm_device(struct btrfs_fs_info *fs_info, 2098 struct btrfs_dev_lookup_args *args, 2099 struct block_device **bdev, void **holder) 2100 { 2101 struct btrfs_trans_handle *trans; 2102 struct btrfs_device *device; 2103 struct btrfs_fs_devices *cur_devices; 2104 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices; 2105 u64 num_devices; 2106 int ret = 0; 2107 2108 if (btrfs_fs_incompat(fs_info, EXTENT_TREE_V2)) { 2109 btrfs_err(fs_info, "device remove not supported on extent tree v2 yet"); 2110 return -EINVAL; 2111 } 2112 2113 /* 2114 * The device list in fs_devices is accessed without locks (neither 2115 * uuid_mutex nor device_list_mutex) as it won't change on a mounted 2116 * filesystem and another device rm cannot run. 2117 */ 2118 num_devices = btrfs_num_devices(fs_info); 2119 2120 ret = btrfs_check_raid_min_devices(fs_info, num_devices - 1); 2121 if (ret) 2122 return ret; 2123 2124 device = btrfs_find_device(fs_info->fs_devices, args); 2125 if (!device) { 2126 if (args->missing) 2127 ret = BTRFS_ERROR_DEV_MISSING_NOT_FOUND; 2128 else 2129 ret = -ENOENT; 2130 return ret; 2131 } 2132 2133 if (btrfs_pinned_by_swapfile(fs_info, device)) { 2134 btrfs_warn_in_rcu(fs_info, 2135 "cannot remove device %s (devid %llu) due to active swapfile", 2136 btrfs_dev_name(device), device->devid); 2137 return -ETXTBSY; 2138 } 2139 2140 if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) 2141 return BTRFS_ERROR_DEV_TGT_REPLACE; 2142 2143 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) && 2144 fs_info->fs_devices->rw_devices == 1) 2145 return BTRFS_ERROR_DEV_ONLY_WRITABLE; 2146 2147 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) { 2148 mutex_lock(&fs_info->chunk_mutex); 2149 list_del_init(&device->dev_alloc_list); 2150 device->fs_devices->rw_devices--; 2151 mutex_unlock(&fs_info->chunk_mutex); 2152 } 2153 2154 ret = btrfs_shrink_device(device, 0); 2155 if (ret) 2156 goto error_undo; 2157 2158 trans = btrfs_start_transaction(fs_info->chunk_root, 0); 2159 if (IS_ERR(trans)) { 2160 ret = PTR_ERR(trans); 2161 goto error_undo; 2162 } 2163 2164 ret = btrfs_rm_dev_item(trans, device); 2165 if (ret) { 2166 /* Any error in dev item removal is critical */ 2167 btrfs_crit(fs_info, 2168 "failed to remove device item for devid %llu: %d", 2169 device->devid, ret); 2170 btrfs_abort_transaction(trans, ret); 2171 btrfs_end_transaction(trans); 2172 return ret; 2173 } 2174 2175 clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state); 2176 btrfs_scrub_cancel_dev(device); 2177 2178 /* 2179 * the device list mutex makes sure that we don't change 2180 * the device list while someone else is writing out all 2181 * the device supers. Whoever is writing all supers, should 2182 * lock the device list mutex before getting the number of 2183 * devices in the super block (super_copy). Conversely, 2184 * whoever updates the number of devices in the super block 2185 * (super_copy) should hold the device list mutex. 2186 */ 2187 2188 /* 2189 * In normal cases the cur_devices == fs_devices. But in case 2190 * of deleting a seed device, the cur_devices should point to 2191 * its own fs_devices listed under the fs_devices->seed_list. 2192 */ 2193 cur_devices = device->fs_devices; 2194 mutex_lock(&fs_devices->device_list_mutex); 2195 list_del_rcu(&device->dev_list); 2196 2197 cur_devices->num_devices--; 2198 cur_devices->total_devices--; 2199 /* Update total_devices of the parent fs_devices if it's seed */ 2200 if (cur_devices != fs_devices) 2201 fs_devices->total_devices--; 2202 2203 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) 2204 cur_devices->missing_devices--; 2205 2206 btrfs_assign_next_active_device(device, NULL); 2207 2208 if (device->bdev) { 2209 cur_devices->open_devices--; 2210 /* remove sysfs entry */ 2211 btrfs_sysfs_remove_device(device); 2212 } 2213 2214 num_devices = btrfs_super_num_devices(fs_info->super_copy) - 1; 2215 btrfs_set_super_num_devices(fs_info->super_copy, num_devices); 2216 mutex_unlock(&fs_devices->device_list_mutex); 2217 2218 /* 2219 * At this point, the device is zero sized and detached from the 2220 * devices list. All that's left is to zero out the old supers and 2221 * free the device. 2222 * 2223 * We cannot call btrfs_close_bdev() here because we're holding the sb 2224 * write lock, and blkdev_put() will pull in the ->open_mutex on the 2225 * block device and it's dependencies. Instead just flush the device 2226 * and let the caller do the final blkdev_put. 2227 */ 2228 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) { 2229 btrfs_scratch_superblocks(fs_info, device->bdev, 2230 device->name->str); 2231 if (device->bdev) { 2232 sync_blockdev(device->bdev); 2233 invalidate_bdev(device->bdev); 2234 } 2235 } 2236 2237 *bdev = device->bdev; 2238 *holder = device->holder; 2239 synchronize_rcu(); 2240 btrfs_free_device(device); 2241 2242 /* 2243 * This can happen if cur_devices is the private seed devices list. We 2244 * cannot call close_fs_devices() here because it expects the uuid_mutex 2245 * to be held, but in fact we don't need that for the private 2246 * seed_devices, we can simply decrement cur_devices->opened and then 2247 * remove it from our list and free the fs_devices. 2248 */ 2249 if (cur_devices->num_devices == 0) { 2250 list_del_init(&cur_devices->seed_list); 2251 ASSERT(cur_devices->opened == 1); 2252 cur_devices->opened--; 2253 free_fs_devices(cur_devices); 2254 } 2255 2256 ret = btrfs_commit_transaction(trans); 2257 2258 return ret; 2259 2260 error_undo: 2261 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) { 2262 mutex_lock(&fs_info->chunk_mutex); 2263 list_add(&device->dev_alloc_list, 2264 &fs_devices->alloc_list); 2265 device->fs_devices->rw_devices++; 2266 mutex_unlock(&fs_info->chunk_mutex); 2267 } 2268 return ret; 2269 } 2270 2271 void btrfs_rm_dev_replace_remove_srcdev(struct btrfs_device *srcdev) 2272 { 2273 struct btrfs_fs_devices *fs_devices; 2274 2275 lockdep_assert_held(&srcdev->fs_info->fs_devices->device_list_mutex); 2276 2277 /* 2278 * in case of fs with no seed, srcdev->fs_devices will point 2279 * to fs_devices of fs_info. However when the dev being replaced is 2280 * a seed dev it will point to the seed's local fs_devices. In short 2281 * srcdev will have its correct fs_devices in both the cases. 2282 */ 2283 fs_devices = srcdev->fs_devices; 2284 2285 list_del_rcu(&srcdev->dev_list); 2286 list_del(&srcdev->dev_alloc_list); 2287 fs_devices->num_devices--; 2288 if (test_bit(BTRFS_DEV_STATE_MISSING, &srcdev->dev_state)) 2289 fs_devices->missing_devices--; 2290 2291 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &srcdev->dev_state)) 2292 fs_devices->rw_devices--; 2293 2294 if (srcdev->bdev) 2295 fs_devices->open_devices--; 2296 } 2297 2298 void btrfs_rm_dev_replace_free_srcdev(struct btrfs_device *srcdev) 2299 { 2300 struct btrfs_fs_devices *fs_devices = srcdev->fs_devices; 2301 2302 mutex_lock(&uuid_mutex); 2303 2304 btrfs_close_bdev(srcdev); 2305 synchronize_rcu(); 2306 btrfs_free_device(srcdev); 2307 2308 /* if this is no devs we rather delete the fs_devices */ 2309 if (!fs_devices->num_devices) { 2310 /* 2311 * On a mounted FS, num_devices can't be zero unless it's a 2312 * seed. In case of a seed device being replaced, the replace 2313 * target added to the sprout FS, so there will be no more 2314 * device left under the seed FS. 2315 */ 2316 ASSERT(fs_devices->seeding); 2317 2318 list_del_init(&fs_devices->seed_list); 2319 close_fs_devices(fs_devices); 2320 free_fs_devices(fs_devices); 2321 } 2322 mutex_unlock(&uuid_mutex); 2323 } 2324 2325 void btrfs_destroy_dev_replace_tgtdev(struct btrfs_device *tgtdev) 2326 { 2327 struct btrfs_fs_devices *fs_devices = tgtdev->fs_info->fs_devices; 2328 2329 mutex_lock(&fs_devices->device_list_mutex); 2330 2331 btrfs_sysfs_remove_device(tgtdev); 2332 2333 if (tgtdev->bdev) 2334 fs_devices->open_devices--; 2335 2336 fs_devices->num_devices--; 2337 2338 btrfs_assign_next_active_device(tgtdev, NULL); 2339 2340 list_del_rcu(&tgtdev->dev_list); 2341 2342 mutex_unlock(&fs_devices->device_list_mutex); 2343 2344 btrfs_scratch_superblocks(tgtdev->fs_info, tgtdev->bdev, 2345 tgtdev->name->str); 2346 2347 btrfs_close_bdev(tgtdev); 2348 synchronize_rcu(); 2349 btrfs_free_device(tgtdev); 2350 } 2351 2352 /* 2353 * Populate args from device at path. 2354 * 2355 * @fs_info: the filesystem 2356 * @args: the args to populate 2357 * @path: the path to the device 2358 * 2359 * This will read the super block of the device at @path and populate @args with 2360 * the devid, fsid, and uuid. This is meant to be used for ioctls that need to 2361 * lookup a device to operate on, but need to do it before we take any locks. 2362 * This properly handles the special case of "missing" that a user may pass in, 2363 * and does some basic sanity checks. The caller must make sure that @path is 2364 * properly NUL terminated before calling in, and must call 2365 * btrfs_put_dev_args_from_path() in order to free up the temporary fsid and 2366 * uuid buffers. 2367 * 2368 * Return: 0 for success, -errno for failure 2369 */ 2370 int btrfs_get_dev_args_from_path(struct btrfs_fs_info *fs_info, 2371 struct btrfs_dev_lookup_args *args, 2372 const char *path) 2373 { 2374 struct btrfs_super_block *disk_super; 2375 struct block_device *bdev; 2376 int ret; 2377 2378 if (!path || !path[0]) 2379 return -EINVAL; 2380 if (!strcmp(path, "missing")) { 2381 args->missing = true; 2382 return 0; 2383 } 2384 2385 args->uuid = kzalloc(BTRFS_UUID_SIZE, GFP_KERNEL); 2386 args->fsid = kzalloc(BTRFS_FSID_SIZE, GFP_KERNEL); 2387 if (!args->uuid || !args->fsid) { 2388 btrfs_put_dev_args_from_path(args); 2389 return -ENOMEM; 2390 } 2391 2392 ret = btrfs_get_bdev_and_sb(path, BLK_OPEN_READ, NULL, 0, 2393 &bdev, &disk_super); 2394 if (ret) { 2395 btrfs_put_dev_args_from_path(args); 2396 return ret; 2397 } 2398 2399 args->devid = btrfs_stack_device_id(&disk_super->dev_item); 2400 memcpy(args->uuid, disk_super->dev_item.uuid, BTRFS_UUID_SIZE); 2401 if (btrfs_fs_incompat(fs_info, METADATA_UUID)) 2402 memcpy(args->fsid, disk_super->metadata_uuid, BTRFS_FSID_SIZE); 2403 else 2404 memcpy(args->fsid, disk_super->fsid, BTRFS_FSID_SIZE); 2405 btrfs_release_disk_super(disk_super); 2406 blkdev_put(bdev, NULL); 2407 return 0; 2408 } 2409 2410 /* 2411 * Only use this jointly with btrfs_get_dev_args_from_path() because we will 2412 * allocate our ->uuid and ->fsid pointers, everybody else uses local variables 2413 * that don't need to be freed. 2414 */ 2415 void btrfs_put_dev_args_from_path(struct btrfs_dev_lookup_args *args) 2416 { 2417 kfree(args->uuid); 2418 kfree(args->fsid); 2419 args->uuid = NULL; 2420 args->fsid = NULL; 2421 } 2422 2423 struct btrfs_device *btrfs_find_device_by_devspec( 2424 struct btrfs_fs_info *fs_info, u64 devid, 2425 const char *device_path) 2426 { 2427 BTRFS_DEV_LOOKUP_ARGS(args); 2428 struct btrfs_device *device; 2429 int ret; 2430 2431 if (devid) { 2432 args.devid = devid; 2433 device = btrfs_find_device(fs_info->fs_devices, &args); 2434 if (!device) 2435 return ERR_PTR(-ENOENT); 2436 return device; 2437 } 2438 2439 ret = btrfs_get_dev_args_from_path(fs_info, &args, device_path); 2440 if (ret) 2441 return ERR_PTR(ret); 2442 device = btrfs_find_device(fs_info->fs_devices, &args); 2443 btrfs_put_dev_args_from_path(&args); 2444 if (!device) 2445 return ERR_PTR(-ENOENT); 2446 return device; 2447 } 2448 2449 static struct btrfs_fs_devices *btrfs_init_sprout(struct btrfs_fs_info *fs_info) 2450 { 2451 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices; 2452 struct btrfs_fs_devices *old_devices; 2453 struct btrfs_fs_devices *seed_devices; 2454 2455 lockdep_assert_held(&uuid_mutex); 2456 if (!fs_devices->seeding) 2457 return ERR_PTR(-EINVAL); 2458 2459 /* 2460 * Private copy of the seed devices, anchored at 2461 * fs_info->fs_devices->seed_list 2462 */ 2463 seed_devices = alloc_fs_devices(NULL, NULL); 2464 if (IS_ERR(seed_devices)) 2465 return seed_devices; 2466 2467 /* 2468 * It's necessary to retain a copy of the original seed fs_devices in 2469 * fs_uuids so that filesystems which have been seeded can successfully 2470 * reference the seed device from open_seed_devices. This also supports 2471 * multiple fs seed. 2472 */ 2473 old_devices = clone_fs_devices(fs_devices); 2474 if (IS_ERR(old_devices)) { 2475 kfree(seed_devices); 2476 return old_devices; 2477 } 2478 2479 list_add(&old_devices->fs_list, &fs_uuids); 2480 2481 memcpy(seed_devices, fs_devices, sizeof(*seed_devices)); 2482 seed_devices->opened = 1; 2483 INIT_LIST_HEAD(&seed_devices->devices); 2484 INIT_LIST_HEAD(&seed_devices->alloc_list); 2485 mutex_init(&seed_devices->device_list_mutex); 2486 2487 return seed_devices; 2488 } 2489 2490 /* 2491 * Splice seed devices into the sprout fs_devices. 2492 * Generate a new fsid for the sprouted read-write filesystem. 2493 */ 2494 static void btrfs_setup_sprout(struct btrfs_fs_info *fs_info, 2495 struct btrfs_fs_devices *seed_devices) 2496 { 2497 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices; 2498 struct btrfs_super_block *disk_super = fs_info->super_copy; 2499 struct btrfs_device *device; 2500 u64 super_flags; 2501 2502 /* 2503 * We are updating the fsid, the thread leading to device_list_add() 2504 * could race, so uuid_mutex is needed. 2505 */ 2506 lockdep_assert_held(&uuid_mutex); 2507 2508 /* 2509 * The threads listed below may traverse dev_list but can do that without 2510 * device_list_mutex: 2511 * - All device ops and balance - as we are in btrfs_exclop_start. 2512 * - Various dev_list readers - are using RCU. 2513 * - btrfs_ioctl_fitrim() - is using RCU. 2514 * 2515 * For-read threads as below are using device_list_mutex: 2516 * - Readonly scrub btrfs_scrub_dev() 2517 * - Readonly scrub btrfs_scrub_progress() 2518 * - btrfs_get_dev_stats() 2519 */ 2520 lockdep_assert_held(&fs_devices->device_list_mutex); 2521 2522 list_splice_init_rcu(&fs_devices->devices, &seed_devices->devices, 2523 synchronize_rcu); 2524 list_for_each_entry(device, &seed_devices->devices, dev_list) 2525 device->fs_devices = seed_devices; 2526 2527 fs_devices->seeding = false; 2528 fs_devices->num_devices = 0; 2529 fs_devices->open_devices = 0; 2530 fs_devices->missing_devices = 0; 2531 fs_devices->rotating = false; 2532 list_add(&seed_devices->seed_list, &fs_devices->seed_list); 2533 2534 generate_random_uuid(fs_devices->fsid); 2535 memcpy(fs_devices->metadata_uuid, fs_devices->fsid, BTRFS_FSID_SIZE); 2536 memcpy(disk_super->fsid, fs_devices->fsid, BTRFS_FSID_SIZE); 2537 2538 super_flags = btrfs_super_flags(disk_super) & 2539 ~BTRFS_SUPER_FLAG_SEEDING; 2540 btrfs_set_super_flags(disk_super, super_flags); 2541 } 2542 2543 /* 2544 * Store the expected generation for seed devices in device items. 2545 */ 2546 static int btrfs_finish_sprout(struct btrfs_trans_handle *trans) 2547 { 2548 BTRFS_DEV_LOOKUP_ARGS(args); 2549 struct btrfs_fs_info *fs_info = trans->fs_info; 2550 struct btrfs_root *root = fs_info->chunk_root; 2551 struct btrfs_path *path; 2552 struct extent_buffer *leaf; 2553 struct btrfs_dev_item *dev_item; 2554 struct btrfs_device *device; 2555 struct btrfs_key key; 2556 u8 fs_uuid[BTRFS_FSID_SIZE]; 2557 u8 dev_uuid[BTRFS_UUID_SIZE]; 2558 int ret; 2559 2560 path = btrfs_alloc_path(); 2561 if (!path) 2562 return -ENOMEM; 2563 2564 key.objectid = BTRFS_DEV_ITEMS_OBJECTID; 2565 key.offset = 0; 2566 key.type = BTRFS_DEV_ITEM_KEY; 2567 2568 while (1) { 2569 btrfs_reserve_chunk_metadata(trans, false); 2570 ret = btrfs_search_slot(trans, root, &key, path, 0, 1); 2571 btrfs_trans_release_chunk_metadata(trans); 2572 if (ret < 0) 2573 goto error; 2574 2575 leaf = path->nodes[0]; 2576 next_slot: 2577 if (path->slots[0] >= btrfs_header_nritems(leaf)) { 2578 ret = btrfs_next_leaf(root, path); 2579 if (ret > 0) 2580 break; 2581 if (ret < 0) 2582 goto error; 2583 leaf = path->nodes[0]; 2584 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]); 2585 btrfs_release_path(path); 2586 continue; 2587 } 2588 2589 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]); 2590 if (key.objectid != BTRFS_DEV_ITEMS_OBJECTID || 2591 key.type != BTRFS_DEV_ITEM_KEY) 2592 break; 2593 2594 dev_item = btrfs_item_ptr(leaf, path->slots[0], 2595 struct btrfs_dev_item); 2596 args.devid = btrfs_device_id(leaf, dev_item); 2597 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item), 2598 BTRFS_UUID_SIZE); 2599 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item), 2600 BTRFS_FSID_SIZE); 2601 args.uuid = dev_uuid; 2602 args.fsid = fs_uuid; 2603 device = btrfs_find_device(fs_info->fs_devices, &args); 2604 BUG_ON(!device); /* Logic error */ 2605 2606 if (device->fs_devices->seeding) { 2607 btrfs_set_device_generation(leaf, dev_item, 2608 device->generation); 2609 btrfs_mark_buffer_dirty(leaf); 2610 } 2611 2612 path->slots[0]++; 2613 goto next_slot; 2614 } 2615 ret = 0; 2616 error: 2617 btrfs_free_path(path); 2618 return ret; 2619 } 2620 2621 int btrfs_init_new_device(struct btrfs_fs_info *fs_info, const char *device_path) 2622 { 2623 struct btrfs_root *root = fs_info->dev_root; 2624 struct btrfs_trans_handle *trans; 2625 struct btrfs_device *device; 2626 struct block_device *bdev; 2627 struct super_block *sb = fs_info->sb; 2628 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices; 2629 struct btrfs_fs_devices *seed_devices = NULL; 2630 u64 orig_super_total_bytes; 2631 u64 orig_super_num_devices; 2632 int ret = 0; 2633 bool seeding_dev = false; 2634 bool locked = false; 2635 2636 if (sb_rdonly(sb) && !fs_devices->seeding) 2637 return -EROFS; 2638 2639 bdev = blkdev_get_by_path(device_path, BLK_OPEN_WRITE, 2640 fs_info->bdev_holder, NULL); 2641 if (IS_ERR(bdev)) 2642 return PTR_ERR(bdev); 2643 2644 if (!btrfs_check_device_zone_type(fs_info, bdev)) { 2645 ret = -EINVAL; 2646 goto error; 2647 } 2648 2649 if (fs_devices->seeding) { 2650 seeding_dev = true; 2651 down_write(&sb->s_umount); 2652 mutex_lock(&uuid_mutex); 2653 locked = true; 2654 } 2655 2656 sync_blockdev(bdev); 2657 2658 rcu_read_lock(); 2659 list_for_each_entry_rcu(device, &fs_devices->devices, dev_list) { 2660 if (device->bdev == bdev) { 2661 ret = -EEXIST; 2662 rcu_read_unlock(); 2663 goto error; 2664 } 2665 } 2666 rcu_read_unlock(); 2667 2668 device = btrfs_alloc_device(fs_info, NULL, NULL, device_path); 2669 if (IS_ERR(device)) { 2670 /* we can safely leave the fs_devices entry around */ 2671 ret = PTR_ERR(device); 2672 goto error; 2673 } 2674 2675 device->fs_info = fs_info; 2676 device->bdev = bdev; 2677 ret = lookup_bdev(device_path, &device->devt); 2678 if (ret) 2679 goto error_free_device; 2680 2681 ret = btrfs_get_dev_zone_info(device, false); 2682 if (ret) 2683 goto error_free_device; 2684 2685 trans = btrfs_start_transaction(root, 0); 2686 if (IS_ERR(trans)) { 2687 ret = PTR_ERR(trans); 2688 goto error_free_zone; 2689 } 2690 2691 set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state); 2692 device->generation = trans->transid; 2693 device->io_width = fs_info->sectorsize; 2694 device->io_align = fs_info->sectorsize; 2695 device->sector_size = fs_info->sectorsize; 2696 device->total_bytes = 2697 round_down(bdev_nr_bytes(bdev), fs_info->sectorsize); 2698 device->disk_total_bytes = device->total_bytes; 2699 device->commit_total_bytes = device->total_bytes; 2700 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state); 2701 clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state); 2702 device->holder = fs_info->bdev_holder; 2703 device->dev_stats_valid = 1; 2704 set_blocksize(device->bdev, BTRFS_BDEV_BLOCKSIZE); 2705 2706 if (seeding_dev) { 2707 btrfs_clear_sb_rdonly(sb); 2708 2709 /* GFP_KERNEL allocation must not be under device_list_mutex */ 2710 seed_devices = btrfs_init_sprout(fs_info); 2711 if (IS_ERR(seed_devices)) { 2712 ret = PTR_ERR(seed_devices); 2713 btrfs_abort_transaction(trans, ret); 2714 goto error_trans; 2715 } 2716 } 2717 2718 mutex_lock(&fs_devices->device_list_mutex); 2719 if (seeding_dev) { 2720 btrfs_setup_sprout(fs_info, seed_devices); 2721 btrfs_assign_next_active_device(fs_info->fs_devices->latest_dev, 2722 device); 2723 } 2724 2725 device->fs_devices = fs_devices; 2726 2727 mutex_lock(&fs_info->chunk_mutex); 2728 list_add_rcu(&device->dev_list, &fs_devices->devices); 2729 list_add(&device->dev_alloc_list, &fs_devices->alloc_list); 2730 fs_devices->num_devices++; 2731 fs_devices->open_devices++; 2732 fs_devices->rw_devices++; 2733 fs_devices->total_devices++; 2734 fs_devices->total_rw_bytes += device->total_bytes; 2735 2736 atomic64_add(device->total_bytes, &fs_info->free_chunk_space); 2737 2738 if (!bdev_nonrot(bdev)) 2739 fs_devices->rotating = true; 2740 2741 orig_super_total_bytes = btrfs_super_total_bytes(fs_info->super_copy); 2742 btrfs_set_super_total_bytes(fs_info->super_copy, 2743 round_down(orig_super_total_bytes + device->total_bytes, 2744 fs_info->sectorsize)); 2745 2746 orig_super_num_devices = btrfs_super_num_devices(fs_info->super_copy); 2747 btrfs_set_super_num_devices(fs_info->super_copy, 2748 orig_super_num_devices + 1); 2749 2750 /* 2751 * we've got more storage, clear any full flags on the space 2752 * infos 2753 */ 2754 btrfs_clear_space_info_full(fs_info); 2755 2756 mutex_unlock(&fs_info->chunk_mutex); 2757 2758 /* Add sysfs device entry */ 2759 btrfs_sysfs_add_device(device); 2760 2761 mutex_unlock(&fs_devices->device_list_mutex); 2762 2763 if (seeding_dev) { 2764 mutex_lock(&fs_info->chunk_mutex); 2765 ret = init_first_rw_device(trans); 2766 mutex_unlock(&fs_info->chunk_mutex); 2767 if (ret) { 2768 btrfs_abort_transaction(trans, ret); 2769 goto error_sysfs; 2770 } 2771 } 2772 2773 ret = btrfs_add_dev_item(trans, device); 2774 if (ret) { 2775 btrfs_abort_transaction(trans, ret); 2776 goto error_sysfs; 2777 } 2778 2779 if (seeding_dev) { 2780 ret = btrfs_finish_sprout(trans); 2781 if (ret) { 2782 btrfs_abort_transaction(trans, ret); 2783 goto error_sysfs; 2784 } 2785 2786 /* 2787 * fs_devices now represents the newly sprouted filesystem and 2788 * its fsid has been changed by btrfs_sprout_splice(). 2789 */ 2790 btrfs_sysfs_update_sprout_fsid(fs_devices); 2791 } 2792 2793 ret = btrfs_commit_transaction(trans); 2794 2795 if (seeding_dev) { 2796 mutex_unlock(&uuid_mutex); 2797 up_write(&sb->s_umount); 2798 locked = false; 2799 2800 if (ret) /* transaction commit */ 2801 return ret; 2802 2803 ret = btrfs_relocate_sys_chunks(fs_info); 2804 if (ret < 0) 2805 btrfs_handle_fs_error(fs_info, ret, 2806 "Failed to relocate sys chunks after device initialization. This can be fixed using the \"btrfs balance\" command."); 2807 trans = btrfs_attach_transaction(root); 2808 if (IS_ERR(trans)) { 2809 if (PTR_ERR(trans) == -ENOENT) 2810 return 0; 2811 ret = PTR_ERR(trans); 2812 trans = NULL; 2813 goto error_sysfs; 2814 } 2815 ret = btrfs_commit_transaction(trans); 2816 } 2817 2818 /* 2819 * Now that we have written a new super block to this device, check all 2820 * other fs_devices list if device_path alienates any other scanned 2821 * device. 2822 * We can ignore the return value as it typically returns -EINVAL and 2823 * only succeeds if the device was an alien. 2824 */ 2825 btrfs_forget_devices(device->devt); 2826 2827 /* Update ctime/mtime for blkid or udev */ 2828 update_dev_time(device_path); 2829 2830 return ret; 2831 2832 error_sysfs: 2833 btrfs_sysfs_remove_device(device); 2834 mutex_lock(&fs_info->fs_devices->device_list_mutex); 2835 mutex_lock(&fs_info->chunk_mutex); 2836 list_del_rcu(&device->dev_list); 2837 list_del(&device->dev_alloc_list); 2838 fs_info->fs_devices->num_devices--; 2839 fs_info->fs_devices->open_devices--; 2840 fs_info->fs_devices->rw_devices--; 2841 fs_info->fs_devices->total_devices--; 2842 fs_info->fs_devices->total_rw_bytes -= device->total_bytes; 2843 atomic64_sub(device->total_bytes, &fs_info->free_chunk_space); 2844 btrfs_set_super_total_bytes(fs_info->super_copy, 2845 orig_super_total_bytes); 2846 btrfs_set_super_num_devices(fs_info->super_copy, 2847 orig_super_num_devices); 2848 mutex_unlock(&fs_info->chunk_mutex); 2849 mutex_unlock(&fs_info->fs_devices->device_list_mutex); 2850 error_trans: 2851 if (seeding_dev) 2852 btrfs_set_sb_rdonly(sb); 2853 if (trans) 2854 btrfs_end_transaction(trans); 2855 error_free_zone: 2856 btrfs_destroy_dev_zone_info(device); 2857 error_free_device: 2858 btrfs_free_device(device); 2859 error: 2860 blkdev_put(bdev, fs_info->bdev_holder); 2861 if (locked) { 2862 mutex_unlock(&uuid_mutex); 2863 up_write(&sb->s_umount); 2864 } 2865 return ret; 2866 } 2867 2868 static noinline int btrfs_update_device(struct btrfs_trans_handle *trans, 2869 struct btrfs_device *device) 2870 { 2871 int ret; 2872 struct btrfs_path *path; 2873 struct btrfs_root *root = device->fs_info->chunk_root; 2874 struct btrfs_dev_item *dev_item; 2875 struct extent_buffer *leaf; 2876 struct btrfs_key key; 2877 2878 path = btrfs_alloc_path(); 2879 if (!path) 2880 return -ENOMEM; 2881 2882 key.objectid = BTRFS_DEV_ITEMS_OBJECTID; 2883 key.type = BTRFS_DEV_ITEM_KEY; 2884 key.offset = device->devid; 2885 2886 ret = btrfs_search_slot(trans, root, &key, path, 0, 1); 2887 if (ret < 0) 2888 goto out; 2889 2890 if (ret > 0) { 2891 ret = -ENOENT; 2892 goto out; 2893 } 2894 2895 leaf = path->nodes[0]; 2896 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item); 2897 2898 btrfs_set_device_id(leaf, dev_item, device->devid); 2899 btrfs_set_device_type(leaf, dev_item, device->type); 2900 btrfs_set_device_io_align(leaf, dev_item, device->io_align); 2901 btrfs_set_device_io_width(leaf, dev_item, device->io_width); 2902 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size); 2903 btrfs_set_device_total_bytes(leaf, dev_item, 2904 btrfs_device_get_disk_total_bytes(device)); 2905 btrfs_set_device_bytes_used(leaf, dev_item, 2906 btrfs_device_get_bytes_used(device)); 2907 btrfs_mark_buffer_dirty(leaf); 2908 2909 out: 2910 btrfs_free_path(path); 2911 return ret; 2912 } 2913 2914 int btrfs_grow_device(struct btrfs_trans_handle *trans, 2915 struct btrfs_device *device, u64 new_size) 2916 { 2917 struct btrfs_fs_info *fs_info = device->fs_info; 2918 struct btrfs_super_block *super_copy = fs_info->super_copy; 2919 u64 old_total; 2920 u64 diff; 2921 int ret; 2922 2923 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) 2924 return -EACCES; 2925 2926 new_size = round_down(new_size, fs_info->sectorsize); 2927 2928 mutex_lock(&fs_info->chunk_mutex); 2929 old_total = btrfs_super_total_bytes(super_copy); 2930 diff = round_down(new_size - device->total_bytes, fs_info->sectorsize); 2931 2932 if (new_size <= device->total_bytes || 2933 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) { 2934 mutex_unlock(&fs_info->chunk_mutex); 2935 return -EINVAL; 2936 } 2937 2938 btrfs_set_super_total_bytes(super_copy, 2939 round_down(old_total + diff, fs_info->sectorsize)); 2940 device->fs_devices->total_rw_bytes += diff; 2941 2942 btrfs_device_set_total_bytes(device, new_size); 2943 btrfs_device_set_disk_total_bytes(device, new_size); 2944 btrfs_clear_space_info_full(device->fs_info); 2945 if (list_empty(&device->post_commit_list)) 2946 list_add_tail(&device->post_commit_list, 2947 &trans->transaction->dev_update_list); 2948 mutex_unlock(&fs_info->chunk_mutex); 2949 2950 btrfs_reserve_chunk_metadata(trans, false); 2951 ret = btrfs_update_device(trans, device); 2952 btrfs_trans_release_chunk_metadata(trans); 2953 2954 return ret; 2955 } 2956 2957 static int btrfs_free_chunk(struct btrfs_trans_handle *trans, u64 chunk_offset) 2958 { 2959 struct btrfs_fs_info *fs_info = trans->fs_info; 2960 struct btrfs_root *root = fs_info->chunk_root; 2961 int ret; 2962 struct btrfs_path *path; 2963 struct btrfs_key key; 2964 2965 path = btrfs_alloc_path(); 2966 if (!path) 2967 return -ENOMEM; 2968 2969 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID; 2970 key.offset = chunk_offset; 2971 key.type = BTRFS_CHUNK_ITEM_KEY; 2972 2973 ret = btrfs_search_slot(trans, root, &key, path, -1, 1); 2974 if (ret < 0) 2975 goto out; 2976 else if (ret > 0) { /* Logic error or corruption */ 2977 btrfs_handle_fs_error(fs_info, -ENOENT, 2978 "Failed lookup while freeing chunk."); 2979 ret = -ENOENT; 2980 goto out; 2981 } 2982 2983 ret = btrfs_del_item(trans, root, path); 2984 if (ret < 0) 2985 btrfs_handle_fs_error(fs_info, ret, 2986 "Failed to delete chunk item."); 2987 out: 2988 btrfs_free_path(path); 2989 return ret; 2990 } 2991 2992 static int btrfs_del_sys_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset) 2993 { 2994 struct btrfs_super_block *super_copy = fs_info->super_copy; 2995 struct btrfs_disk_key *disk_key; 2996 struct btrfs_chunk *chunk; 2997 u8 *ptr; 2998 int ret = 0; 2999 u32 num_stripes; 3000 u32 array_size; 3001 u32 len = 0; 3002 u32 cur; 3003 struct btrfs_key key; 3004 3005 lockdep_assert_held(&fs_info->chunk_mutex); 3006 array_size = btrfs_super_sys_array_size(super_copy); 3007 3008 ptr = super_copy->sys_chunk_array; 3009 cur = 0; 3010 3011 while (cur < array_size) { 3012 disk_key = (struct btrfs_disk_key *)ptr; 3013 btrfs_disk_key_to_cpu(&key, disk_key); 3014 3015 len = sizeof(*disk_key); 3016 3017 if (key.type == BTRFS_CHUNK_ITEM_KEY) { 3018 chunk = (struct btrfs_chunk *)(ptr + len); 3019 num_stripes = btrfs_stack_chunk_num_stripes(chunk); 3020 len += btrfs_chunk_item_size(num_stripes); 3021 } else { 3022 ret = -EIO; 3023 break; 3024 } 3025 if (key.objectid == BTRFS_FIRST_CHUNK_TREE_OBJECTID && 3026 key.offset == chunk_offset) { 3027 memmove(ptr, ptr + len, array_size - (cur + len)); 3028 array_size -= len; 3029 btrfs_set_super_sys_array_size(super_copy, array_size); 3030 } else { 3031 ptr += len; 3032 cur += len; 3033 } 3034 } 3035 return ret; 3036 } 3037 3038 /* 3039 * btrfs_get_chunk_map() - Find the mapping containing the given logical extent. 3040 * @logical: Logical block offset in bytes. 3041 * @length: Length of extent in bytes. 3042 * 3043 * Return: Chunk mapping or ERR_PTR. 3044 */ 3045 struct extent_map *btrfs_get_chunk_map(struct btrfs_fs_info *fs_info, 3046 u64 logical, u64 length) 3047 { 3048 struct extent_map_tree *em_tree; 3049 struct extent_map *em; 3050 3051 em_tree = &fs_info->mapping_tree; 3052 read_lock(&em_tree->lock); 3053 em = lookup_extent_mapping(em_tree, logical, length); 3054 read_unlock(&em_tree->lock); 3055 3056 if (!em) { 3057 btrfs_crit(fs_info, "unable to find logical %llu length %llu", 3058 logical, length); 3059 return ERR_PTR(-EINVAL); 3060 } 3061 3062 if (em->start > logical || em->start + em->len < logical) { 3063 btrfs_crit(fs_info, 3064 "found a bad mapping, wanted %llu-%llu, found %llu-%llu", 3065 logical, length, em->start, em->start + em->len); 3066 free_extent_map(em); 3067 return ERR_PTR(-EINVAL); 3068 } 3069 3070 /* callers are responsible for dropping em's ref. */ 3071 return em; 3072 } 3073 3074 static int remove_chunk_item(struct btrfs_trans_handle *trans, 3075 struct map_lookup *map, u64 chunk_offset) 3076 { 3077 int i; 3078 3079 /* 3080 * Removing chunk items and updating the device items in the chunks btree 3081 * requires holding the chunk_mutex. 3082 * See the comment at btrfs_chunk_alloc() for the details. 3083 */ 3084 lockdep_assert_held(&trans->fs_info->chunk_mutex); 3085 3086 for (i = 0; i < map->num_stripes; i++) { 3087 int ret; 3088 3089 ret = btrfs_update_device(trans, map->stripes[i].dev); 3090 if (ret) 3091 return ret; 3092 } 3093 3094 return btrfs_free_chunk(trans, chunk_offset); 3095 } 3096 3097 int btrfs_remove_chunk(struct btrfs_trans_handle *trans, u64 chunk_offset) 3098 { 3099 struct btrfs_fs_info *fs_info = trans->fs_info; 3100 struct extent_map *em; 3101 struct map_lookup *map; 3102 u64 dev_extent_len = 0; 3103 int i, ret = 0; 3104 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices; 3105 3106 em = btrfs_get_chunk_map(fs_info, chunk_offset, 1); 3107 if (IS_ERR(em)) { 3108 /* 3109 * This is a logic error, but we don't want to just rely on the 3110 * user having built with ASSERT enabled, so if ASSERT doesn't 3111 * do anything we still error out. 3112 */ 3113 ASSERT(0); 3114 return PTR_ERR(em); 3115 } 3116 map = em->map_lookup; 3117 3118 /* 3119 * First delete the device extent items from the devices btree. 3120 * We take the device_list_mutex to avoid racing with the finishing phase 3121 * of a device replace operation. See the comment below before acquiring 3122 * fs_info->chunk_mutex. Note that here we do not acquire the chunk_mutex 3123 * because that can result in a deadlock when deleting the device extent 3124 * items from the devices btree - COWing an extent buffer from the btree 3125 * may result in allocating a new metadata chunk, which would attempt to 3126 * lock again fs_info->chunk_mutex. 3127 */ 3128 mutex_lock(&fs_devices->device_list_mutex); 3129 for (i = 0; i < map->num_stripes; i++) { 3130 struct btrfs_device *device = map->stripes[i].dev; 3131 ret = btrfs_free_dev_extent(trans, device, 3132 map->stripes[i].physical, 3133 &dev_extent_len); 3134 if (ret) { 3135 mutex_unlock(&fs_devices->device_list_mutex); 3136 btrfs_abort_transaction(trans, ret); 3137 goto out; 3138 } 3139 3140 if (device->bytes_used > 0) { 3141 mutex_lock(&fs_info->chunk_mutex); 3142 btrfs_device_set_bytes_used(device, 3143 device->bytes_used - dev_extent_len); 3144 atomic64_add(dev_extent_len, &fs_info->free_chunk_space); 3145 btrfs_clear_space_info_full(fs_info); 3146 mutex_unlock(&fs_info->chunk_mutex); 3147 } 3148 } 3149 mutex_unlock(&fs_devices->device_list_mutex); 3150 3151 /* 3152 * We acquire fs_info->chunk_mutex for 2 reasons: 3153 * 3154 * 1) Just like with the first phase of the chunk allocation, we must 3155 * reserve system space, do all chunk btree updates and deletions, and 3156 * update the system chunk array in the superblock while holding this 3157 * mutex. This is for similar reasons as explained on the comment at 3158 * the top of btrfs_chunk_alloc(); 3159 * 3160 * 2) Prevent races with the final phase of a device replace operation 3161 * that replaces the device object associated with the map's stripes, 3162 * because the device object's id can change at any time during that 3163 * final phase of the device replace operation 3164 * (dev-replace.c:btrfs_dev_replace_finishing()), so we could grab the 3165 * replaced device and then see it with an ID of 3166 * BTRFS_DEV_REPLACE_DEVID, which would cause a failure when updating 3167 * the device item, which does not exists on the chunk btree. 3168 * The finishing phase of device replace acquires both the 3169 * device_list_mutex and the chunk_mutex, in that order, so we are 3170 * safe by just acquiring the chunk_mutex. 3171 */ 3172 trans->removing_chunk = true; 3173 mutex_lock(&fs_info->chunk_mutex); 3174 3175 check_system_chunk(trans, map->type); 3176 3177 ret = remove_chunk_item(trans, map, chunk_offset); 3178 /* 3179 * Normally we should not get -ENOSPC since we reserved space before 3180 * through the call to check_system_chunk(). 3181 * 3182 * Despite our system space_info having enough free space, we may not 3183 * be able to allocate extents from its block groups, because all have 3184 * an incompatible profile, which will force us to allocate a new system 3185 * block group with the right profile, or right after we called 3186 * check_system_space() above, a scrub turned the only system block group 3187 * with enough free space into RO mode. 3188 * This is explained with more detail at do_chunk_alloc(). 3189 * 3190 * So if we get -ENOSPC, allocate a new system chunk and retry once. 3191 */ 3192 if (ret == -ENOSPC) { 3193 const u64 sys_flags = btrfs_system_alloc_profile(fs_info); 3194 struct btrfs_block_group *sys_bg; 3195 3196 sys_bg = btrfs_create_chunk(trans, sys_flags); 3197 if (IS_ERR(sys_bg)) { 3198 ret = PTR_ERR(sys_bg); 3199 btrfs_abort_transaction(trans, ret); 3200 goto out; 3201 } 3202 3203 ret = btrfs_chunk_alloc_add_chunk_item(trans, sys_bg); 3204 if (ret) { 3205 btrfs_abort_transaction(trans, ret); 3206 goto out; 3207 } 3208 3209 ret = remove_chunk_item(trans, map, chunk_offset); 3210 if (ret) { 3211 btrfs_abort_transaction(trans, ret); 3212 goto out; 3213 } 3214 } else if (ret) { 3215 btrfs_abort_transaction(trans, ret); 3216 goto out; 3217 } 3218 3219 trace_btrfs_chunk_free(fs_info, map, chunk_offset, em->len); 3220 3221 if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) { 3222 ret = btrfs_del_sys_chunk(fs_info, chunk_offset); 3223 if (ret) { 3224 btrfs_abort_transaction(trans, ret); 3225 goto out; 3226 } 3227 } 3228 3229 mutex_unlock(&fs_info->chunk_mutex); 3230 trans->removing_chunk = false; 3231 3232 /* 3233 * We are done with chunk btree updates and deletions, so release the 3234 * system space we previously reserved (with check_system_chunk()). 3235 */ 3236 btrfs_trans_release_chunk_metadata(trans); 3237 3238 ret = btrfs_remove_block_group(trans, chunk_offset, em); 3239 if (ret) { 3240 btrfs_abort_transaction(trans, ret); 3241 goto out; 3242 } 3243 3244 out: 3245 if (trans->removing_chunk) { 3246 mutex_unlock(&fs_info->chunk_mutex); 3247 trans->removing_chunk = false; 3248 } 3249 /* once for us */ 3250 free_extent_map(em); 3251 return ret; 3252 } 3253 3254 int btrfs_relocate_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset) 3255 { 3256 struct btrfs_root *root = fs_info->chunk_root; 3257 struct btrfs_trans_handle *trans; 3258 struct btrfs_block_group *block_group; 3259 u64 length; 3260 int ret; 3261 3262 if (btrfs_fs_incompat(fs_info, EXTENT_TREE_V2)) { 3263 btrfs_err(fs_info, 3264 "relocate: not supported on extent tree v2 yet"); 3265 return -EINVAL; 3266 } 3267 3268 /* 3269 * Prevent races with automatic removal of unused block groups. 3270 * After we relocate and before we remove the chunk with offset 3271 * chunk_offset, automatic removal of the block group can kick in, 3272 * resulting in a failure when calling btrfs_remove_chunk() below. 3273 * 3274 * Make sure to acquire this mutex before doing a tree search (dev 3275 * or chunk trees) to find chunks. Otherwise the cleaner kthread might 3276 * call btrfs_remove_chunk() (through btrfs_delete_unused_bgs()) after 3277 * we release the path used to search the chunk/dev tree and before 3278 * the current task acquires this mutex and calls us. 3279 */ 3280 lockdep_assert_held(&fs_info->reclaim_bgs_lock); 3281 3282 /* step one, relocate all the extents inside this chunk */ 3283 btrfs_scrub_pause(fs_info); 3284 ret = btrfs_relocate_block_group(fs_info, chunk_offset); 3285 btrfs_scrub_continue(fs_info); 3286 if (ret) { 3287 /* 3288 * If we had a transaction abort, stop all running scrubs. 3289 * See transaction.c:cleanup_transaction() why we do it here. 3290 */ 3291 if (BTRFS_FS_ERROR(fs_info)) 3292 btrfs_scrub_cancel(fs_info); 3293 return ret; 3294 } 3295 3296 block_group = btrfs_lookup_block_group(fs_info, chunk_offset); 3297 if (!block_group) 3298 return -ENOENT; 3299 btrfs_discard_cancel_work(&fs_info->discard_ctl, block_group); 3300 length = block_group->length; 3301 btrfs_put_block_group(block_group); 3302 3303 /* 3304 * On a zoned file system, discard the whole block group, this will 3305 * trigger a REQ_OP_ZONE_RESET operation on the device zone. If 3306 * resetting the zone fails, don't treat it as a fatal problem from the 3307 * filesystem's point of view. 3308 */ 3309 if (btrfs_is_zoned(fs_info)) { 3310 ret = btrfs_discard_extent(fs_info, chunk_offset, length, NULL); 3311 if (ret) 3312 btrfs_info(fs_info, 3313 "failed to reset zone %llu after relocation", 3314 chunk_offset); 3315 } 3316 3317 trans = btrfs_start_trans_remove_block_group(root->fs_info, 3318 chunk_offset); 3319 if (IS_ERR(trans)) { 3320 ret = PTR_ERR(trans); 3321 btrfs_handle_fs_error(root->fs_info, ret, NULL); 3322 return ret; 3323 } 3324 3325 /* 3326 * step two, delete the device extents and the 3327 * chunk tree entries 3328 */ 3329 ret = btrfs_remove_chunk(trans, chunk_offset); 3330 btrfs_end_transaction(trans); 3331 return ret; 3332 } 3333 3334 static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info) 3335 { 3336 struct btrfs_root *chunk_root = fs_info->chunk_root; 3337 struct btrfs_path *path; 3338 struct extent_buffer *leaf; 3339 struct btrfs_chunk *chunk; 3340 struct btrfs_key key; 3341 struct btrfs_key found_key; 3342 u64 chunk_type; 3343 bool retried = false; 3344 int failed = 0; 3345 int ret; 3346 3347 path = btrfs_alloc_path(); 3348 if (!path) 3349 return -ENOMEM; 3350 3351 again: 3352 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID; 3353 key.offset = (u64)-1; 3354 key.type = BTRFS_CHUNK_ITEM_KEY; 3355 3356 while (1) { 3357 mutex_lock(&fs_info->reclaim_bgs_lock); 3358 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0); 3359 if (ret < 0) { 3360 mutex_unlock(&fs_info->reclaim_bgs_lock); 3361 goto error; 3362 } 3363 BUG_ON(ret == 0); /* Corruption */ 3364 3365 ret = btrfs_previous_item(chunk_root, path, key.objectid, 3366 key.type); 3367 if (ret) 3368 mutex_unlock(&fs_info->reclaim_bgs_lock); 3369 if (ret < 0) 3370 goto error; 3371 if (ret > 0) 3372 break; 3373 3374 leaf = path->nodes[0]; 3375 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]); 3376 3377 chunk = btrfs_item_ptr(leaf, path->slots[0], 3378 struct btrfs_chunk); 3379 chunk_type = btrfs_chunk_type(leaf, chunk); 3380 btrfs_release_path(path); 3381 3382 if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) { 3383 ret = btrfs_relocate_chunk(fs_info, found_key.offset); 3384 if (ret == -ENOSPC) 3385 failed++; 3386 else 3387 BUG_ON(ret); 3388 } 3389 mutex_unlock(&fs_info->reclaim_bgs_lock); 3390 3391 if (found_key.offset == 0) 3392 break; 3393 key.offset = found_key.offset - 1; 3394 } 3395 ret = 0; 3396 if (failed && !retried) { 3397 failed = 0; 3398 retried = true; 3399 goto again; 3400 } else if (WARN_ON(failed && retried)) { 3401 ret = -ENOSPC; 3402 } 3403 error: 3404 btrfs_free_path(path); 3405 return ret; 3406 } 3407 3408 /* 3409 * return 1 : allocate a data chunk successfully, 3410 * return <0: errors during allocating a data chunk, 3411 * return 0 : no need to allocate a data chunk. 3412 */ 3413 static int btrfs_may_alloc_data_chunk(struct btrfs_fs_info *fs_info, 3414 u64 chunk_offset) 3415 { 3416 struct btrfs_block_group *cache; 3417 u64 bytes_used; 3418 u64 chunk_type; 3419 3420 cache = btrfs_lookup_block_group(fs_info, chunk_offset); 3421 ASSERT(cache); 3422 chunk_type = cache->flags; 3423 btrfs_put_block_group(cache); 3424 3425 if (!(chunk_type & BTRFS_BLOCK_GROUP_DATA)) 3426 return 0; 3427 3428 spin_lock(&fs_info->data_sinfo->lock); 3429 bytes_used = fs_info->data_sinfo->bytes_used; 3430 spin_unlock(&fs_info->data_sinfo->lock); 3431 3432 if (!bytes_used) { 3433 struct btrfs_trans_handle *trans; 3434 int ret; 3435 3436 trans = btrfs_join_transaction(fs_info->tree_root); 3437 if (IS_ERR(trans)) 3438 return PTR_ERR(trans); 3439 3440 ret = btrfs_force_chunk_alloc(trans, BTRFS_BLOCK_GROUP_DATA); 3441 btrfs_end_transaction(trans); 3442 if (ret < 0) 3443 return ret; 3444 return 1; 3445 } 3446 3447 return 0; 3448 } 3449 3450 static int insert_balance_item(struct btrfs_fs_info *fs_info, 3451 struct btrfs_balance_control *bctl) 3452 { 3453 struct btrfs_root *root = fs_info->tree_root; 3454 struct btrfs_trans_handle *trans; 3455 struct btrfs_balance_item *item; 3456 struct btrfs_disk_balance_args disk_bargs; 3457 struct btrfs_path *path; 3458 struct extent_buffer *leaf; 3459 struct btrfs_key key; 3460 int ret, err; 3461 3462 path = btrfs_alloc_path(); 3463 if (!path) 3464 return -ENOMEM; 3465 3466 trans = btrfs_start_transaction(root, 0); 3467 if (IS_ERR(trans)) { 3468 btrfs_free_path(path); 3469 return PTR_ERR(trans); 3470 } 3471 3472 key.objectid = BTRFS_BALANCE_OBJECTID; 3473 key.type = BTRFS_TEMPORARY_ITEM_KEY; 3474 key.offset = 0; 3475 3476 ret = btrfs_insert_empty_item(trans, root, path, &key, 3477 sizeof(*item)); 3478 if (ret) 3479 goto out; 3480 3481 leaf = path->nodes[0]; 3482 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item); 3483 3484 memzero_extent_buffer(leaf, (unsigned long)item, sizeof(*item)); 3485 3486 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->data); 3487 btrfs_set_balance_data(leaf, item, &disk_bargs); 3488 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->meta); 3489 btrfs_set_balance_meta(leaf, item, &disk_bargs); 3490 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->sys); 3491 btrfs_set_balance_sys(leaf, item, &disk_bargs); 3492 3493 btrfs_set_balance_flags(leaf, item, bctl->flags); 3494 3495 btrfs_mark_buffer_dirty(leaf); 3496 out: 3497 btrfs_free_path(path); 3498 err = btrfs_commit_transaction(trans); 3499 if (err && !ret) 3500 ret = err; 3501 return ret; 3502 } 3503 3504 static int del_balance_item(struct btrfs_fs_info *fs_info) 3505 { 3506 struct btrfs_root *root = fs_info->tree_root; 3507 struct btrfs_trans_handle *trans; 3508 struct btrfs_path *path; 3509 struct btrfs_key key; 3510 int ret, err; 3511 3512 path = btrfs_alloc_path(); 3513 if (!path) 3514 return -ENOMEM; 3515 3516 trans = btrfs_start_transaction_fallback_global_rsv(root, 0); 3517 if (IS_ERR(trans)) { 3518 btrfs_free_path(path); 3519 return PTR_ERR(trans); 3520 } 3521 3522 key.objectid = BTRFS_BALANCE_OBJECTID; 3523 key.type = BTRFS_TEMPORARY_ITEM_KEY; 3524 key.offset = 0; 3525 3526 ret = btrfs_search_slot(trans, root, &key, path, -1, 1); 3527 if (ret < 0) 3528 goto out; 3529 if (ret > 0) { 3530 ret = -ENOENT; 3531 goto out; 3532 } 3533 3534 ret = btrfs_del_item(trans, root, path); 3535 out: 3536 btrfs_free_path(path); 3537 err = btrfs_commit_transaction(trans); 3538 if (err && !ret) 3539 ret = err; 3540 return ret; 3541 } 3542 3543 /* 3544 * This is a heuristic used to reduce the number of chunks balanced on 3545 * resume after balance was interrupted. 3546 */ 3547 static void update_balance_args(struct btrfs_balance_control *bctl) 3548 { 3549 /* 3550 * Turn on soft mode for chunk types that were being converted. 3551 */ 3552 if (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) 3553 bctl->data.flags |= BTRFS_BALANCE_ARGS_SOFT; 3554 if (bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) 3555 bctl->sys.flags |= BTRFS_BALANCE_ARGS_SOFT; 3556 if (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) 3557 bctl->meta.flags |= BTRFS_BALANCE_ARGS_SOFT; 3558 3559 /* 3560 * Turn on usage filter if is not already used. The idea is 3561 * that chunks that we have already balanced should be 3562 * reasonably full. Don't do it for chunks that are being 3563 * converted - that will keep us from relocating unconverted 3564 * (albeit full) chunks. 3565 */ 3566 if (!(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE) && 3567 !(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) && 3568 !(bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)) { 3569 bctl->data.flags |= BTRFS_BALANCE_ARGS_USAGE; 3570 bctl->data.usage = 90; 3571 } 3572 if (!(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE) && 3573 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) && 3574 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)) { 3575 bctl->sys.flags |= BTRFS_BALANCE_ARGS_USAGE; 3576 bctl->sys.usage = 90; 3577 } 3578 if (!(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE) && 3579 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) && 3580 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)) { 3581 bctl->meta.flags |= BTRFS_BALANCE_ARGS_USAGE; 3582 bctl->meta.usage = 90; 3583 } 3584 } 3585 3586 /* 3587 * Clear the balance status in fs_info and delete the balance item from disk. 3588 */ 3589 static void reset_balance_state(struct btrfs_fs_info *fs_info) 3590 { 3591 struct btrfs_balance_control *bctl = fs_info->balance_ctl; 3592 int ret; 3593 3594 BUG_ON(!fs_info->balance_ctl); 3595 3596 spin_lock(&fs_info->balance_lock); 3597 fs_info->balance_ctl = NULL; 3598 spin_unlock(&fs_info->balance_lock); 3599 3600 kfree(bctl); 3601 ret = del_balance_item(fs_info); 3602 if (ret) 3603 btrfs_handle_fs_error(fs_info, ret, NULL); 3604 } 3605 3606 /* 3607 * Balance filters. Return 1 if chunk should be filtered out 3608 * (should not be balanced). 3609 */ 3610 static int chunk_profiles_filter(u64 chunk_type, 3611 struct btrfs_balance_args *bargs) 3612 { 3613 chunk_type = chunk_to_extended(chunk_type) & 3614 BTRFS_EXTENDED_PROFILE_MASK; 3615 3616 if (bargs->profiles & chunk_type) 3617 return 0; 3618 3619 return 1; 3620 } 3621 3622 static int chunk_usage_range_filter(struct btrfs_fs_info *fs_info, u64 chunk_offset, 3623 struct btrfs_balance_args *bargs) 3624 { 3625 struct btrfs_block_group *cache; 3626 u64 chunk_used; 3627 u64 user_thresh_min; 3628 u64 user_thresh_max; 3629 int ret = 1; 3630 3631 cache = btrfs_lookup_block_group(fs_info, chunk_offset); 3632 chunk_used = cache->used; 3633 3634 if (bargs->usage_min == 0) 3635 user_thresh_min = 0; 3636 else 3637 user_thresh_min = mult_perc(cache->length, bargs->usage_min); 3638 3639 if (bargs->usage_max == 0) 3640 user_thresh_max = 1; 3641 else if (bargs->usage_max > 100) 3642 user_thresh_max = cache->length; 3643 else 3644 user_thresh_max = mult_perc(cache->length, bargs->usage_max); 3645 3646 if (user_thresh_min <= chunk_used && chunk_used < user_thresh_max) 3647 ret = 0; 3648 3649 btrfs_put_block_group(cache); 3650 return ret; 3651 } 3652 3653 static int chunk_usage_filter(struct btrfs_fs_info *fs_info, 3654 u64 chunk_offset, struct btrfs_balance_args *bargs) 3655 { 3656 struct btrfs_block_group *cache; 3657 u64 chunk_used, user_thresh; 3658 int ret = 1; 3659 3660 cache = btrfs_lookup_block_group(fs_info, chunk_offset); 3661 chunk_used = cache->used; 3662 3663 if (bargs->usage_min == 0) 3664 user_thresh = 1; 3665 else if (bargs->usage > 100) 3666 user_thresh = cache->length; 3667 else 3668 user_thresh = mult_perc(cache->length, bargs->usage); 3669 3670 if (chunk_used < user_thresh) 3671 ret = 0; 3672 3673 btrfs_put_block_group(cache); 3674 return ret; 3675 } 3676 3677 static int chunk_devid_filter(struct extent_buffer *leaf, 3678 struct btrfs_chunk *chunk, 3679 struct btrfs_balance_args *bargs) 3680 { 3681 struct btrfs_stripe *stripe; 3682 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk); 3683 int i; 3684 3685 for (i = 0; i < num_stripes; i++) { 3686 stripe = btrfs_stripe_nr(chunk, i); 3687 if (btrfs_stripe_devid(leaf, stripe) == bargs->devid) 3688 return 0; 3689 } 3690 3691 return 1; 3692 } 3693 3694 static u64 calc_data_stripes(u64 type, int num_stripes) 3695 { 3696 const int index = btrfs_bg_flags_to_raid_index(type); 3697 const int ncopies = btrfs_raid_array[index].ncopies; 3698 const int nparity = btrfs_raid_array[index].nparity; 3699 3700 return (num_stripes - nparity) / ncopies; 3701 } 3702 3703 /* [pstart, pend) */ 3704 static int chunk_drange_filter(struct extent_buffer *leaf, 3705 struct btrfs_chunk *chunk, 3706 struct btrfs_balance_args *bargs) 3707 { 3708 struct btrfs_stripe *stripe; 3709 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk); 3710 u64 stripe_offset; 3711 u64 stripe_length; 3712 u64 type; 3713 int factor; 3714 int i; 3715 3716 if (!(bargs->flags & BTRFS_BALANCE_ARGS_DEVID)) 3717 return 0; 3718 3719 type = btrfs_chunk_type(leaf, chunk); 3720 factor = calc_data_stripes(type, num_stripes); 3721 3722 for (i = 0; i < num_stripes; i++) { 3723 stripe = btrfs_stripe_nr(chunk, i); 3724 if (btrfs_stripe_devid(leaf, stripe) != bargs->devid) 3725 continue; 3726 3727 stripe_offset = btrfs_stripe_offset(leaf, stripe); 3728 stripe_length = btrfs_chunk_length(leaf, chunk); 3729 stripe_length = div_u64(stripe_length, factor); 3730 3731 if (stripe_offset < bargs->pend && 3732 stripe_offset + stripe_length > bargs->pstart) 3733 return 0; 3734 } 3735 3736 return 1; 3737 } 3738 3739 /* [vstart, vend) */ 3740 static int chunk_vrange_filter(struct extent_buffer *leaf, 3741 struct btrfs_chunk *chunk, 3742 u64 chunk_offset, 3743 struct btrfs_balance_args *bargs) 3744 { 3745 if (chunk_offset < bargs->vend && 3746 chunk_offset + btrfs_chunk_length(leaf, chunk) > bargs->vstart) 3747 /* at least part of the chunk is inside this vrange */ 3748 return 0; 3749 3750 return 1; 3751 } 3752 3753 static int chunk_stripes_range_filter(struct extent_buffer *leaf, 3754 struct btrfs_chunk *chunk, 3755 struct btrfs_balance_args *bargs) 3756 { 3757 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk); 3758 3759 if (bargs->stripes_min <= num_stripes 3760 && num_stripes <= bargs->stripes_max) 3761 return 0; 3762 3763 return 1; 3764 } 3765 3766 static int chunk_soft_convert_filter(u64 chunk_type, 3767 struct btrfs_balance_args *bargs) 3768 { 3769 if (!(bargs->flags & BTRFS_BALANCE_ARGS_CONVERT)) 3770 return 0; 3771 3772 chunk_type = chunk_to_extended(chunk_type) & 3773 BTRFS_EXTENDED_PROFILE_MASK; 3774 3775 if (bargs->target == chunk_type) 3776 return 1; 3777 3778 return 0; 3779 } 3780 3781 static int should_balance_chunk(struct extent_buffer *leaf, 3782 struct btrfs_chunk *chunk, u64 chunk_offset) 3783 { 3784 struct btrfs_fs_info *fs_info = leaf->fs_info; 3785 struct btrfs_balance_control *bctl = fs_info->balance_ctl; 3786 struct btrfs_balance_args *bargs = NULL; 3787 u64 chunk_type = btrfs_chunk_type(leaf, chunk); 3788 3789 /* type filter */ 3790 if (!((chunk_type & BTRFS_BLOCK_GROUP_TYPE_MASK) & 3791 (bctl->flags & BTRFS_BALANCE_TYPE_MASK))) { 3792 return 0; 3793 } 3794 3795 if (chunk_type & BTRFS_BLOCK_GROUP_DATA) 3796 bargs = &bctl->data; 3797 else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) 3798 bargs = &bctl->sys; 3799 else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA) 3800 bargs = &bctl->meta; 3801 3802 /* profiles filter */ 3803 if ((bargs->flags & BTRFS_BALANCE_ARGS_PROFILES) && 3804 chunk_profiles_filter(chunk_type, bargs)) { 3805 return 0; 3806 } 3807 3808 /* usage filter */ 3809 if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE) && 3810 chunk_usage_filter(fs_info, chunk_offset, bargs)) { 3811 return 0; 3812 } else if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) && 3813 chunk_usage_range_filter(fs_info, chunk_offset, bargs)) { 3814 return 0; 3815 } 3816 3817 /* devid filter */ 3818 if ((bargs->flags & BTRFS_BALANCE_ARGS_DEVID) && 3819 chunk_devid_filter(leaf, chunk, bargs)) { 3820 return 0; 3821 } 3822 3823 /* drange filter, makes sense only with devid filter */ 3824 if ((bargs->flags & BTRFS_BALANCE_ARGS_DRANGE) && 3825 chunk_drange_filter(leaf, chunk, bargs)) { 3826 return 0; 3827 } 3828 3829 /* vrange filter */ 3830 if ((bargs->flags & BTRFS_BALANCE_ARGS_VRANGE) && 3831 chunk_vrange_filter(leaf, chunk, chunk_offset, bargs)) { 3832 return 0; 3833 } 3834 3835 /* stripes filter */ 3836 if ((bargs->flags & BTRFS_BALANCE_ARGS_STRIPES_RANGE) && 3837 chunk_stripes_range_filter(leaf, chunk, bargs)) { 3838 return 0; 3839 } 3840 3841 /* soft profile changing mode */ 3842 if ((bargs->flags & BTRFS_BALANCE_ARGS_SOFT) && 3843 chunk_soft_convert_filter(chunk_type, bargs)) { 3844 return 0; 3845 } 3846 3847 /* 3848 * limited by count, must be the last filter 3849 */ 3850 if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT)) { 3851 if (bargs->limit == 0) 3852 return 0; 3853 else 3854 bargs->limit--; 3855 } else if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT_RANGE)) { 3856 /* 3857 * Same logic as the 'limit' filter; the minimum cannot be 3858 * determined here because we do not have the global information 3859 * about the count of all chunks that satisfy the filters. 3860 */ 3861 if (bargs->limit_max == 0) 3862 return 0; 3863 else 3864 bargs->limit_max--; 3865 } 3866 3867 return 1; 3868 } 3869 3870 static int __btrfs_balance(struct btrfs_fs_info *fs_info) 3871 { 3872 struct btrfs_balance_control *bctl = fs_info->balance_ctl; 3873 struct btrfs_root *chunk_root = fs_info->chunk_root; 3874 u64 chunk_type; 3875 struct btrfs_chunk *chunk; 3876 struct btrfs_path *path = NULL; 3877 struct btrfs_key key; 3878 struct btrfs_key found_key; 3879 struct extent_buffer *leaf; 3880 int slot; 3881 int ret; 3882 int enospc_errors = 0; 3883 bool counting = true; 3884 /* The single value limit and min/max limits use the same bytes in the */ 3885 u64 limit_data = bctl->data.limit; 3886 u64 limit_meta = bctl->meta.limit; 3887 u64 limit_sys = bctl->sys.limit; 3888 u32 count_data = 0; 3889 u32 count_meta = 0; 3890 u32 count_sys = 0; 3891 int chunk_reserved = 0; 3892 3893 path = btrfs_alloc_path(); 3894 if (!path) { 3895 ret = -ENOMEM; 3896 goto error; 3897 } 3898 3899 /* zero out stat counters */ 3900 spin_lock(&fs_info->balance_lock); 3901 memset(&bctl->stat, 0, sizeof(bctl->stat)); 3902 spin_unlock(&fs_info->balance_lock); 3903 again: 3904 if (!counting) { 3905 /* 3906 * The single value limit and min/max limits use the same bytes 3907 * in the 3908 */ 3909 bctl->data.limit = limit_data; 3910 bctl->meta.limit = limit_meta; 3911 bctl->sys.limit = limit_sys; 3912 } 3913 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID; 3914 key.offset = (u64)-1; 3915 key.type = BTRFS_CHUNK_ITEM_KEY; 3916 3917 while (1) { 3918 if ((!counting && atomic_read(&fs_info->balance_pause_req)) || 3919 atomic_read(&fs_info->balance_cancel_req)) { 3920 ret = -ECANCELED; 3921 goto error; 3922 } 3923 3924 mutex_lock(&fs_info->reclaim_bgs_lock); 3925 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0); 3926 if (ret < 0) { 3927 mutex_unlock(&fs_info->reclaim_bgs_lock); 3928 goto error; 3929 } 3930 3931 /* 3932 * this shouldn't happen, it means the last relocate 3933 * failed 3934 */ 3935 if (ret == 0) 3936 BUG(); /* FIXME break ? */ 3937 3938 ret = btrfs_previous_item(chunk_root, path, 0, 3939 BTRFS_CHUNK_ITEM_KEY); 3940 if (ret) { 3941 mutex_unlock(&fs_info->reclaim_bgs_lock); 3942 ret = 0; 3943 break; 3944 } 3945 3946 leaf = path->nodes[0]; 3947 slot = path->slots[0]; 3948 btrfs_item_key_to_cpu(leaf, &found_key, slot); 3949 3950 if (found_key.objectid != key.objectid) { 3951 mutex_unlock(&fs_info->reclaim_bgs_lock); 3952 break; 3953 } 3954 3955 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk); 3956 chunk_type = btrfs_chunk_type(leaf, chunk); 3957 3958 if (!counting) { 3959 spin_lock(&fs_info->balance_lock); 3960 bctl->stat.considered++; 3961 spin_unlock(&fs_info->balance_lock); 3962 } 3963 3964 ret = should_balance_chunk(leaf, chunk, found_key.offset); 3965 3966 btrfs_release_path(path); 3967 if (!ret) { 3968 mutex_unlock(&fs_info->reclaim_bgs_lock); 3969 goto loop; 3970 } 3971 3972 if (counting) { 3973 mutex_unlock(&fs_info->reclaim_bgs_lock); 3974 spin_lock(&fs_info->balance_lock); 3975 bctl->stat.expected++; 3976 spin_unlock(&fs_info->balance_lock); 3977 3978 if (chunk_type & BTRFS_BLOCK_GROUP_DATA) 3979 count_data++; 3980 else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) 3981 count_sys++; 3982 else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA) 3983 count_meta++; 3984 3985 goto loop; 3986 } 3987 3988 /* 3989 * Apply limit_min filter, no need to check if the LIMITS 3990 * filter is used, limit_min is 0 by default 3991 */ 3992 if (((chunk_type & BTRFS_BLOCK_GROUP_DATA) && 3993 count_data < bctl->data.limit_min) 3994 || ((chunk_type & BTRFS_BLOCK_GROUP_METADATA) && 3995 count_meta < bctl->meta.limit_min) 3996 || ((chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) && 3997 count_sys < bctl->sys.limit_min)) { 3998 mutex_unlock(&fs_info->reclaim_bgs_lock); 3999 goto loop; 4000 } 4001 4002 if (!chunk_reserved) { 4003 /* 4004 * We may be relocating the only data chunk we have, 4005 * which could potentially end up with losing data's 4006 * raid profile, so lets allocate an empty one in 4007 * advance. 4008 */ 4009 ret = btrfs_may_alloc_data_chunk(fs_info, 4010 found_key.offset); 4011 if (ret < 0) { 4012 mutex_unlock(&fs_info->reclaim_bgs_lock); 4013 goto error; 4014 } else if (ret == 1) { 4015 chunk_reserved = 1; 4016 } 4017 } 4018 4019 ret = btrfs_relocate_chunk(fs_info, found_key.offset); 4020 mutex_unlock(&fs_info->reclaim_bgs_lock); 4021 if (ret == -ENOSPC) { 4022 enospc_errors++; 4023 } else if (ret == -ETXTBSY) { 4024 btrfs_info(fs_info, 4025 "skipping relocation of block group %llu due to active swapfile", 4026 found_key.offset); 4027 ret = 0; 4028 } else if (ret) { 4029 goto error; 4030 } else { 4031 spin_lock(&fs_info->balance_lock); 4032 bctl->stat.completed++; 4033 spin_unlock(&fs_info->balance_lock); 4034 } 4035 loop: 4036 if (found_key.offset == 0) 4037 break; 4038 key.offset = found_key.offset - 1; 4039 } 4040 4041 if (counting) { 4042 btrfs_release_path(path); 4043 counting = false; 4044 goto again; 4045 } 4046 error: 4047 btrfs_free_path(path); 4048 if (enospc_errors) { 4049 btrfs_info(fs_info, "%d enospc errors during balance", 4050 enospc_errors); 4051 if (!ret) 4052 ret = -ENOSPC; 4053 } 4054 4055 return ret; 4056 } 4057 4058 /* 4059 * See if a given profile is valid and reduced. 4060 * 4061 * @flags: profile to validate 4062 * @extended: if true @flags is treated as an extended profile 4063 */ 4064 static int alloc_profile_is_valid(u64 flags, int extended) 4065 { 4066 u64 mask = (extended ? BTRFS_EXTENDED_PROFILE_MASK : 4067 BTRFS_BLOCK_GROUP_PROFILE_MASK); 4068 4069 flags &= ~BTRFS_BLOCK_GROUP_TYPE_MASK; 4070 4071 /* 1) check that all other bits are zeroed */ 4072 if (flags & ~mask) 4073 return 0; 4074 4075 /* 2) see if profile is reduced */ 4076 if (flags == 0) 4077 return !extended; /* "0" is valid for usual profiles */ 4078 4079 return has_single_bit_set(flags); 4080 } 4081 4082 /* 4083 * Validate target profile against allowed profiles and return true if it's OK. 4084 * Otherwise print the error message and return false. 4085 */ 4086 static inline int validate_convert_profile(struct btrfs_fs_info *fs_info, 4087 const struct btrfs_balance_args *bargs, 4088 u64 allowed, const char *type) 4089 { 4090 if (!(bargs->flags & BTRFS_BALANCE_ARGS_CONVERT)) 4091 return true; 4092 4093 /* Profile is valid and does not have bits outside of the allowed set */ 4094 if (alloc_profile_is_valid(bargs->target, 1) && 4095 (bargs->target & ~allowed) == 0) 4096 return true; 4097 4098 btrfs_err(fs_info, "balance: invalid convert %s profile %s", 4099 type, btrfs_bg_type_to_raid_name(bargs->target)); 4100 return false; 4101 } 4102 4103 /* 4104 * Fill @buf with textual description of balance filter flags @bargs, up to 4105 * @size_buf including the terminating null. The output may be trimmed if it 4106 * does not fit into the provided buffer. 4107 */ 4108 static void describe_balance_args(struct btrfs_balance_args *bargs, char *buf, 4109 u32 size_buf) 4110 { 4111 int ret; 4112 u32 size_bp = size_buf; 4113 char *bp = buf; 4114 u64 flags = bargs->flags; 4115 char tmp_buf[128] = {'\0'}; 4116 4117 if (!flags) 4118 return; 4119 4120 #define CHECK_APPEND_NOARG(a) \ 4121 do { \ 4122 ret = snprintf(bp, size_bp, (a)); \ 4123 if (ret < 0 || ret >= size_bp) \ 4124 goto out_overflow; \ 4125 size_bp -= ret; \ 4126 bp += ret; \ 4127 } while (0) 4128 4129 #define CHECK_APPEND_1ARG(a, v1) \ 4130 do { \ 4131 ret = snprintf(bp, size_bp, (a), (v1)); \ 4132 if (ret < 0 || ret >= size_bp) \ 4133 goto out_overflow; \ 4134 size_bp -= ret; \ 4135 bp += ret; \ 4136 } while (0) 4137 4138 #define CHECK_APPEND_2ARG(a, v1, v2) \ 4139 do { \ 4140 ret = snprintf(bp, size_bp, (a), (v1), (v2)); \ 4141 if (ret < 0 || ret >= size_bp) \ 4142 goto out_overflow; \ 4143 size_bp -= ret; \ 4144 bp += ret; \ 4145 } while (0) 4146 4147 if (flags & BTRFS_BALANCE_ARGS_CONVERT) 4148 CHECK_APPEND_1ARG("convert=%s,", 4149 btrfs_bg_type_to_raid_name(bargs->target)); 4150 4151 if (flags & BTRFS_BALANCE_ARGS_SOFT) 4152 CHECK_APPEND_NOARG("soft,"); 4153 4154 if (flags & BTRFS_BALANCE_ARGS_PROFILES) { 4155 btrfs_describe_block_groups(bargs->profiles, tmp_buf, 4156 sizeof(tmp_buf)); 4157 CHECK_APPEND_1ARG("profiles=%s,", tmp_buf); 4158 } 4159 4160 if (flags & BTRFS_BALANCE_ARGS_USAGE) 4161 CHECK_APPEND_1ARG("usage=%llu,", bargs->usage); 4162 4163 if (flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) 4164 CHECK_APPEND_2ARG("usage=%u..%u,", 4165 bargs->usage_min, bargs->usage_max); 4166 4167 if (flags & BTRFS_BALANCE_ARGS_DEVID) 4168 CHECK_APPEND_1ARG("devid=%llu,", bargs->devid); 4169 4170 if (flags & BTRFS_BALANCE_ARGS_DRANGE) 4171 CHECK_APPEND_2ARG("drange=%llu..%llu,", 4172 bargs->pstart, bargs->pend); 4173 4174 if (flags & BTRFS_BALANCE_ARGS_VRANGE) 4175 CHECK_APPEND_2ARG("vrange=%llu..%llu,", 4176 bargs->vstart, bargs->vend); 4177 4178 if (flags & BTRFS_BALANCE_ARGS_LIMIT) 4179 CHECK_APPEND_1ARG("limit=%llu,", bargs->limit); 4180 4181 if (flags & BTRFS_BALANCE_ARGS_LIMIT_RANGE) 4182 CHECK_APPEND_2ARG("limit=%u..%u,", 4183 bargs->limit_min, bargs->limit_max); 4184 4185 if (flags & BTRFS_BALANCE_ARGS_STRIPES_RANGE) 4186 CHECK_APPEND_2ARG("stripes=%u..%u,", 4187 bargs->stripes_min, bargs->stripes_max); 4188 4189 #undef CHECK_APPEND_2ARG 4190 #undef CHECK_APPEND_1ARG 4191 #undef CHECK_APPEND_NOARG 4192 4193 out_overflow: 4194 4195 if (size_bp < size_buf) 4196 buf[size_buf - size_bp - 1] = '\0'; /* remove last , */ 4197 else 4198 buf[0] = '\0'; 4199 } 4200 4201 static void describe_balance_start_or_resume(struct btrfs_fs_info *fs_info) 4202 { 4203 u32 size_buf = 1024; 4204 char tmp_buf[192] = {'\0'}; 4205 char *buf; 4206 char *bp; 4207 u32 size_bp = size_buf; 4208 int ret; 4209 struct btrfs_balance_control *bctl = fs_info->balance_ctl; 4210 4211 buf = kzalloc(size_buf, GFP_KERNEL); 4212 if (!buf) 4213 return; 4214 4215 bp = buf; 4216 4217 #define CHECK_APPEND_1ARG(a, v1) \ 4218 do { \ 4219 ret = snprintf(bp, size_bp, (a), (v1)); \ 4220 if (ret < 0 || ret >= size_bp) \ 4221 goto out_overflow; \ 4222 size_bp -= ret; \ 4223 bp += ret; \ 4224 } while (0) 4225 4226 if (bctl->flags & BTRFS_BALANCE_FORCE) 4227 CHECK_APPEND_1ARG("%s", "-f "); 4228 4229 if (bctl->flags & BTRFS_BALANCE_DATA) { 4230 describe_balance_args(&bctl->data, tmp_buf, sizeof(tmp_buf)); 4231 CHECK_APPEND_1ARG("-d%s ", tmp_buf); 4232 } 4233 4234 if (bctl->flags & BTRFS_BALANCE_METADATA) { 4235 describe_balance_args(&bctl->meta, tmp_buf, sizeof(tmp_buf)); 4236 CHECK_APPEND_1ARG("-m%s ", tmp_buf); 4237 } 4238 4239 if (bctl->flags & BTRFS_BALANCE_SYSTEM) { 4240 describe_balance_args(&bctl->sys, tmp_buf, sizeof(tmp_buf)); 4241 CHECK_APPEND_1ARG("-s%s ", tmp_buf); 4242 } 4243 4244 #undef CHECK_APPEND_1ARG 4245 4246 out_overflow: 4247 4248 if (size_bp < size_buf) 4249 buf[size_buf - size_bp - 1] = '\0'; /* remove last " " */ 4250 btrfs_info(fs_info, "balance: %s %s", 4251 (bctl->flags & BTRFS_BALANCE_RESUME) ? 4252 "resume" : "start", buf); 4253 4254 kfree(buf); 4255 } 4256 4257 /* 4258 * Should be called with balance mutexe held 4259 */ 4260 int btrfs_balance(struct btrfs_fs_info *fs_info, 4261 struct btrfs_balance_control *bctl, 4262 struct btrfs_ioctl_balance_args *bargs) 4263 { 4264 u64 meta_target, data_target; 4265 u64 allowed; 4266 int mixed = 0; 4267 int ret; 4268 u64 num_devices; 4269 unsigned seq; 4270 bool reducing_redundancy; 4271 bool paused = false; 4272 int i; 4273 4274 if (btrfs_fs_closing(fs_info) || 4275 atomic_read(&fs_info->balance_pause_req) || 4276 btrfs_should_cancel_balance(fs_info)) { 4277 ret = -EINVAL; 4278 goto out; 4279 } 4280 4281 allowed = btrfs_super_incompat_flags(fs_info->super_copy); 4282 if (allowed & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS) 4283 mixed = 1; 4284 4285 /* 4286 * In case of mixed groups both data and meta should be picked, 4287 * and identical options should be given for both of them. 4288 */ 4289 allowed = BTRFS_BALANCE_DATA | BTRFS_BALANCE_METADATA; 4290 if (mixed && (bctl->flags & allowed)) { 4291 if (!(bctl->flags & BTRFS_BALANCE_DATA) || 4292 !(bctl->flags & BTRFS_BALANCE_METADATA) || 4293 memcmp(&bctl->data, &bctl->meta, sizeof(bctl->data))) { 4294 btrfs_err(fs_info, 4295 "balance: mixed groups data and metadata options must be the same"); 4296 ret = -EINVAL; 4297 goto out; 4298 } 4299 } 4300 4301 /* 4302 * rw_devices will not change at the moment, device add/delete/replace 4303 * are exclusive 4304 */ 4305 num_devices = fs_info->fs_devices->rw_devices; 4306 4307 /* 4308 * SINGLE profile on-disk has no profile bit, but in-memory we have a 4309 * special bit for it, to make it easier to distinguish. Thus we need 4310 * to set it manually, or balance would refuse the profile. 4311 */ 4312 allowed = BTRFS_AVAIL_ALLOC_BIT_SINGLE; 4313 for (i = 0; i < ARRAY_SIZE(btrfs_raid_array); i++) 4314 if (num_devices >= btrfs_raid_array[i].devs_min) 4315 allowed |= btrfs_raid_array[i].bg_flag; 4316 4317 if (!validate_convert_profile(fs_info, &bctl->data, allowed, "data") || 4318 !validate_convert_profile(fs_info, &bctl->meta, allowed, "metadata") || 4319 !validate_convert_profile(fs_info, &bctl->sys, allowed, "system")) { 4320 ret = -EINVAL; 4321 goto out; 4322 } 4323 4324 /* 4325 * Allow to reduce metadata or system integrity only if force set for 4326 * profiles with redundancy (copies, parity) 4327 */ 4328 allowed = 0; 4329 for (i = 0; i < ARRAY_SIZE(btrfs_raid_array); i++) { 4330 if (btrfs_raid_array[i].ncopies >= 2 || 4331 btrfs_raid_array[i].tolerated_failures >= 1) 4332 allowed |= btrfs_raid_array[i].bg_flag; 4333 } 4334 do { 4335 seq = read_seqbegin(&fs_info->profiles_lock); 4336 4337 if (((bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) && 4338 (fs_info->avail_system_alloc_bits & allowed) && 4339 !(bctl->sys.target & allowed)) || 4340 ((bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) && 4341 (fs_info->avail_metadata_alloc_bits & allowed) && 4342 !(bctl->meta.target & allowed))) 4343 reducing_redundancy = true; 4344 else 4345 reducing_redundancy = false; 4346 4347 /* if we're not converting, the target field is uninitialized */ 4348 meta_target = (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) ? 4349 bctl->meta.target : fs_info->avail_metadata_alloc_bits; 4350 data_target = (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) ? 4351 bctl->data.target : fs_info->avail_data_alloc_bits; 4352 } while (read_seqretry(&fs_info->profiles_lock, seq)); 4353 4354 if (reducing_redundancy) { 4355 if (bctl->flags & BTRFS_BALANCE_FORCE) { 4356 btrfs_info(fs_info, 4357 "balance: force reducing metadata redundancy"); 4358 } else { 4359 btrfs_err(fs_info, 4360 "balance: reduces metadata redundancy, use --force if you want this"); 4361 ret = -EINVAL; 4362 goto out; 4363 } 4364 } 4365 4366 if (btrfs_get_num_tolerated_disk_barrier_failures(meta_target) < 4367 btrfs_get_num_tolerated_disk_barrier_failures(data_target)) { 4368 btrfs_warn(fs_info, 4369 "balance: metadata profile %s has lower redundancy than data profile %s", 4370 btrfs_bg_type_to_raid_name(meta_target), 4371 btrfs_bg_type_to_raid_name(data_target)); 4372 } 4373 4374 ret = insert_balance_item(fs_info, bctl); 4375 if (ret && ret != -EEXIST) 4376 goto out; 4377 4378 if (!(bctl->flags & BTRFS_BALANCE_RESUME)) { 4379 BUG_ON(ret == -EEXIST); 4380 BUG_ON(fs_info->balance_ctl); 4381 spin_lock(&fs_info->balance_lock); 4382 fs_info->balance_ctl = bctl; 4383 spin_unlock(&fs_info->balance_lock); 4384 } else { 4385 BUG_ON(ret != -EEXIST); 4386 spin_lock(&fs_info->balance_lock); 4387 update_balance_args(bctl); 4388 spin_unlock(&fs_info->balance_lock); 4389 } 4390 4391 ASSERT(!test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)); 4392 set_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags); 4393 describe_balance_start_or_resume(fs_info); 4394 mutex_unlock(&fs_info->balance_mutex); 4395 4396 ret = __btrfs_balance(fs_info); 4397 4398 mutex_lock(&fs_info->balance_mutex); 4399 if (ret == -ECANCELED && atomic_read(&fs_info->balance_pause_req)) { 4400 btrfs_info(fs_info, "balance: paused"); 4401 btrfs_exclop_balance(fs_info, BTRFS_EXCLOP_BALANCE_PAUSED); 4402 paused = true; 4403 } 4404 /* 4405 * Balance can be canceled by: 4406 * 4407 * - Regular cancel request 4408 * Then ret == -ECANCELED and balance_cancel_req > 0 4409 * 4410 * - Fatal signal to "btrfs" process 4411 * Either the signal caught by wait_reserve_ticket() and callers 4412 * got -EINTR, or caught by btrfs_should_cancel_balance() and 4413 * got -ECANCELED. 4414 * Either way, in this case balance_cancel_req = 0, and 4415 * ret == -EINTR or ret == -ECANCELED. 4416 * 4417 * So here we only check the return value to catch canceled balance. 4418 */ 4419 else if (ret == -ECANCELED || ret == -EINTR) 4420 btrfs_info(fs_info, "balance: canceled"); 4421 else 4422 btrfs_info(fs_info, "balance: ended with status: %d", ret); 4423 4424 clear_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags); 4425 4426 if (bargs) { 4427 memset(bargs, 0, sizeof(*bargs)); 4428 btrfs_update_ioctl_balance_args(fs_info, bargs); 4429 } 4430 4431 /* We didn't pause, we can clean everything up. */ 4432 if (!paused) { 4433 reset_balance_state(fs_info); 4434 btrfs_exclop_finish(fs_info); 4435 } 4436 4437 wake_up(&fs_info->balance_wait_q); 4438 4439 return ret; 4440 out: 4441 if (bctl->flags & BTRFS_BALANCE_RESUME) 4442 reset_balance_state(fs_info); 4443 else 4444 kfree(bctl); 4445 btrfs_exclop_finish(fs_info); 4446 4447 return ret; 4448 } 4449 4450 static int balance_kthread(void *data) 4451 { 4452 struct btrfs_fs_info *fs_info = data; 4453 int ret = 0; 4454 4455 sb_start_write(fs_info->sb); 4456 mutex_lock(&fs_info->balance_mutex); 4457 if (fs_info->balance_ctl) 4458 ret = btrfs_balance(fs_info, fs_info->balance_ctl, NULL); 4459 mutex_unlock(&fs_info->balance_mutex); 4460 sb_end_write(fs_info->sb); 4461 4462 return ret; 4463 } 4464 4465 int btrfs_resume_balance_async(struct btrfs_fs_info *fs_info) 4466 { 4467 struct task_struct *tsk; 4468 4469 mutex_lock(&fs_info->balance_mutex); 4470 if (!fs_info->balance_ctl) { 4471 mutex_unlock(&fs_info->balance_mutex); 4472 return 0; 4473 } 4474 mutex_unlock(&fs_info->balance_mutex); 4475 4476 if (btrfs_test_opt(fs_info, SKIP_BALANCE)) { 4477 btrfs_info(fs_info, "balance: resume skipped"); 4478 return 0; 4479 } 4480 4481 spin_lock(&fs_info->super_lock); 4482 ASSERT(fs_info->exclusive_operation == BTRFS_EXCLOP_BALANCE_PAUSED); 4483 fs_info->exclusive_operation = BTRFS_EXCLOP_BALANCE; 4484 spin_unlock(&fs_info->super_lock); 4485 /* 4486 * A ro->rw remount sequence should continue with the paused balance 4487 * regardless of who pauses it, system or the user as of now, so set 4488 * the resume flag. 4489 */ 4490 spin_lock(&fs_info->balance_lock); 4491 fs_info->balance_ctl->flags |= BTRFS_BALANCE_RESUME; 4492 spin_unlock(&fs_info->balance_lock); 4493 4494 tsk = kthread_run(balance_kthread, fs_info, "btrfs-balance"); 4495 return PTR_ERR_OR_ZERO(tsk); 4496 } 4497 4498 int btrfs_recover_balance(struct btrfs_fs_info *fs_info) 4499 { 4500 struct btrfs_balance_control *bctl; 4501 struct btrfs_balance_item *item; 4502 struct btrfs_disk_balance_args disk_bargs; 4503 struct btrfs_path *path; 4504 struct extent_buffer *leaf; 4505 struct btrfs_key key; 4506 int ret; 4507 4508 path = btrfs_alloc_path(); 4509 if (!path) 4510 return -ENOMEM; 4511 4512 key.objectid = BTRFS_BALANCE_OBJECTID; 4513 key.type = BTRFS_TEMPORARY_ITEM_KEY; 4514 key.offset = 0; 4515 4516 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0); 4517 if (ret < 0) 4518 goto out; 4519 if (ret > 0) { /* ret = -ENOENT; */ 4520 ret = 0; 4521 goto out; 4522 } 4523 4524 bctl = kzalloc(sizeof(*bctl), GFP_NOFS); 4525 if (!bctl) { 4526 ret = -ENOMEM; 4527 goto out; 4528 } 4529 4530 leaf = path->nodes[0]; 4531 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item); 4532 4533 bctl->flags = btrfs_balance_flags(leaf, item); 4534 bctl->flags |= BTRFS_BALANCE_RESUME; 4535 4536 btrfs_balance_data(leaf, item, &disk_bargs); 4537 btrfs_disk_balance_args_to_cpu(&bctl->data, &disk_bargs); 4538 btrfs_balance_meta(leaf, item, &disk_bargs); 4539 btrfs_disk_balance_args_to_cpu(&bctl->meta, &disk_bargs); 4540 btrfs_balance_sys(leaf, item, &disk_bargs); 4541 btrfs_disk_balance_args_to_cpu(&bctl->sys, &disk_bargs); 4542 4543 /* 4544 * This should never happen, as the paused balance state is recovered 4545 * during mount without any chance of other exclusive ops to collide. 4546 * 4547 * This gives the exclusive op status to balance and keeps in paused 4548 * state until user intervention (cancel or umount). If the ownership 4549 * cannot be assigned, show a message but do not fail. The balance 4550 * is in a paused state and must have fs_info::balance_ctl properly 4551 * set up. 4552 */ 4553 if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_BALANCE_PAUSED)) 4554 btrfs_warn(fs_info, 4555 "balance: cannot set exclusive op status, resume manually"); 4556 4557 btrfs_release_path(path); 4558 4559 mutex_lock(&fs_info->balance_mutex); 4560 BUG_ON(fs_info->balance_ctl); 4561 spin_lock(&fs_info->balance_lock); 4562 fs_info->balance_ctl = bctl; 4563 spin_unlock(&fs_info->balance_lock); 4564 mutex_unlock(&fs_info->balance_mutex); 4565 out: 4566 btrfs_free_path(path); 4567 return ret; 4568 } 4569 4570 int btrfs_pause_balance(struct btrfs_fs_info *fs_info) 4571 { 4572 int ret = 0; 4573 4574 mutex_lock(&fs_info->balance_mutex); 4575 if (!fs_info->balance_ctl) { 4576 mutex_unlock(&fs_info->balance_mutex); 4577 return -ENOTCONN; 4578 } 4579 4580 if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) { 4581 atomic_inc(&fs_info->balance_pause_req); 4582 mutex_unlock(&fs_info->balance_mutex); 4583 4584 wait_event(fs_info->balance_wait_q, 4585 !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)); 4586 4587 mutex_lock(&fs_info->balance_mutex); 4588 /* we are good with balance_ctl ripped off from under us */ 4589 BUG_ON(test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)); 4590 atomic_dec(&fs_info->balance_pause_req); 4591 } else { 4592 ret = -ENOTCONN; 4593 } 4594 4595 mutex_unlock(&fs_info->balance_mutex); 4596 return ret; 4597 } 4598 4599 int btrfs_cancel_balance(struct btrfs_fs_info *fs_info) 4600 { 4601 mutex_lock(&fs_info->balance_mutex); 4602 if (!fs_info->balance_ctl) { 4603 mutex_unlock(&fs_info->balance_mutex); 4604 return -ENOTCONN; 4605 } 4606 4607 /* 4608 * A paused balance with the item stored on disk can be resumed at 4609 * mount time if the mount is read-write. Otherwise it's still paused 4610 * and we must not allow cancelling as it deletes the item. 4611 */ 4612 if (sb_rdonly(fs_info->sb)) { 4613 mutex_unlock(&fs_info->balance_mutex); 4614 return -EROFS; 4615 } 4616 4617 atomic_inc(&fs_info->balance_cancel_req); 4618 /* 4619 * if we are running just wait and return, balance item is 4620 * deleted in btrfs_balance in this case 4621 */ 4622 if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) { 4623 mutex_unlock(&fs_info->balance_mutex); 4624 wait_event(fs_info->balance_wait_q, 4625 !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)); 4626 mutex_lock(&fs_info->balance_mutex); 4627 } else { 4628 mutex_unlock(&fs_info->balance_mutex); 4629 /* 4630 * Lock released to allow other waiters to continue, we'll 4631 * reexamine the status again. 4632 */ 4633 mutex_lock(&fs_info->balance_mutex); 4634 4635 if (fs_info->balance_ctl) { 4636 reset_balance_state(fs_info); 4637 btrfs_exclop_finish(fs_info); 4638 btrfs_info(fs_info, "balance: canceled"); 4639 } 4640 } 4641 4642 ASSERT(!test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)); 4643 atomic_dec(&fs_info->balance_cancel_req); 4644 mutex_unlock(&fs_info->balance_mutex); 4645 return 0; 4646 } 4647 4648 int btrfs_uuid_scan_kthread(void *data) 4649 { 4650 struct btrfs_fs_info *fs_info = data; 4651 struct btrfs_root *root = fs_info->tree_root; 4652 struct btrfs_key key; 4653 struct btrfs_path *path = NULL; 4654 int ret = 0; 4655 struct extent_buffer *eb; 4656 int slot; 4657 struct btrfs_root_item root_item; 4658 u32 item_size; 4659 struct btrfs_trans_handle *trans = NULL; 4660 bool closing = false; 4661 4662 path = btrfs_alloc_path(); 4663 if (!path) { 4664 ret = -ENOMEM; 4665 goto out; 4666 } 4667 4668 key.objectid = 0; 4669 key.type = BTRFS_ROOT_ITEM_KEY; 4670 key.offset = 0; 4671 4672 while (1) { 4673 if (btrfs_fs_closing(fs_info)) { 4674 closing = true; 4675 break; 4676 } 4677 ret = btrfs_search_forward(root, &key, path, 4678 BTRFS_OLDEST_GENERATION); 4679 if (ret) { 4680 if (ret > 0) 4681 ret = 0; 4682 break; 4683 } 4684 4685 if (key.type != BTRFS_ROOT_ITEM_KEY || 4686 (key.objectid < BTRFS_FIRST_FREE_OBJECTID && 4687 key.objectid != BTRFS_FS_TREE_OBJECTID) || 4688 key.objectid > BTRFS_LAST_FREE_OBJECTID) 4689 goto skip; 4690 4691 eb = path->nodes[0]; 4692 slot = path->slots[0]; 4693 item_size = btrfs_item_size(eb, slot); 4694 if (item_size < sizeof(root_item)) 4695 goto skip; 4696 4697 read_extent_buffer(eb, &root_item, 4698 btrfs_item_ptr_offset(eb, slot), 4699 (int)sizeof(root_item)); 4700 if (btrfs_root_refs(&root_item) == 0) 4701 goto skip; 4702 4703 if (!btrfs_is_empty_uuid(root_item.uuid) || 4704 !btrfs_is_empty_uuid(root_item.received_uuid)) { 4705 if (trans) 4706 goto update_tree; 4707 4708 btrfs_release_path(path); 4709 /* 4710 * 1 - subvol uuid item 4711 * 1 - received_subvol uuid item 4712 */ 4713 trans = btrfs_start_transaction(fs_info->uuid_root, 2); 4714 if (IS_ERR(trans)) { 4715 ret = PTR_ERR(trans); 4716 break; 4717 } 4718 continue; 4719 } else { 4720 goto skip; 4721 } 4722 update_tree: 4723 btrfs_release_path(path); 4724 if (!btrfs_is_empty_uuid(root_item.uuid)) { 4725 ret = btrfs_uuid_tree_add(trans, root_item.uuid, 4726 BTRFS_UUID_KEY_SUBVOL, 4727 key.objectid); 4728 if (ret < 0) { 4729 btrfs_warn(fs_info, "uuid_tree_add failed %d", 4730 ret); 4731 break; 4732 } 4733 } 4734 4735 if (!btrfs_is_empty_uuid(root_item.received_uuid)) { 4736 ret = btrfs_uuid_tree_add(trans, 4737 root_item.received_uuid, 4738 BTRFS_UUID_KEY_RECEIVED_SUBVOL, 4739 key.objectid); 4740 if (ret < 0) { 4741 btrfs_warn(fs_info, "uuid_tree_add failed %d", 4742 ret); 4743 break; 4744 } 4745 } 4746 4747 skip: 4748 btrfs_release_path(path); 4749 if (trans) { 4750 ret = btrfs_end_transaction(trans); 4751 trans = NULL; 4752 if (ret) 4753 break; 4754 } 4755 4756 if (key.offset < (u64)-1) { 4757 key.offset++; 4758 } else if (key.type < BTRFS_ROOT_ITEM_KEY) { 4759 key.offset = 0; 4760 key.type = BTRFS_ROOT_ITEM_KEY; 4761 } else if (key.objectid < (u64)-1) { 4762 key.offset = 0; 4763 key.type = BTRFS_ROOT_ITEM_KEY; 4764 key.objectid++; 4765 } else { 4766 break; 4767 } 4768 cond_resched(); 4769 } 4770 4771 out: 4772 btrfs_free_path(path); 4773 if (trans && !IS_ERR(trans)) 4774 btrfs_end_transaction(trans); 4775 if (ret) 4776 btrfs_warn(fs_info, "btrfs_uuid_scan_kthread failed %d", ret); 4777 else if (!closing) 4778 set_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags); 4779 up(&fs_info->uuid_tree_rescan_sem); 4780 return 0; 4781 } 4782 4783 int btrfs_create_uuid_tree(struct btrfs_fs_info *fs_info) 4784 { 4785 struct btrfs_trans_handle *trans; 4786 struct btrfs_root *tree_root = fs_info->tree_root; 4787 struct btrfs_root *uuid_root; 4788 struct task_struct *task; 4789 int ret; 4790 4791 /* 4792 * 1 - root node 4793 * 1 - root item 4794 */ 4795 trans = btrfs_start_transaction(tree_root, 2); 4796 if (IS_ERR(trans)) 4797 return PTR_ERR(trans); 4798 4799 uuid_root = btrfs_create_tree(trans, BTRFS_UUID_TREE_OBJECTID); 4800 if (IS_ERR(uuid_root)) { 4801 ret = PTR_ERR(uuid_root); 4802 btrfs_abort_transaction(trans, ret); 4803 btrfs_end_transaction(trans); 4804 return ret; 4805 } 4806 4807 fs_info->uuid_root = uuid_root; 4808 4809 ret = btrfs_commit_transaction(trans); 4810 if (ret) 4811 return ret; 4812 4813 down(&fs_info->uuid_tree_rescan_sem); 4814 task = kthread_run(btrfs_uuid_scan_kthread, fs_info, "btrfs-uuid"); 4815 if (IS_ERR(task)) { 4816 /* fs_info->update_uuid_tree_gen remains 0 in all error case */ 4817 btrfs_warn(fs_info, "failed to start uuid_scan task"); 4818 up(&fs_info->uuid_tree_rescan_sem); 4819 return PTR_ERR(task); 4820 } 4821 4822 return 0; 4823 } 4824 4825 /* 4826 * shrinking a device means finding all of the device extents past 4827 * the new size, and then following the back refs to the chunks. 4828 * The chunk relocation code actually frees the device extent 4829 */ 4830 int btrfs_shrink_device(struct btrfs_device *device, u64 new_size) 4831 { 4832 struct btrfs_fs_info *fs_info = device->fs_info; 4833 struct btrfs_root *root = fs_info->dev_root; 4834 struct btrfs_trans_handle *trans; 4835 struct btrfs_dev_extent *dev_extent = NULL; 4836 struct btrfs_path *path; 4837 u64 length; 4838 u64 chunk_offset; 4839 int ret; 4840 int slot; 4841 int failed = 0; 4842 bool retried = false; 4843 struct extent_buffer *l; 4844 struct btrfs_key key; 4845 struct btrfs_super_block *super_copy = fs_info->super_copy; 4846 u64 old_total = btrfs_super_total_bytes(super_copy); 4847 u64 old_size = btrfs_device_get_total_bytes(device); 4848 u64 diff; 4849 u64 start; 4850 4851 new_size = round_down(new_size, fs_info->sectorsize); 4852 start = new_size; 4853 diff = round_down(old_size - new_size, fs_info->sectorsize); 4854 4855 if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) 4856 return -EINVAL; 4857 4858 path = btrfs_alloc_path(); 4859 if (!path) 4860 return -ENOMEM; 4861 4862 path->reada = READA_BACK; 4863 4864 trans = btrfs_start_transaction(root, 0); 4865 if (IS_ERR(trans)) { 4866 btrfs_free_path(path); 4867 return PTR_ERR(trans); 4868 } 4869 4870 mutex_lock(&fs_info->chunk_mutex); 4871 4872 btrfs_device_set_total_bytes(device, new_size); 4873 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) { 4874 device->fs_devices->total_rw_bytes -= diff; 4875 atomic64_sub(diff, &fs_info->free_chunk_space); 4876 } 4877 4878 /* 4879 * Once the device's size has been set to the new size, ensure all 4880 * in-memory chunks are synced to disk so that the loop below sees them 4881 * and relocates them accordingly. 4882 */ 4883 if (contains_pending_extent(device, &start, diff)) { 4884 mutex_unlock(&fs_info->chunk_mutex); 4885 ret = btrfs_commit_transaction(trans); 4886 if (ret) 4887 goto done; 4888 } else { 4889 mutex_unlock(&fs_info->chunk_mutex); 4890 btrfs_end_transaction(trans); 4891 } 4892 4893 again: 4894 key.objectid = device->devid; 4895 key.offset = (u64)-1; 4896 key.type = BTRFS_DEV_EXTENT_KEY; 4897 4898 do { 4899 mutex_lock(&fs_info->reclaim_bgs_lock); 4900 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0); 4901 if (ret < 0) { 4902 mutex_unlock(&fs_info->reclaim_bgs_lock); 4903 goto done; 4904 } 4905 4906 ret = btrfs_previous_item(root, path, 0, key.type); 4907 if (ret) { 4908 mutex_unlock(&fs_info->reclaim_bgs_lock); 4909 if (ret < 0) 4910 goto done; 4911 ret = 0; 4912 btrfs_release_path(path); 4913 break; 4914 } 4915 4916 l = path->nodes[0]; 4917 slot = path->slots[0]; 4918 btrfs_item_key_to_cpu(l, &key, path->slots[0]); 4919 4920 if (key.objectid != device->devid) { 4921 mutex_unlock(&fs_info->reclaim_bgs_lock); 4922 btrfs_release_path(path); 4923 break; 4924 } 4925 4926 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent); 4927 length = btrfs_dev_extent_length(l, dev_extent); 4928 4929 if (key.offset + length <= new_size) { 4930 mutex_unlock(&fs_info->reclaim_bgs_lock); 4931 btrfs_release_path(path); 4932 break; 4933 } 4934 4935 chunk_offset = btrfs_dev_extent_chunk_offset(l, dev_extent); 4936 btrfs_release_path(path); 4937 4938 /* 4939 * We may be relocating the only data chunk we have, 4940 * which could potentially end up with losing data's 4941 * raid profile, so lets allocate an empty one in 4942 * advance. 4943 */ 4944 ret = btrfs_may_alloc_data_chunk(fs_info, chunk_offset); 4945 if (ret < 0) { 4946 mutex_unlock(&fs_info->reclaim_bgs_lock); 4947 goto done; 4948 } 4949 4950 ret = btrfs_relocate_chunk(fs_info, chunk_offset); 4951 mutex_unlock(&fs_info->reclaim_bgs_lock); 4952 if (ret == -ENOSPC) { 4953 failed++; 4954 } else if (ret) { 4955 if (ret == -ETXTBSY) { 4956 btrfs_warn(fs_info, 4957 "could not shrink block group %llu due to active swapfile", 4958 chunk_offset); 4959 } 4960 goto done; 4961 } 4962 } while (key.offset-- > 0); 4963 4964 if (failed && !retried) { 4965 failed = 0; 4966 retried = true; 4967 goto again; 4968 } else if (failed && retried) { 4969 ret = -ENOSPC; 4970 goto done; 4971 } 4972 4973 /* Shrinking succeeded, else we would be at "done". */ 4974 trans = btrfs_start_transaction(root, 0); 4975 if (IS_ERR(trans)) { 4976 ret = PTR_ERR(trans); 4977 goto done; 4978 } 4979 4980 mutex_lock(&fs_info->chunk_mutex); 4981 /* Clear all state bits beyond the shrunk device size */ 4982 clear_extent_bits(&device->alloc_state, new_size, (u64)-1, 4983 CHUNK_STATE_MASK); 4984 4985 btrfs_device_set_disk_total_bytes(device, new_size); 4986 if (list_empty(&device->post_commit_list)) 4987 list_add_tail(&device->post_commit_list, 4988 &trans->transaction->dev_update_list); 4989 4990 WARN_ON(diff > old_total); 4991 btrfs_set_super_total_bytes(super_copy, 4992 round_down(old_total - diff, fs_info->sectorsize)); 4993 mutex_unlock(&fs_info->chunk_mutex); 4994 4995 btrfs_reserve_chunk_metadata(trans, false); 4996 /* Now btrfs_update_device() will change the on-disk size. */ 4997 ret = btrfs_update_device(trans, device); 4998 btrfs_trans_release_chunk_metadata(trans); 4999 if (ret < 0) { 5000 btrfs_abort_transaction(trans, ret); 5001 btrfs_end_transaction(trans); 5002 } else { 5003 ret = btrfs_commit_transaction(trans); 5004 } 5005 done: 5006 btrfs_free_path(path); 5007 if (ret) { 5008 mutex_lock(&fs_info->chunk_mutex); 5009 btrfs_device_set_total_bytes(device, old_size); 5010 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) 5011 device->fs_devices->total_rw_bytes += diff; 5012 atomic64_add(diff, &fs_info->free_chunk_space); 5013 mutex_unlock(&fs_info->chunk_mutex); 5014 } 5015 return ret; 5016 } 5017 5018 static int btrfs_add_system_chunk(struct btrfs_fs_info *fs_info, 5019 struct btrfs_key *key, 5020 struct btrfs_chunk *chunk, int item_size) 5021 { 5022 struct btrfs_super_block *super_copy = fs_info->super_copy; 5023 struct btrfs_disk_key disk_key; 5024 u32 array_size; 5025 u8 *ptr; 5026 5027 lockdep_assert_held(&fs_info->chunk_mutex); 5028 5029 array_size = btrfs_super_sys_array_size(super_copy); 5030 if (array_size + item_size + sizeof(disk_key) 5031 > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE) 5032 return -EFBIG; 5033 5034 ptr = super_copy->sys_chunk_array + array_size; 5035 btrfs_cpu_key_to_disk(&disk_key, key); 5036 memcpy(ptr, &disk_key, sizeof(disk_key)); 5037 ptr += sizeof(disk_key); 5038 memcpy(ptr, chunk, item_size); 5039 item_size += sizeof(disk_key); 5040 btrfs_set_super_sys_array_size(super_copy, array_size + item_size); 5041 5042 return 0; 5043 } 5044 5045 /* 5046 * sort the devices in descending order by max_avail, total_avail 5047 */ 5048 static int btrfs_cmp_device_info(const void *a, const void *b) 5049 { 5050 const struct btrfs_device_info *di_a = a; 5051 const struct btrfs_device_info *di_b = b; 5052 5053 if (di_a->max_avail > di_b->max_avail) 5054 return -1; 5055 if (di_a->max_avail < di_b->max_avail) 5056 return 1; 5057 if (di_a->total_avail > di_b->total_avail) 5058 return -1; 5059 if (di_a->total_avail < di_b->total_avail) 5060 return 1; 5061 return 0; 5062 } 5063 5064 static void check_raid56_incompat_flag(struct btrfs_fs_info *info, u64 type) 5065 { 5066 if (!(type & BTRFS_BLOCK_GROUP_RAID56_MASK)) 5067 return; 5068 5069 btrfs_set_fs_incompat(info, RAID56); 5070 } 5071 5072 static void check_raid1c34_incompat_flag(struct btrfs_fs_info *info, u64 type) 5073 { 5074 if (!(type & (BTRFS_BLOCK_GROUP_RAID1C3 | BTRFS_BLOCK_GROUP_RAID1C4))) 5075 return; 5076 5077 btrfs_set_fs_incompat(info, RAID1C34); 5078 } 5079 5080 /* 5081 * Structure used internally for btrfs_create_chunk() function. 5082 * Wraps needed parameters. 5083 */ 5084 struct alloc_chunk_ctl { 5085 u64 start; 5086 u64 type; 5087 /* Total number of stripes to allocate */ 5088 int num_stripes; 5089 /* sub_stripes info for map */ 5090 int sub_stripes; 5091 /* Stripes per device */ 5092 int dev_stripes; 5093 /* Maximum number of devices to use */ 5094 int devs_max; 5095 /* Minimum number of devices to use */ 5096 int devs_min; 5097 /* ndevs has to be a multiple of this */ 5098 int devs_increment; 5099 /* Number of copies */ 5100 int ncopies; 5101 /* Number of stripes worth of bytes to store parity information */ 5102 int nparity; 5103 u64 max_stripe_size; 5104 u64 max_chunk_size; 5105 u64 dev_extent_min; 5106 u64 stripe_size; 5107 u64 chunk_size; 5108 int ndevs; 5109 }; 5110 5111 static void init_alloc_chunk_ctl_policy_regular( 5112 struct btrfs_fs_devices *fs_devices, 5113 struct alloc_chunk_ctl *ctl) 5114 { 5115 struct btrfs_space_info *space_info; 5116 5117 space_info = btrfs_find_space_info(fs_devices->fs_info, ctl->type); 5118 ASSERT(space_info); 5119 5120 ctl->max_chunk_size = READ_ONCE(space_info->chunk_size); 5121 ctl->max_stripe_size = ctl->max_chunk_size; 5122 5123 if (ctl->type & BTRFS_BLOCK_GROUP_SYSTEM) 5124 ctl->devs_max = min_t(int, ctl->devs_max, BTRFS_MAX_DEVS_SYS_CHUNK); 5125 5126 /* We don't want a chunk larger than 10% of writable space */ 5127 ctl->max_chunk_size = min(mult_perc(fs_devices->total_rw_bytes, 10), 5128 ctl->max_chunk_size); 5129 ctl->dev_extent_min = btrfs_stripe_nr_to_offset(ctl->dev_stripes); 5130 } 5131 5132 static void init_alloc_chunk_ctl_policy_zoned( 5133 struct btrfs_fs_devices *fs_devices, 5134 struct alloc_chunk_ctl *ctl) 5135 { 5136 u64 zone_size = fs_devices->fs_info->zone_size; 5137 u64 limit; 5138 int min_num_stripes = ctl->devs_min * ctl->dev_stripes; 5139 int min_data_stripes = (min_num_stripes - ctl->nparity) / ctl->ncopies; 5140 u64 min_chunk_size = min_data_stripes * zone_size; 5141 u64 type = ctl->type; 5142 5143 ctl->max_stripe_size = zone_size; 5144 if (type & BTRFS_BLOCK_GROUP_DATA) { 5145 ctl->max_chunk_size = round_down(BTRFS_MAX_DATA_CHUNK_SIZE, 5146 zone_size); 5147 } else if (type & BTRFS_BLOCK_GROUP_METADATA) { 5148 ctl->max_chunk_size = ctl->max_stripe_size; 5149 } else if (type & BTRFS_BLOCK_GROUP_SYSTEM) { 5150 ctl->max_chunk_size = 2 * ctl->max_stripe_size; 5151 ctl->devs_max = min_t(int, ctl->devs_max, 5152 BTRFS_MAX_DEVS_SYS_CHUNK); 5153 } else { 5154 BUG(); 5155 } 5156 5157 /* We don't want a chunk larger than 10% of writable space */ 5158 limit = max(round_down(mult_perc(fs_devices->total_rw_bytes, 10), 5159 zone_size), 5160 min_chunk_size); 5161 ctl->max_chunk_size = min(limit, ctl->max_chunk_size); 5162 ctl->dev_extent_min = zone_size * ctl->dev_stripes; 5163 } 5164 5165 static void init_alloc_chunk_ctl(struct btrfs_fs_devices *fs_devices, 5166 struct alloc_chunk_ctl *ctl) 5167 { 5168 int index = btrfs_bg_flags_to_raid_index(ctl->type); 5169 5170 ctl->sub_stripes = btrfs_raid_array[index].sub_stripes; 5171 ctl->dev_stripes = btrfs_raid_array[index].dev_stripes; 5172 ctl->devs_max = btrfs_raid_array[index].devs_max; 5173 if (!ctl->devs_max) 5174 ctl->devs_max = BTRFS_MAX_DEVS(fs_devices->fs_info); 5175 ctl->devs_min = btrfs_raid_array[index].devs_min; 5176 ctl->devs_increment = btrfs_raid_array[index].devs_increment; 5177 ctl->ncopies = btrfs_raid_array[index].ncopies; 5178 ctl->nparity = btrfs_raid_array[index].nparity; 5179 ctl->ndevs = 0; 5180 5181 switch (fs_devices->chunk_alloc_policy) { 5182 case BTRFS_CHUNK_ALLOC_REGULAR: 5183 init_alloc_chunk_ctl_policy_regular(fs_devices, ctl); 5184 break; 5185 case BTRFS_CHUNK_ALLOC_ZONED: 5186 init_alloc_chunk_ctl_policy_zoned(fs_devices, ctl); 5187 break; 5188 default: 5189 BUG(); 5190 } 5191 } 5192 5193 static int gather_device_info(struct btrfs_fs_devices *fs_devices, 5194 struct alloc_chunk_ctl *ctl, 5195 struct btrfs_device_info *devices_info) 5196 { 5197 struct btrfs_fs_info *info = fs_devices->fs_info; 5198 struct btrfs_device *device; 5199 u64 total_avail; 5200 u64 dev_extent_want = ctl->max_stripe_size * ctl->dev_stripes; 5201 int ret; 5202 int ndevs = 0; 5203 u64 max_avail; 5204 u64 dev_offset; 5205 5206 /* 5207 * in the first pass through the devices list, we gather information 5208 * about the available holes on each device. 5209 */ 5210 list_for_each_entry(device, &fs_devices->alloc_list, dev_alloc_list) { 5211 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) { 5212 WARN(1, KERN_ERR 5213 "BTRFS: read-only device in alloc_list\n"); 5214 continue; 5215 } 5216 5217 if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, 5218 &device->dev_state) || 5219 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) 5220 continue; 5221 5222 if (device->total_bytes > device->bytes_used) 5223 total_avail = device->total_bytes - device->bytes_used; 5224 else 5225 total_avail = 0; 5226 5227 /* If there is no space on this device, skip it. */ 5228 if (total_avail < ctl->dev_extent_min) 5229 continue; 5230 5231 ret = find_free_dev_extent(device, dev_extent_want, &dev_offset, 5232 &max_avail); 5233 if (ret && ret != -ENOSPC) 5234 return ret; 5235 5236 if (ret == 0) 5237 max_avail = dev_extent_want; 5238 5239 if (max_avail < ctl->dev_extent_min) { 5240 if (btrfs_test_opt(info, ENOSPC_DEBUG)) 5241 btrfs_debug(info, 5242 "%s: devid %llu has no free space, have=%llu want=%llu", 5243 __func__, device->devid, max_avail, 5244 ctl->dev_extent_min); 5245 continue; 5246 } 5247 5248 if (ndevs == fs_devices->rw_devices) { 5249 WARN(1, "%s: found more than %llu devices\n", 5250 __func__, fs_devices->rw_devices); 5251 break; 5252 } 5253 devices_info[ndevs].dev_offset = dev_offset; 5254 devices_info[ndevs].max_avail = max_avail; 5255 devices_info[ndevs].total_avail = total_avail; 5256 devices_info[ndevs].dev = device; 5257 ++ndevs; 5258 } 5259 ctl->ndevs = ndevs; 5260 5261 /* 5262 * now sort the devices by hole size / available space 5263 */ 5264 sort(devices_info, ndevs, sizeof(struct btrfs_device_info), 5265 btrfs_cmp_device_info, NULL); 5266 5267 return 0; 5268 } 5269 5270 static int decide_stripe_size_regular(struct alloc_chunk_ctl *ctl, 5271 struct btrfs_device_info *devices_info) 5272 { 5273 /* Number of stripes that count for block group size */ 5274 int data_stripes; 5275 5276 /* 5277 * The primary goal is to maximize the number of stripes, so use as 5278 * many devices as possible, even if the stripes are not maximum sized. 5279 * 5280 * The DUP profile stores more than one stripe per device, the 5281 * max_avail is the total size so we have to adjust. 5282 */ 5283 ctl->stripe_size = div_u64(devices_info[ctl->ndevs - 1].max_avail, 5284 ctl->dev_stripes); 5285 ctl->num_stripes = ctl->ndevs * ctl->dev_stripes; 5286 5287 /* This will have to be fixed for RAID1 and RAID10 over more drives */ 5288 data_stripes = (ctl->num_stripes - ctl->nparity) / ctl->ncopies; 5289 5290 /* 5291 * Use the number of data stripes to figure out how big this chunk is 5292 * really going to be in terms of logical address space, and compare 5293 * that answer with the max chunk size. If it's higher, we try to 5294 * reduce stripe_size. 5295 */ 5296 if (ctl->stripe_size * data_stripes > ctl->max_chunk_size) { 5297 /* 5298 * Reduce stripe_size, round it up to a 16MB boundary again and 5299 * then use it, unless it ends up being even bigger than the 5300 * previous value we had already. 5301 */ 5302 ctl->stripe_size = min(round_up(div_u64(ctl->max_chunk_size, 5303 data_stripes), SZ_16M), 5304 ctl->stripe_size); 5305 } 5306 5307 /* Stripe size should not go beyond 1G. */ 5308 ctl->stripe_size = min_t(u64, ctl->stripe_size, SZ_1G); 5309 5310 /* Align to BTRFS_STRIPE_LEN */ 5311 ctl->stripe_size = round_down(ctl->stripe_size, BTRFS_STRIPE_LEN); 5312 ctl->chunk_size = ctl->stripe_size * data_stripes; 5313 5314 return 0; 5315 } 5316 5317 static int decide_stripe_size_zoned(struct alloc_chunk_ctl *ctl, 5318 struct btrfs_device_info *devices_info) 5319 { 5320 u64 zone_size = devices_info[0].dev->zone_info->zone_size; 5321 /* Number of stripes that count for block group size */ 5322 int data_stripes; 5323 5324 /* 5325 * It should hold because: 5326 * dev_extent_min == dev_extent_want == zone_size * dev_stripes 5327 */ 5328 ASSERT(devices_info[ctl->ndevs - 1].max_avail == ctl->dev_extent_min); 5329 5330 ctl->stripe_size = zone_size; 5331 ctl->num_stripes = ctl->ndevs * ctl->dev_stripes; 5332 data_stripes = (ctl->num_stripes - ctl->nparity) / ctl->ncopies; 5333 5334 /* stripe_size is fixed in zoned filesysmte. Reduce ndevs instead. */ 5335 if (ctl->stripe_size * data_stripes > ctl->max_chunk_size) { 5336 ctl->ndevs = div_u64(div_u64(ctl->max_chunk_size * ctl->ncopies, 5337 ctl->stripe_size) + ctl->nparity, 5338 ctl->dev_stripes); 5339 ctl->num_stripes = ctl->ndevs * ctl->dev_stripes; 5340 data_stripes = (ctl->num_stripes - ctl->nparity) / ctl->ncopies; 5341 ASSERT(ctl->stripe_size * data_stripes <= ctl->max_chunk_size); 5342 } 5343 5344 ctl->chunk_size = ctl->stripe_size * data_stripes; 5345 5346 return 0; 5347 } 5348 5349 static int decide_stripe_size(struct btrfs_fs_devices *fs_devices, 5350 struct alloc_chunk_ctl *ctl, 5351 struct btrfs_device_info *devices_info) 5352 { 5353 struct btrfs_fs_info *info = fs_devices->fs_info; 5354 5355 /* 5356 * Round down to number of usable stripes, devs_increment can be any 5357 * number so we can't use round_down() that requires power of 2, while 5358 * rounddown is safe. 5359 */ 5360 ctl->ndevs = rounddown(ctl->ndevs, ctl->devs_increment); 5361 5362 if (ctl->ndevs < ctl->devs_min) { 5363 if (btrfs_test_opt(info, ENOSPC_DEBUG)) { 5364 btrfs_debug(info, 5365 "%s: not enough devices with free space: have=%d minimum required=%d", 5366 __func__, ctl->ndevs, ctl->devs_min); 5367 } 5368 return -ENOSPC; 5369 } 5370 5371 ctl->ndevs = min(ctl->ndevs, ctl->devs_max); 5372 5373 switch (fs_devices->chunk_alloc_policy) { 5374 case BTRFS_CHUNK_ALLOC_REGULAR: 5375 return decide_stripe_size_regular(ctl, devices_info); 5376 case BTRFS_CHUNK_ALLOC_ZONED: 5377 return decide_stripe_size_zoned(ctl, devices_info); 5378 default: 5379 BUG(); 5380 } 5381 } 5382 5383 static struct btrfs_block_group *create_chunk(struct btrfs_trans_handle *trans, 5384 struct alloc_chunk_ctl *ctl, 5385 struct btrfs_device_info *devices_info) 5386 { 5387 struct btrfs_fs_info *info = trans->fs_info; 5388 struct map_lookup *map = NULL; 5389 struct extent_map_tree *em_tree; 5390 struct btrfs_block_group *block_group; 5391 struct extent_map *em; 5392 u64 start = ctl->start; 5393 u64 type = ctl->type; 5394 int ret; 5395 int i; 5396 int j; 5397 5398 map = kmalloc(map_lookup_size(ctl->num_stripes), GFP_NOFS); 5399 if (!map) 5400 return ERR_PTR(-ENOMEM); 5401 map->num_stripes = ctl->num_stripes; 5402 5403 for (i = 0; i < ctl->ndevs; ++i) { 5404 for (j = 0; j < ctl->dev_stripes; ++j) { 5405 int s = i * ctl->dev_stripes + j; 5406 map->stripes[s].dev = devices_info[i].dev; 5407 map->stripes[s].physical = devices_info[i].dev_offset + 5408 j * ctl->stripe_size; 5409 } 5410 } 5411 map->io_align = BTRFS_STRIPE_LEN; 5412 map->io_width = BTRFS_STRIPE_LEN; 5413 map->type = type; 5414 map->sub_stripes = ctl->sub_stripes; 5415 5416 trace_btrfs_chunk_alloc(info, map, start, ctl->chunk_size); 5417 5418 em = alloc_extent_map(); 5419 if (!em) { 5420 kfree(map); 5421 return ERR_PTR(-ENOMEM); 5422 } 5423 set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags); 5424 em->map_lookup = map; 5425 em->start = start; 5426 em->len = ctl->chunk_size; 5427 em->block_start = 0; 5428 em->block_len = em->len; 5429 em->orig_block_len = ctl->stripe_size; 5430 5431 em_tree = &info->mapping_tree; 5432 write_lock(&em_tree->lock); 5433 ret = add_extent_mapping(em_tree, em, 0); 5434 if (ret) { 5435 write_unlock(&em_tree->lock); 5436 free_extent_map(em); 5437 return ERR_PTR(ret); 5438 } 5439 write_unlock(&em_tree->lock); 5440 5441 block_group = btrfs_make_block_group(trans, type, start, ctl->chunk_size); 5442 if (IS_ERR(block_group)) 5443 goto error_del_extent; 5444 5445 for (i = 0; i < map->num_stripes; i++) { 5446 struct btrfs_device *dev = map->stripes[i].dev; 5447 5448 btrfs_device_set_bytes_used(dev, 5449 dev->bytes_used + ctl->stripe_size); 5450 if (list_empty(&dev->post_commit_list)) 5451 list_add_tail(&dev->post_commit_list, 5452 &trans->transaction->dev_update_list); 5453 } 5454 5455 atomic64_sub(ctl->stripe_size * map->num_stripes, 5456 &info->free_chunk_space); 5457 5458 free_extent_map(em); 5459 check_raid56_incompat_flag(info, type); 5460 check_raid1c34_incompat_flag(info, type); 5461 5462 return block_group; 5463 5464 error_del_extent: 5465 write_lock(&em_tree->lock); 5466 remove_extent_mapping(em_tree, em); 5467 write_unlock(&em_tree->lock); 5468 5469 /* One for our allocation */ 5470 free_extent_map(em); 5471 /* One for the tree reference */ 5472 free_extent_map(em); 5473 5474 return block_group; 5475 } 5476 5477 struct btrfs_block_group *btrfs_create_chunk(struct btrfs_trans_handle *trans, 5478 u64 type) 5479 { 5480 struct btrfs_fs_info *info = trans->fs_info; 5481 struct btrfs_fs_devices *fs_devices = info->fs_devices; 5482 struct btrfs_device_info *devices_info = NULL; 5483 struct alloc_chunk_ctl ctl; 5484 struct btrfs_block_group *block_group; 5485 int ret; 5486 5487 lockdep_assert_held(&info->chunk_mutex); 5488 5489 if (!alloc_profile_is_valid(type, 0)) { 5490 ASSERT(0); 5491 return ERR_PTR(-EINVAL); 5492 } 5493 5494 if (list_empty(&fs_devices->alloc_list)) { 5495 if (btrfs_test_opt(info, ENOSPC_DEBUG)) 5496 btrfs_debug(info, "%s: no writable device", __func__); 5497 return ERR_PTR(-ENOSPC); 5498 } 5499 5500 if (!(type & BTRFS_BLOCK_GROUP_TYPE_MASK)) { 5501 btrfs_err(info, "invalid chunk type 0x%llx requested", type); 5502 ASSERT(0); 5503 return ERR_PTR(-EINVAL); 5504 } 5505 5506 ctl.start = find_next_chunk(info); 5507 ctl.type = type; 5508 init_alloc_chunk_ctl(fs_devices, &ctl); 5509 5510 devices_info = kcalloc(fs_devices->rw_devices, sizeof(*devices_info), 5511 GFP_NOFS); 5512 if (!devices_info) 5513 return ERR_PTR(-ENOMEM); 5514 5515 ret = gather_device_info(fs_devices, &ctl, devices_info); 5516 if (ret < 0) { 5517 block_group = ERR_PTR(ret); 5518 goto out; 5519 } 5520 5521 ret = decide_stripe_size(fs_devices, &ctl, devices_info); 5522 if (ret < 0) { 5523 block_group = ERR_PTR(ret); 5524 goto out; 5525 } 5526 5527 block_group = create_chunk(trans, &ctl, devices_info); 5528 5529 out: 5530 kfree(devices_info); 5531 return block_group; 5532 } 5533 5534 /* 5535 * This function, btrfs_chunk_alloc_add_chunk_item(), typically belongs to the 5536 * phase 1 of chunk allocation. It belongs to phase 2 only when allocating system 5537 * chunks. 5538 * 5539 * See the comment at btrfs_chunk_alloc() for details about the chunk allocation 5540 * phases. 5541 */ 5542 int btrfs_chunk_alloc_add_chunk_item(struct btrfs_trans_handle *trans, 5543 struct btrfs_block_group *bg) 5544 { 5545 struct btrfs_fs_info *fs_info = trans->fs_info; 5546 struct btrfs_root *chunk_root = fs_info->chunk_root; 5547 struct btrfs_key key; 5548 struct btrfs_chunk *chunk; 5549 struct btrfs_stripe *stripe; 5550 struct extent_map *em; 5551 struct map_lookup *map; 5552 size_t item_size; 5553 int i; 5554 int ret; 5555 5556 /* 5557 * We take the chunk_mutex for 2 reasons: 5558 * 5559 * 1) Updates and insertions in the chunk btree must be done while holding 5560 * the chunk_mutex, as well as updating the system chunk array in the 5561 * superblock. See the comment on top of btrfs_chunk_alloc() for the 5562 * details; 5563 * 5564 * 2) To prevent races with the final phase of a device replace operation 5565 * that replaces the device object associated with the map's stripes, 5566 * because the device object's id can change at any time during that 5567 * final phase of the device replace operation 5568 * (dev-replace.c:btrfs_dev_replace_finishing()), so we could grab the 5569 * replaced device and then see it with an ID of BTRFS_DEV_REPLACE_DEVID, 5570 * which would cause a failure when updating the device item, which does 5571 * not exists, or persisting a stripe of the chunk item with such ID. 5572 * Here we can't use the device_list_mutex because our caller already 5573 * has locked the chunk_mutex, and the final phase of device replace 5574 * acquires both mutexes - first the device_list_mutex and then the 5575 * chunk_mutex. Using any of those two mutexes protects us from a 5576 * concurrent device replace. 5577 */ 5578 lockdep_assert_held(&fs_info->chunk_mutex); 5579 5580 em = btrfs_get_chunk_map(fs_info, bg->start, bg->length); 5581 if (IS_ERR(em)) { 5582 ret = PTR_ERR(em); 5583 btrfs_abort_transaction(trans, ret); 5584 return ret; 5585 } 5586 5587 map = em->map_lookup; 5588 item_size = btrfs_chunk_item_size(map->num_stripes); 5589 5590 chunk = kzalloc(item_size, GFP_NOFS); 5591 if (!chunk) { 5592 ret = -ENOMEM; 5593 btrfs_abort_transaction(trans, ret); 5594 goto out; 5595 } 5596 5597 for (i = 0; i < map->num_stripes; i++) { 5598 struct btrfs_device *device = map->stripes[i].dev; 5599 5600 ret = btrfs_update_device(trans, device); 5601 if (ret) 5602 goto out; 5603 } 5604 5605 stripe = &chunk->stripe; 5606 for (i = 0; i < map->num_stripes; i++) { 5607 struct btrfs_device *device = map->stripes[i].dev; 5608 const u64 dev_offset = map->stripes[i].physical; 5609 5610 btrfs_set_stack_stripe_devid(stripe, device->devid); 5611 btrfs_set_stack_stripe_offset(stripe, dev_offset); 5612 memcpy(stripe->dev_uuid, device->uuid, BTRFS_UUID_SIZE); 5613 stripe++; 5614 } 5615 5616 btrfs_set_stack_chunk_length(chunk, bg->length); 5617 btrfs_set_stack_chunk_owner(chunk, BTRFS_EXTENT_TREE_OBJECTID); 5618 btrfs_set_stack_chunk_stripe_len(chunk, BTRFS_STRIPE_LEN); 5619 btrfs_set_stack_chunk_type(chunk, map->type); 5620 btrfs_set_stack_chunk_num_stripes(chunk, map->num_stripes); 5621 btrfs_set_stack_chunk_io_align(chunk, BTRFS_STRIPE_LEN); 5622 btrfs_set_stack_chunk_io_width(chunk, BTRFS_STRIPE_LEN); 5623 btrfs_set_stack_chunk_sector_size(chunk, fs_info->sectorsize); 5624 btrfs_set_stack_chunk_sub_stripes(chunk, map->sub_stripes); 5625 5626 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID; 5627 key.type = BTRFS_CHUNK_ITEM_KEY; 5628 key.offset = bg->start; 5629 5630 ret = btrfs_insert_item(trans, chunk_root, &key, chunk, item_size); 5631 if (ret) 5632 goto out; 5633 5634 set_bit(BLOCK_GROUP_FLAG_CHUNK_ITEM_INSERTED, &bg->runtime_flags); 5635 5636 if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) { 5637 ret = btrfs_add_system_chunk(fs_info, &key, chunk, item_size); 5638 if (ret) 5639 goto out; 5640 } 5641 5642 out: 5643 kfree(chunk); 5644 free_extent_map(em); 5645 return ret; 5646 } 5647 5648 static noinline int init_first_rw_device(struct btrfs_trans_handle *trans) 5649 { 5650 struct btrfs_fs_info *fs_info = trans->fs_info; 5651 u64 alloc_profile; 5652 struct btrfs_block_group *meta_bg; 5653 struct btrfs_block_group *sys_bg; 5654 5655 /* 5656 * When adding a new device for sprouting, the seed device is read-only 5657 * so we must first allocate a metadata and a system chunk. But before 5658 * adding the block group items to the extent, device and chunk btrees, 5659 * we must first: 5660 * 5661 * 1) Create both chunks without doing any changes to the btrees, as 5662 * otherwise we would get -ENOSPC since the block groups from the 5663 * seed device are read-only; 5664 * 5665 * 2) Add the device item for the new sprout device - finishing the setup 5666 * of a new block group requires updating the device item in the chunk 5667 * btree, so it must exist when we attempt to do it. The previous step 5668 * ensures this does not fail with -ENOSPC. 5669 * 5670 * After that we can add the block group items to their btrees: 5671 * update existing device item in the chunk btree, add a new block group 5672 * item to the extent btree, add a new chunk item to the chunk btree and 5673 * finally add the new device extent items to the devices btree. 5674 */ 5675 5676 alloc_profile = btrfs_metadata_alloc_profile(fs_info); 5677 meta_bg = btrfs_create_chunk(trans, alloc_profile); 5678 if (IS_ERR(meta_bg)) 5679 return PTR_ERR(meta_bg); 5680 5681 alloc_profile = btrfs_system_alloc_profile(fs_info); 5682 sys_bg = btrfs_create_chunk(trans, alloc_profile); 5683 if (IS_ERR(sys_bg)) 5684 return PTR_ERR(sys_bg); 5685 5686 return 0; 5687 } 5688 5689 static inline int btrfs_chunk_max_errors(struct map_lookup *map) 5690 { 5691 const int index = btrfs_bg_flags_to_raid_index(map->type); 5692 5693 return btrfs_raid_array[index].tolerated_failures; 5694 } 5695 5696 bool btrfs_chunk_writeable(struct btrfs_fs_info *fs_info, u64 chunk_offset) 5697 { 5698 struct extent_map *em; 5699 struct map_lookup *map; 5700 int miss_ndevs = 0; 5701 int i; 5702 bool ret = true; 5703 5704 em = btrfs_get_chunk_map(fs_info, chunk_offset, 1); 5705 if (IS_ERR(em)) 5706 return false; 5707 5708 map = em->map_lookup; 5709 for (i = 0; i < map->num_stripes; i++) { 5710 if (test_bit(BTRFS_DEV_STATE_MISSING, 5711 &map->stripes[i].dev->dev_state)) { 5712 miss_ndevs++; 5713 continue; 5714 } 5715 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, 5716 &map->stripes[i].dev->dev_state)) { 5717 ret = false; 5718 goto end; 5719 } 5720 } 5721 5722 /* 5723 * If the number of missing devices is larger than max errors, we can 5724 * not write the data into that chunk successfully. 5725 */ 5726 if (miss_ndevs > btrfs_chunk_max_errors(map)) 5727 ret = false; 5728 end: 5729 free_extent_map(em); 5730 return ret; 5731 } 5732 5733 void btrfs_mapping_tree_free(struct extent_map_tree *tree) 5734 { 5735 struct extent_map *em; 5736 5737 while (1) { 5738 write_lock(&tree->lock); 5739 em = lookup_extent_mapping(tree, 0, (u64)-1); 5740 if (em) 5741 remove_extent_mapping(tree, em); 5742 write_unlock(&tree->lock); 5743 if (!em) 5744 break; 5745 /* once for us */ 5746 free_extent_map(em); 5747 /* once for the tree */ 5748 free_extent_map(em); 5749 } 5750 } 5751 5752 int btrfs_num_copies(struct btrfs_fs_info *fs_info, u64 logical, u64 len) 5753 { 5754 struct extent_map *em; 5755 struct map_lookup *map; 5756 enum btrfs_raid_types index; 5757 int ret = 1; 5758 5759 em = btrfs_get_chunk_map(fs_info, logical, len); 5760 if (IS_ERR(em)) 5761 /* 5762 * We could return errors for these cases, but that could get 5763 * ugly and we'd probably do the same thing which is just not do 5764 * anything else and exit, so return 1 so the callers don't try 5765 * to use other copies. 5766 */ 5767 return 1; 5768 5769 map = em->map_lookup; 5770 index = btrfs_bg_flags_to_raid_index(map->type); 5771 5772 /* Non-RAID56, use their ncopies from btrfs_raid_array. */ 5773 if (!(map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)) 5774 ret = btrfs_raid_array[index].ncopies; 5775 else if (map->type & BTRFS_BLOCK_GROUP_RAID5) 5776 ret = 2; 5777 else if (map->type & BTRFS_BLOCK_GROUP_RAID6) 5778 /* 5779 * There could be two corrupted data stripes, we need 5780 * to loop retry in order to rebuild the correct data. 5781 * 5782 * Fail a stripe at a time on every retry except the 5783 * stripe under reconstruction. 5784 */ 5785 ret = map->num_stripes; 5786 free_extent_map(em); 5787 return ret; 5788 } 5789 5790 unsigned long btrfs_full_stripe_len(struct btrfs_fs_info *fs_info, 5791 u64 logical) 5792 { 5793 struct extent_map *em; 5794 struct map_lookup *map; 5795 unsigned long len = fs_info->sectorsize; 5796 5797 if (!btrfs_fs_incompat(fs_info, RAID56)) 5798 return len; 5799 5800 em = btrfs_get_chunk_map(fs_info, logical, len); 5801 5802 if (!WARN_ON(IS_ERR(em))) { 5803 map = em->map_lookup; 5804 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) 5805 len = btrfs_stripe_nr_to_offset(nr_data_stripes(map)); 5806 free_extent_map(em); 5807 } 5808 return len; 5809 } 5810 5811 int btrfs_is_parity_mirror(struct btrfs_fs_info *fs_info, u64 logical, u64 len) 5812 { 5813 struct extent_map *em; 5814 struct map_lookup *map; 5815 int ret = 0; 5816 5817 if (!btrfs_fs_incompat(fs_info, RAID56)) 5818 return 0; 5819 5820 em = btrfs_get_chunk_map(fs_info, logical, len); 5821 5822 if(!WARN_ON(IS_ERR(em))) { 5823 map = em->map_lookup; 5824 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) 5825 ret = 1; 5826 free_extent_map(em); 5827 } 5828 return ret; 5829 } 5830 5831 static int find_live_mirror(struct btrfs_fs_info *fs_info, 5832 struct map_lookup *map, int first, 5833 int dev_replace_is_ongoing) 5834 { 5835 int i; 5836 int num_stripes; 5837 int preferred_mirror; 5838 int tolerance; 5839 struct btrfs_device *srcdev; 5840 5841 ASSERT((map->type & 5842 (BTRFS_BLOCK_GROUP_RAID1_MASK | BTRFS_BLOCK_GROUP_RAID10))); 5843 5844 if (map->type & BTRFS_BLOCK_GROUP_RAID10) 5845 num_stripes = map->sub_stripes; 5846 else 5847 num_stripes = map->num_stripes; 5848 5849 switch (fs_info->fs_devices->read_policy) { 5850 default: 5851 /* Shouldn't happen, just warn and use pid instead of failing */ 5852 btrfs_warn_rl(fs_info, 5853 "unknown read_policy type %u, reset to pid", 5854 fs_info->fs_devices->read_policy); 5855 fs_info->fs_devices->read_policy = BTRFS_READ_POLICY_PID; 5856 fallthrough; 5857 case BTRFS_READ_POLICY_PID: 5858 preferred_mirror = first + (current->pid % num_stripes); 5859 break; 5860 } 5861 5862 if (dev_replace_is_ongoing && 5863 fs_info->dev_replace.cont_reading_from_srcdev_mode == 5864 BTRFS_DEV_REPLACE_ITEM_CONT_READING_FROM_SRCDEV_MODE_AVOID) 5865 srcdev = fs_info->dev_replace.srcdev; 5866 else 5867 srcdev = NULL; 5868 5869 /* 5870 * try to avoid the drive that is the source drive for a 5871 * dev-replace procedure, only choose it if no other non-missing 5872 * mirror is available 5873 */ 5874 for (tolerance = 0; tolerance < 2; tolerance++) { 5875 if (map->stripes[preferred_mirror].dev->bdev && 5876 (tolerance || map->stripes[preferred_mirror].dev != srcdev)) 5877 return preferred_mirror; 5878 for (i = first; i < first + num_stripes; i++) { 5879 if (map->stripes[i].dev->bdev && 5880 (tolerance || map->stripes[i].dev != srcdev)) 5881 return i; 5882 } 5883 } 5884 5885 /* we couldn't find one that doesn't fail. Just return something 5886 * and the io error handling code will clean up eventually 5887 */ 5888 return preferred_mirror; 5889 } 5890 5891 static struct btrfs_io_context *alloc_btrfs_io_context(struct btrfs_fs_info *fs_info, 5892 u16 total_stripes) 5893 { 5894 struct btrfs_io_context *bioc; 5895 5896 bioc = kzalloc( 5897 /* The size of btrfs_io_context */ 5898 sizeof(struct btrfs_io_context) + 5899 /* Plus the variable array for the stripes */ 5900 sizeof(struct btrfs_io_stripe) * (total_stripes), 5901 GFP_NOFS); 5902 5903 if (!bioc) 5904 return NULL; 5905 5906 refcount_set(&bioc->refs, 1); 5907 5908 bioc->fs_info = fs_info; 5909 bioc->replace_stripe_src = -1; 5910 bioc->full_stripe_logical = (u64)-1; 5911 5912 return bioc; 5913 } 5914 5915 void btrfs_get_bioc(struct btrfs_io_context *bioc) 5916 { 5917 WARN_ON(!refcount_read(&bioc->refs)); 5918 refcount_inc(&bioc->refs); 5919 } 5920 5921 void btrfs_put_bioc(struct btrfs_io_context *bioc) 5922 { 5923 if (!bioc) 5924 return; 5925 if (refcount_dec_and_test(&bioc->refs)) 5926 kfree(bioc); 5927 } 5928 5929 /* 5930 * Please note that, discard won't be sent to target device of device 5931 * replace. 5932 */ 5933 struct btrfs_discard_stripe *btrfs_map_discard(struct btrfs_fs_info *fs_info, 5934 u64 logical, u64 *length_ret, 5935 u32 *num_stripes) 5936 { 5937 struct extent_map *em; 5938 struct map_lookup *map; 5939 struct btrfs_discard_stripe *stripes; 5940 u64 length = *length_ret; 5941 u64 offset; 5942 u32 stripe_nr; 5943 u32 stripe_nr_end; 5944 u32 stripe_cnt; 5945 u64 stripe_end_offset; 5946 u64 stripe_offset; 5947 u32 stripe_index; 5948 u32 factor = 0; 5949 u32 sub_stripes = 0; 5950 u32 stripes_per_dev = 0; 5951 u32 remaining_stripes = 0; 5952 u32 last_stripe = 0; 5953 int ret; 5954 int i; 5955 5956 em = btrfs_get_chunk_map(fs_info, logical, length); 5957 if (IS_ERR(em)) 5958 return ERR_CAST(em); 5959 5960 map = em->map_lookup; 5961 5962 /* we don't discard raid56 yet */ 5963 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) { 5964 ret = -EOPNOTSUPP; 5965 goto out_free_map; 5966 } 5967 5968 offset = logical - em->start; 5969 length = min_t(u64, em->start + em->len - logical, length); 5970 *length_ret = length; 5971 5972 /* 5973 * stripe_nr counts the total number of stripes we have to stride 5974 * to get to this block 5975 */ 5976 stripe_nr = offset >> BTRFS_STRIPE_LEN_SHIFT; 5977 5978 /* stripe_offset is the offset of this block in its stripe */ 5979 stripe_offset = offset - btrfs_stripe_nr_to_offset(stripe_nr); 5980 5981 stripe_nr_end = round_up(offset + length, BTRFS_STRIPE_LEN) >> 5982 BTRFS_STRIPE_LEN_SHIFT; 5983 stripe_cnt = stripe_nr_end - stripe_nr; 5984 stripe_end_offset = btrfs_stripe_nr_to_offset(stripe_nr_end) - 5985 (offset + length); 5986 /* 5987 * after this, stripe_nr is the number of stripes on this 5988 * device we have to walk to find the data, and stripe_index is 5989 * the number of our device in the stripe array 5990 */ 5991 *num_stripes = 1; 5992 stripe_index = 0; 5993 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 | 5994 BTRFS_BLOCK_GROUP_RAID10)) { 5995 if (map->type & BTRFS_BLOCK_GROUP_RAID0) 5996 sub_stripes = 1; 5997 else 5998 sub_stripes = map->sub_stripes; 5999 6000 factor = map->num_stripes / sub_stripes; 6001 *num_stripes = min_t(u64, map->num_stripes, 6002 sub_stripes * stripe_cnt); 6003 stripe_index = stripe_nr % factor; 6004 stripe_nr /= factor; 6005 stripe_index *= sub_stripes; 6006 6007 remaining_stripes = stripe_cnt % factor; 6008 stripes_per_dev = stripe_cnt / factor; 6009 last_stripe = ((stripe_nr_end - 1) % factor) * sub_stripes; 6010 } else if (map->type & (BTRFS_BLOCK_GROUP_RAID1_MASK | 6011 BTRFS_BLOCK_GROUP_DUP)) { 6012 *num_stripes = map->num_stripes; 6013 } else { 6014 stripe_index = stripe_nr % map->num_stripes; 6015 stripe_nr /= map->num_stripes; 6016 } 6017 6018 stripes = kcalloc(*num_stripes, sizeof(*stripes), GFP_NOFS); 6019 if (!stripes) { 6020 ret = -ENOMEM; 6021 goto out_free_map; 6022 } 6023 6024 for (i = 0; i < *num_stripes; i++) { 6025 stripes[i].physical = 6026 map->stripes[stripe_index].physical + 6027 stripe_offset + btrfs_stripe_nr_to_offset(stripe_nr); 6028 stripes[i].dev = map->stripes[stripe_index].dev; 6029 6030 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 | 6031 BTRFS_BLOCK_GROUP_RAID10)) { 6032 stripes[i].length = btrfs_stripe_nr_to_offset(stripes_per_dev); 6033 6034 if (i / sub_stripes < remaining_stripes) 6035 stripes[i].length += BTRFS_STRIPE_LEN; 6036 6037 /* 6038 * Special for the first stripe and 6039 * the last stripe: 6040 * 6041 * |-------|...|-------| 6042 * |----------| 6043 * off end_off 6044 */ 6045 if (i < sub_stripes) 6046 stripes[i].length -= stripe_offset; 6047 6048 if (stripe_index >= last_stripe && 6049 stripe_index <= (last_stripe + 6050 sub_stripes - 1)) 6051 stripes[i].length -= stripe_end_offset; 6052 6053 if (i == sub_stripes - 1) 6054 stripe_offset = 0; 6055 } else { 6056 stripes[i].length = length; 6057 } 6058 6059 stripe_index++; 6060 if (stripe_index == map->num_stripes) { 6061 stripe_index = 0; 6062 stripe_nr++; 6063 } 6064 } 6065 6066 free_extent_map(em); 6067 return stripes; 6068 out_free_map: 6069 free_extent_map(em); 6070 return ERR_PTR(ret); 6071 } 6072 6073 static bool is_block_group_to_copy(struct btrfs_fs_info *fs_info, u64 logical) 6074 { 6075 struct btrfs_block_group *cache; 6076 bool ret; 6077 6078 /* Non zoned filesystem does not use "to_copy" flag */ 6079 if (!btrfs_is_zoned(fs_info)) 6080 return false; 6081 6082 cache = btrfs_lookup_block_group(fs_info, logical); 6083 6084 ret = test_bit(BLOCK_GROUP_FLAG_TO_COPY, &cache->runtime_flags); 6085 6086 btrfs_put_block_group(cache); 6087 return ret; 6088 } 6089 6090 static void handle_ops_on_dev_replace(enum btrfs_map_op op, 6091 struct btrfs_io_context *bioc, 6092 struct btrfs_dev_replace *dev_replace, 6093 u64 logical, 6094 int *num_stripes_ret, int *max_errors_ret) 6095 { 6096 u64 srcdev_devid = dev_replace->srcdev->devid; 6097 /* 6098 * At this stage, num_stripes is still the real number of stripes, 6099 * excluding the duplicated stripes. 6100 */ 6101 int num_stripes = *num_stripes_ret; 6102 int nr_extra_stripes = 0; 6103 int max_errors = *max_errors_ret; 6104 int i; 6105 6106 /* 6107 * A block group which has "to_copy" set will eventually be copied by 6108 * the dev-replace process. We can avoid cloning IO here. 6109 */ 6110 if (is_block_group_to_copy(dev_replace->srcdev->fs_info, logical)) 6111 return; 6112 6113 /* 6114 * Duplicate the write operations while the dev-replace procedure is 6115 * running. Since the copying of the old disk to the new disk takes 6116 * place at run time while the filesystem is mounted writable, the 6117 * regular write operations to the old disk have to be duplicated to go 6118 * to the new disk as well. 6119 * 6120 * Note that device->missing is handled by the caller, and that the 6121 * write to the old disk is already set up in the stripes array. 6122 */ 6123 for (i = 0; i < num_stripes; i++) { 6124 struct btrfs_io_stripe *old = &bioc->stripes[i]; 6125 struct btrfs_io_stripe *new = &bioc->stripes[num_stripes + nr_extra_stripes]; 6126 6127 if (old->dev->devid != srcdev_devid) 6128 continue; 6129 6130 new->physical = old->physical; 6131 new->dev = dev_replace->tgtdev; 6132 if (bioc->map_type & BTRFS_BLOCK_GROUP_RAID56_MASK) 6133 bioc->replace_stripe_src = i; 6134 nr_extra_stripes++; 6135 } 6136 6137 /* We can only have at most 2 extra nr_stripes (for DUP). */ 6138 ASSERT(nr_extra_stripes <= 2); 6139 /* 6140 * For GET_READ_MIRRORS, we can only return at most 1 extra stripe for 6141 * replace. 6142 * If we have 2 extra stripes, only choose the one with smaller physical. 6143 */ 6144 if (op == BTRFS_MAP_GET_READ_MIRRORS && nr_extra_stripes == 2) { 6145 struct btrfs_io_stripe *first = &bioc->stripes[num_stripes]; 6146 struct btrfs_io_stripe *second = &bioc->stripes[num_stripes + 1]; 6147 6148 /* Only DUP can have two extra stripes. */ 6149 ASSERT(bioc->map_type & BTRFS_BLOCK_GROUP_DUP); 6150 6151 /* 6152 * Swap the last stripe stripes and reduce @nr_extra_stripes. 6153 * The extra stripe would still be there, but won't be accessed. 6154 */ 6155 if (first->physical > second->physical) { 6156 swap(second->physical, first->physical); 6157 swap(second->dev, first->dev); 6158 nr_extra_stripes--; 6159 } 6160 } 6161 6162 *num_stripes_ret = num_stripes + nr_extra_stripes; 6163 *max_errors_ret = max_errors + nr_extra_stripes; 6164 bioc->replace_nr_stripes = nr_extra_stripes; 6165 } 6166 6167 static u64 btrfs_max_io_len(struct map_lookup *map, enum btrfs_map_op op, 6168 u64 offset, u32 *stripe_nr, u64 *stripe_offset, 6169 u64 *full_stripe_start) 6170 { 6171 /* 6172 * Stripe_nr is the stripe where this block falls. stripe_offset is 6173 * the offset of this block in its stripe. 6174 */ 6175 *stripe_offset = offset & BTRFS_STRIPE_LEN_MASK; 6176 *stripe_nr = offset >> BTRFS_STRIPE_LEN_SHIFT; 6177 ASSERT(*stripe_offset < U32_MAX); 6178 6179 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) { 6180 unsigned long full_stripe_len = 6181 btrfs_stripe_nr_to_offset(nr_data_stripes(map)); 6182 6183 /* 6184 * For full stripe start, we use previously calculated 6185 * @stripe_nr. Align it to nr_data_stripes, then multiply with 6186 * STRIPE_LEN. 6187 * 6188 * By this we can avoid u64 division completely. And we have 6189 * to go rounddown(), not round_down(), as nr_data_stripes is 6190 * not ensured to be power of 2. 6191 */ 6192 *full_stripe_start = 6193 btrfs_stripe_nr_to_offset( 6194 rounddown(*stripe_nr, nr_data_stripes(map))); 6195 6196 ASSERT(*full_stripe_start + full_stripe_len > offset); 6197 ASSERT(*full_stripe_start <= offset); 6198 /* 6199 * For writes to RAID56, allow to write a full stripe set, but 6200 * no straddling of stripe sets. 6201 */ 6202 if (op == BTRFS_MAP_WRITE) 6203 return full_stripe_len - (offset - *full_stripe_start); 6204 } 6205 6206 /* 6207 * For other RAID types and for RAID56 reads, allow a single stripe (on 6208 * a single disk). 6209 */ 6210 if (map->type & BTRFS_BLOCK_GROUP_STRIPE_MASK) 6211 return BTRFS_STRIPE_LEN - *stripe_offset; 6212 return U64_MAX; 6213 } 6214 6215 static void set_io_stripe(struct btrfs_io_stripe *dst, const struct map_lookup *map, 6216 u32 stripe_index, u64 stripe_offset, u32 stripe_nr) 6217 { 6218 dst->dev = map->stripes[stripe_index].dev; 6219 dst->physical = map->stripes[stripe_index].physical + 6220 stripe_offset + btrfs_stripe_nr_to_offset(stripe_nr); 6221 } 6222 6223 /* 6224 * Map one logical range to one or more physical ranges. 6225 * 6226 * @length: (Mandatory) mapped length of this run. 6227 * One logical range can be split into different segments 6228 * due to factors like zones and RAID0/5/6/10 stripe 6229 * boundaries. 6230 * 6231 * @bioc_ret: (Mandatory) returned btrfs_io_context structure. 6232 * which has one or more physical ranges (btrfs_io_stripe) 6233 * recorded inside. 6234 * Caller should call btrfs_put_bioc() to free it after use. 6235 * 6236 * @smap: (Optional) single physical range optimization. 6237 * If the map request can be fulfilled by one single 6238 * physical range, and this is parameter is not NULL, 6239 * then @bioc_ret would be NULL, and @smap would be 6240 * updated. 6241 * 6242 * @mirror_num_ret: (Mandatory) returned mirror number if the original 6243 * value is 0. 6244 * 6245 * Mirror number 0 means to choose any live mirrors. 6246 * 6247 * For non-RAID56 profiles, non-zero mirror_num means 6248 * the Nth mirror. (e.g. mirror_num 1 means the first 6249 * copy). 6250 * 6251 * For RAID56 profile, mirror 1 means rebuild from P and 6252 * the remaining data stripes. 6253 * 6254 * For RAID6 profile, mirror > 2 means mark another 6255 * data/P stripe error and rebuild from the remaining 6256 * stripes.. 6257 * 6258 * @need_raid_map: (Used only for integrity checker) whether the map wants 6259 * a full stripe map (including all data and P/Q stripes) 6260 * for RAID56. Should always be 1 except integrity checker. 6261 */ 6262 int btrfs_map_block(struct btrfs_fs_info *fs_info, enum btrfs_map_op op, 6263 u64 logical, u64 *length, 6264 struct btrfs_io_context **bioc_ret, 6265 struct btrfs_io_stripe *smap, int *mirror_num_ret, 6266 int need_raid_map) 6267 { 6268 struct extent_map *em; 6269 struct map_lookup *map; 6270 u64 map_offset; 6271 u64 stripe_offset; 6272 u32 stripe_nr; 6273 u32 stripe_index; 6274 int data_stripes; 6275 int i; 6276 int ret = 0; 6277 int mirror_num = (mirror_num_ret ? *mirror_num_ret : 0); 6278 int num_stripes; 6279 int num_copies; 6280 int max_errors = 0; 6281 struct btrfs_io_context *bioc = NULL; 6282 struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace; 6283 int dev_replace_is_ongoing = 0; 6284 u16 num_alloc_stripes; 6285 u64 raid56_full_stripe_start = (u64)-1; 6286 u64 max_len; 6287 6288 ASSERT(bioc_ret); 6289 6290 num_copies = btrfs_num_copies(fs_info, logical, fs_info->sectorsize); 6291 if (mirror_num > num_copies) 6292 return -EINVAL; 6293 6294 em = btrfs_get_chunk_map(fs_info, logical, *length); 6295 if (IS_ERR(em)) 6296 return PTR_ERR(em); 6297 6298 map = em->map_lookup; 6299 data_stripes = nr_data_stripes(map); 6300 6301 map_offset = logical - em->start; 6302 max_len = btrfs_max_io_len(map, op, map_offset, &stripe_nr, 6303 &stripe_offset, &raid56_full_stripe_start); 6304 *length = min_t(u64, em->len - map_offset, max_len); 6305 6306 down_read(&dev_replace->rwsem); 6307 dev_replace_is_ongoing = btrfs_dev_replace_is_ongoing(dev_replace); 6308 /* 6309 * Hold the semaphore for read during the whole operation, write is 6310 * requested at commit time but must wait. 6311 */ 6312 if (!dev_replace_is_ongoing) 6313 up_read(&dev_replace->rwsem); 6314 6315 num_stripes = 1; 6316 stripe_index = 0; 6317 if (map->type & BTRFS_BLOCK_GROUP_RAID0) { 6318 stripe_index = stripe_nr % map->num_stripes; 6319 stripe_nr /= map->num_stripes; 6320 if (op == BTRFS_MAP_READ) 6321 mirror_num = 1; 6322 } else if (map->type & BTRFS_BLOCK_GROUP_RAID1_MASK) { 6323 if (op != BTRFS_MAP_READ) { 6324 num_stripes = map->num_stripes; 6325 } else if (mirror_num) { 6326 stripe_index = mirror_num - 1; 6327 } else { 6328 stripe_index = find_live_mirror(fs_info, map, 0, 6329 dev_replace_is_ongoing); 6330 mirror_num = stripe_index + 1; 6331 } 6332 6333 } else if (map->type & BTRFS_BLOCK_GROUP_DUP) { 6334 if (op != BTRFS_MAP_READ) { 6335 num_stripes = map->num_stripes; 6336 } else if (mirror_num) { 6337 stripe_index = mirror_num - 1; 6338 } else { 6339 mirror_num = 1; 6340 } 6341 6342 } else if (map->type & BTRFS_BLOCK_GROUP_RAID10) { 6343 u32 factor = map->num_stripes / map->sub_stripes; 6344 6345 stripe_index = (stripe_nr % factor) * map->sub_stripes; 6346 stripe_nr /= factor; 6347 6348 if (op != BTRFS_MAP_READ) 6349 num_stripes = map->sub_stripes; 6350 else if (mirror_num) 6351 stripe_index += mirror_num - 1; 6352 else { 6353 int old_stripe_index = stripe_index; 6354 stripe_index = find_live_mirror(fs_info, map, 6355 stripe_index, 6356 dev_replace_is_ongoing); 6357 mirror_num = stripe_index - old_stripe_index + 1; 6358 } 6359 6360 } else if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) { 6361 if (need_raid_map && (op != BTRFS_MAP_READ || mirror_num > 1)) { 6362 /* 6363 * Push stripe_nr back to the start of the full stripe 6364 * For those cases needing a full stripe, @stripe_nr 6365 * is the full stripe number. 6366 * 6367 * Originally we go raid56_full_stripe_start / full_stripe_len, 6368 * but that can be expensive. Here we just divide 6369 * @stripe_nr with @data_stripes. 6370 */ 6371 stripe_nr /= data_stripes; 6372 6373 /* RAID[56] write or recovery. Return all stripes */ 6374 num_stripes = map->num_stripes; 6375 max_errors = btrfs_chunk_max_errors(map); 6376 6377 /* Return the length to the full stripe end */ 6378 *length = min(logical + *length, 6379 raid56_full_stripe_start + em->start + 6380 btrfs_stripe_nr_to_offset(data_stripes)) - 6381 logical; 6382 stripe_index = 0; 6383 stripe_offset = 0; 6384 } else { 6385 /* 6386 * Mirror #0 or #1 means the original data block. 6387 * Mirror #2 is RAID5 parity block. 6388 * Mirror #3 is RAID6 Q block. 6389 */ 6390 stripe_index = stripe_nr % data_stripes; 6391 stripe_nr /= data_stripes; 6392 if (mirror_num > 1) 6393 stripe_index = data_stripes + mirror_num - 2; 6394 6395 /* We distribute the parity blocks across stripes */ 6396 stripe_index = (stripe_nr + stripe_index) % map->num_stripes; 6397 if (op == BTRFS_MAP_READ && mirror_num <= 1) 6398 mirror_num = 1; 6399 } 6400 } else { 6401 /* 6402 * After this, stripe_nr is the number of stripes on this 6403 * device we have to walk to find the data, and stripe_index is 6404 * the number of our device in the stripe array 6405 */ 6406 stripe_index = stripe_nr % map->num_stripes; 6407 stripe_nr /= map->num_stripes; 6408 mirror_num = stripe_index + 1; 6409 } 6410 if (stripe_index >= map->num_stripes) { 6411 btrfs_crit(fs_info, 6412 "stripe index math went horribly wrong, got stripe_index=%u, num_stripes=%u", 6413 stripe_index, map->num_stripes); 6414 ret = -EINVAL; 6415 goto out; 6416 } 6417 6418 num_alloc_stripes = num_stripes; 6419 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL && 6420 op != BTRFS_MAP_READ) 6421 /* 6422 * For replace case, we need to add extra stripes for extra 6423 * duplicated stripes. 6424 * 6425 * For both WRITE and GET_READ_MIRRORS, we may have at most 6426 * 2 more stripes (DUP types, otherwise 1). 6427 */ 6428 num_alloc_stripes += 2; 6429 6430 /* 6431 * If this I/O maps to a single device, try to return the device and 6432 * physical block information on the stack instead of allocating an 6433 * I/O context structure. 6434 */ 6435 if (smap && num_alloc_stripes == 1 && 6436 !((map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) && mirror_num > 1)) { 6437 set_io_stripe(smap, map, stripe_index, stripe_offset, stripe_nr); 6438 if (mirror_num_ret) 6439 *mirror_num_ret = mirror_num; 6440 *bioc_ret = NULL; 6441 ret = 0; 6442 goto out; 6443 } 6444 6445 bioc = alloc_btrfs_io_context(fs_info, num_alloc_stripes); 6446 if (!bioc) { 6447 ret = -ENOMEM; 6448 goto out; 6449 } 6450 bioc->map_type = map->type; 6451 6452 /* 6453 * For RAID56 full map, we need to make sure the stripes[] follows the 6454 * rule that data stripes are all ordered, then followed with P and Q 6455 * (if we have). 6456 * 6457 * It's still mostly the same as other profiles, just with extra rotation. 6458 */ 6459 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK && need_raid_map && 6460 (op != BTRFS_MAP_READ || mirror_num > 1)) { 6461 /* 6462 * For RAID56 @stripe_nr is already the number of full stripes 6463 * before us, which is also the rotation value (needs to modulo 6464 * with num_stripes). 6465 * 6466 * In this case, we just add @stripe_nr with @i, then do the 6467 * modulo, to reduce one modulo call. 6468 */ 6469 bioc->full_stripe_logical = em->start + 6470 btrfs_stripe_nr_to_offset(stripe_nr * data_stripes); 6471 for (i = 0; i < num_stripes; i++) 6472 set_io_stripe(&bioc->stripes[i], map, 6473 (i + stripe_nr) % num_stripes, 6474 stripe_offset, stripe_nr); 6475 } else { 6476 /* 6477 * For all other non-RAID56 profiles, just copy the target 6478 * stripe into the bioc. 6479 */ 6480 for (i = 0; i < num_stripes; i++) { 6481 set_io_stripe(&bioc->stripes[i], map, stripe_index, 6482 stripe_offset, stripe_nr); 6483 stripe_index++; 6484 } 6485 } 6486 6487 if (op != BTRFS_MAP_READ) 6488 max_errors = btrfs_chunk_max_errors(map); 6489 6490 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL && 6491 op != BTRFS_MAP_READ) { 6492 handle_ops_on_dev_replace(op, bioc, dev_replace, logical, 6493 &num_stripes, &max_errors); 6494 } 6495 6496 *bioc_ret = bioc; 6497 bioc->num_stripes = num_stripes; 6498 bioc->max_errors = max_errors; 6499 bioc->mirror_num = mirror_num; 6500 6501 out: 6502 if (dev_replace_is_ongoing) { 6503 lockdep_assert_held(&dev_replace->rwsem); 6504 /* Unlock and let waiting writers proceed */ 6505 up_read(&dev_replace->rwsem); 6506 } 6507 free_extent_map(em); 6508 return ret; 6509 } 6510 6511 static bool dev_args_match_fs_devices(const struct btrfs_dev_lookup_args *args, 6512 const struct btrfs_fs_devices *fs_devices) 6513 { 6514 if (args->fsid == NULL) 6515 return true; 6516 if (memcmp(fs_devices->metadata_uuid, args->fsid, BTRFS_FSID_SIZE) == 0) 6517 return true; 6518 return false; 6519 } 6520 6521 static bool dev_args_match_device(const struct btrfs_dev_lookup_args *args, 6522 const struct btrfs_device *device) 6523 { 6524 if (args->missing) { 6525 if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state) && 6526 !device->bdev) 6527 return true; 6528 return false; 6529 } 6530 6531 if (device->devid != args->devid) 6532 return false; 6533 if (args->uuid && memcmp(device->uuid, args->uuid, BTRFS_UUID_SIZE) != 0) 6534 return false; 6535 return true; 6536 } 6537 6538 /* 6539 * Find a device specified by @devid or @uuid in the list of @fs_devices, or 6540 * return NULL. 6541 * 6542 * If devid and uuid are both specified, the match must be exact, otherwise 6543 * only devid is used. 6544 */ 6545 struct btrfs_device *btrfs_find_device(const struct btrfs_fs_devices *fs_devices, 6546 const struct btrfs_dev_lookup_args *args) 6547 { 6548 struct btrfs_device *device; 6549 struct btrfs_fs_devices *seed_devs; 6550 6551 if (dev_args_match_fs_devices(args, fs_devices)) { 6552 list_for_each_entry(device, &fs_devices->devices, dev_list) { 6553 if (dev_args_match_device(args, device)) 6554 return device; 6555 } 6556 } 6557 6558 list_for_each_entry(seed_devs, &fs_devices->seed_list, seed_list) { 6559 if (!dev_args_match_fs_devices(args, seed_devs)) 6560 continue; 6561 list_for_each_entry(device, &seed_devs->devices, dev_list) { 6562 if (dev_args_match_device(args, device)) 6563 return device; 6564 } 6565 } 6566 6567 return NULL; 6568 } 6569 6570 static struct btrfs_device *add_missing_dev(struct btrfs_fs_devices *fs_devices, 6571 u64 devid, u8 *dev_uuid) 6572 { 6573 struct btrfs_device *device; 6574 unsigned int nofs_flag; 6575 6576 /* 6577 * We call this under the chunk_mutex, so we want to use NOFS for this 6578 * allocation, however we don't want to change btrfs_alloc_device() to 6579 * always do NOFS because we use it in a lot of other GFP_KERNEL safe 6580 * places. 6581 */ 6582 6583 nofs_flag = memalloc_nofs_save(); 6584 device = btrfs_alloc_device(NULL, &devid, dev_uuid, NULL); 6585 memalloc_nofs_restore(nofs_flag); 6586 if (IS_ERR(device)) 6587 return device; 6588 6589 list_add(&device->dev_list, &fs_devices->devices); 6590 device->fs_devices = fs_devices; 6591 fs_devices->num_devices++; 6592 6593 set_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state); 6594 fs_devices->missing_devices++; 6595 6596 return device; 6597 } 6598 6599 /* 6600 * Allocate new device struct, set up devid and UUID. 6601 * 6602 * @fs_info: used only for generating a new devid, can be NULL if 6603 * devid is provided (i.e. @devid != NULL). 6604 * @devid: a pointer to devid for this device. If NULL a new devid 6605 * is generated. 6606 * @uuid: a pointer to UUID for this device. If NULL a new UUID 6607 * is generated. 6608 * @path: a pointer to device path if available, NULL otherwise. 6609 * 6610 * Return: a pointer to a new &struct btrfs_device on success; ERR_PTR() 6611 * on error. Returned struct is not linked onto any lists and must be 6612 * destroyed with btrfs_free_device. 6613 */ 6614 struct btrfs_device *btrfs_alloc_device(struct btrfs_fs_info *fs_info, 6615 const u64 *devid, const u8 *uuid, 6616 const char *path) 6617 { 6618 struct btrfs_device *dev; 6619 u64 tmp; 6620 6621 if (WARN_ON(!devid && !fs_info)) 6622 return ERR_PTR(-EINVAL); 6623 6624 dev = kzalloc(sizeof(*dev), GFP_KERNEL); 6625 if (!dev) 6626 return ERR_PTR(-ENOMEM); 6627 6628 INIT_LIST_HEAD(&dev->dev_list); 6629 INIT_LIST_HEAD(&dev->dev_alloc_list); 6630 INIT_LIST_HEAD(&dev->post_commit_list); 6631 6632 atomic_set(&dev->dev_stats_ccnt, 0); 6633 btrfs_device_data_ordered_init(dev); 6634 extent_io_tree_init(fs_info, &dev->alloc_state, IO_TREE_DEVICE_ALLOC_STATE); 6635 6636 if (devid) 6637 tmp = *devid; 6638 else { 6639 int ret; 6640 6641 ret = find_next_devid(fs_info, &tmp); 6642 if (ret) { 6643 btrfs_free_device(dev); 6644 return ERR_PTR(ret); 6645 } 6646 } 6647 dev->devid = tmp; 6648 6649 if (uuid) 6650 memcpy(dev->uuid, uuid, BTRFS_UUID_SIZE); 6651 else 6652 generate_random_uuid(dev->uuid); 6653 6654 if (path) { 6655 struct rcu_string *name; 6656 6657 name = rcu_string_strdup(path, GFP_KERNEL); 6658 if (!name) { 6659 btrfs_free_device(dev); 6660 return ERR_PTR(-ENOMEM); 6661 } 6662 rcu_assign_pointer(dev->name, name); 6663 } 6664 6665 return dev; 6666 } 6667 6668 static void btrfs_report_missing_device(struct btrfs_fs_info *fs_info, 6669 u64 devid, u8 *uuid, bool error) 6670 { 6671 if (error) 6672 btrfs_err_rl(fs_info, "devid %llu uuid %pU is missing", 6673 devid, uuid); 6674 else 6675 btrfs_warn_rl(fs_info, "devid %llu uuid %pU is missing", 6676 devid, uuid); 6677 } 6678 6679 u64 btrfs_calc_stripe_length(const struct extent_map *em) 6680 { 6681 const struct map_lookup *map = em->map_lookup; 6682 const int data_stripes = calc_data_stripes(map->type, map->num_stripes); 6683 6684 return div_u64(em->len, data_stripes); 6685 } 6686 6687 #if BITS_PER_LONG == 32 6688 /* 6689 * Due to page cache limit, metadata beyond BTRFS_32BIT_MAX_FILE_SIZE 6690 * can't be accessed on 32bit systems. 6691 * 6692 * This function do mount time check to reject the fs if it already has 6693 * metadata chunk beyond that limit. 6694 */ 6695 static int check_32bit_meta_chunk(struct btrfs_fs_info *fs_info, 6696 u64 logical, u64 length, u64 type) 6697 { 6698 if (!(type & BTRFS_BLOCK_GROUP_METADATA)) 6699 return 0; 6700 6701 if (logical + length < MAX_LFS_FILESIZE) 6702 return 0; 6703 6704 btrfs_err_32bit_limit(fs_info); 6705 return -EOVERFLOW; 6706 } 6707 6708 /* 6709 * This is to give early warning for any metadata chunk reaching 6710 * BTRFS_32BIT_EARLY_WARN_THRESHOLD. 6711 * Although we can still access the metadata, it's not going to be possible 6712 * once the limit is reached. 6713 */ 6714 static void warn_32bit_meta_chunk(struct btrfs_fs_info *fs_info, 6715 u64 logical, u64 length, u64 type) 6716 { 6717 if (!(type & BTRFS_BLOCK_GROUP_METADATA)) 6718 return; 6719 6720 if (logical + length < BTRFS_32BIT_EARLY_WARN_THRESHOLD) 6721 return; 6722 6723 btrfs_warn_32bit_limit(fs_info); 6724 } 6725 #endif 6726 6727 static struct btrfs_device *handle_missing_device(struct btrfs_fs_info *fs_info, 6728 u64 devid, u8 *uuid) 6729 { 6730 struct btrfs_device *dev; 6731 6732 if (!btrfs_test_opt(fs_info, DEGRADED)) { 6733 btrfs_report_missing_device(fs_info, devid, uuid, true); 6734 return ERR_PTR(-ENOENT); 6735 } 6736 6737 dev = add_missing_dev(fs_info->fs_devices, devid, uuid); 6738 if (IS_ERR(dev)) { 6739 btrfs_err(fs_info, "failed to init missing device %llu: %ld", 6740 devid, PTR_ERR(dev)); 6741 return dev; 6742 } 6743 btrfs_report_missing_device(fs_info, devid, uuid, false); 6744 6745 return dev; 6746 } 6747 6748 static int read_one_chunk(struct btrfs_key *key, struct extent_buffer *leaf, 6749 struct btrfs_chunk *chunk) 6750 { 6751 BTRFS_DEV_LOOKUP_ARGS(args); 6752 struct btrfs_fs_info *fs_info = leaf->fs_info; 6753 struct extent_map_tree *map_tree = &fs_info->mapping_tree; 6754 struct map_lookup *map; 6755 struct extent_map *em; 6756 u64 logical; 6757 u64 length; 6758 u64 devid; 6759 u64 type; 6760 u8 uuid[BTRFS_UUID_SIZE]; 6761 int index; 6762 int num_stripes; 6763 int ret; 6764 int i; 6765 6766 logical = key->offset; 6767 length = btrfs_chunk_length(leaf, chunk); 6768 type = btrfs_chunk_type(leaf, chunk); 6769 index = btrfs_bg_flags_to_raid_index(type); 6770 num_stripes = btrfs_chunk_num_stripes(leaf, chunk); 6771 6772 #if BITS_PER_LONG == 32 6773 ret = check_32bit_meta_chunk(fs_info, logical, length, type); 6774 if (ret < 0) 6775 return ret; 6776 warn_32bit_meta_chunk(fs_info, logical, length, type); 6777 #endif 6778 6779 /* 6780 * Only need to verify chunk item if we're reading from sys chunk array, 6781 * as chunk item in tree block is already verified by tree-checker. 6782 */ 6783 if (leaf->start == BTRFS_SUPER_INFO_OFFSET) { 6784 ret = btrfs_check_chunk_valid(leaf, chunk, logical); 6785 if (ret) 6786 return ret; 6787 } 6788 6789 read_lock(&map_tree->lock); 6790 em = lookup_extent_mapping(map_tree, logical, 1); 6791 read_unlock(&map_tree->lock); 6792 6793 /* already mapped? */ 6794 if (em && em->start <= logical && em->start + em->len > logical) { 6795 free_extent_map(em); 6796 return 0; 6797 } else if (em) { 6798 free_extent_map(em); 6799 } 6800 6801 em = alloc_extent_map(); 6802 if (!em) 6803 return -ENOMEM; 6804 map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS); 6805 if (!map) { 6806 free_extent_map(em); 6807 return -ENOMEM; 6808 } 6809 6810 set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags); 6811 em->map_lookup = map; 6812 em->start = logical; 6813 em->len = length; 6814 em->orig_start = 0; 6815 em->block_start = 0; 6816 em->block_len = em->len; 6817 6818 map->num_stripes = num_stripes; 6819 map->io_width = btrfs_chunk_io_width(leaf, chunk); 6820 map->io_align = btrfs_chunk_io_align(leaf, chunk); 6821 map->type = type; 6822 /* 6823 * We can't use the sub_stripes value, as for profiles other than 6824 * RAID10, they may have 0 as sub_stripes for filesystems created by 6825 * older mkfs (<v5.4). 6826 * In that case, it can cause divide-by-zero errors later. 6827 * Since currently sub_stripes is fixed for each profile, let's 6828 * use the trusted value instead. 6829 */ 6830 map->sub_stripes = btrfs_raid_array[index].sub_stripes; 6831 map->verified_stripes = 0; 6832 em->orig_block_len = btrfs_calc_stripe_length(em); 6833 for (i = 0; i < num_stripes; i++) { 6834 map->stripes[i].physical = 6835 btrfs_stripe_offset_nr(leaf, chunk, i); 6836 devid = btrfs_stripe_devid_nr(leaf, chunk, i); 6837 args.devid = devid; 6838 read_extent_buffer(leaf, uuid, (unsigned long) 6839 btrfs_stripe_dev_uuid_nr(chunk, i), 6840 BTRFS_UUID_SIZE); 6841 args.uuid = uuid; 6842 map->stripes[i].dev = btrfs_find_device(fs_info->fs_devices, &args); 6843 if (!map->stripes[i].dev) { 6844 map->stripes[i].dev = handle_missing_device(fs_info, 6845 devid, uuid); 6846 if (IS_ERR(map->stripes[i].dev)) { 6847 ret = PTR_ERR(map->stripes[i].dev); 6848 free_extent_map(em); 6849 return ret; 6850 } 6851 } 6852 6853 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, 6854 &(map->stripes[i].dev->dev_state)); 6855 } 6856 6857 write_lock(&map_tree->lock); 6858 ret = add_extent_mapping(map_tree, em, 0); 6859 write_unlock(&map_tree->lock); 6860 if (ret < 0) { 6861 btrfs_err(fs_info, 6862 "failed to add chunk map, start=%llu len=%llu: %d", 6863 em->start, em->len, ret); 6864 } 6865 free_extent_map(em); 6866 6867 return ret; 6868 } 6869 6870 static void fill_device_from_item(struct extent_buffer *leaf, 6871 struct btrfs_dev_item *dev_item, 6872 struct btrfs_device *device) 6873 { 6874 unsigned long ptr; 6875 6876 device->devid = btrfs_device_id(leaf, dev_item); 6877 device->disk_total_bytes = btrfs_device_total_bytes(leaf, dev_item); 6878 device->total_bytes = device->disk_total_bytes; 6879 device->commit_total_bytes = device->disk_total_bytes; 6880 device->bytes_used = btrfs_device_bytes_used(leaf, dev_item); 6881 device->commit_bytes_used = device->bytes_used; 6882 device->type = btrfs_device_type(leaf, dev_item); 6883 device->io_align = btrfs_device_io_align(leaf, dev_item); 6884 device->io_width = btrfs_device_io_width(leaf, dev_item); 6885 device->sector_size = btrfs_device_sector_size(leaf, dev_item); 6886 WARN_ON(device->devid == BTRFS_DEV_REPLACE_DEVID); 6887 clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state); 6888 6889 ptr = btrfs_device_uuid(dev_item); 6890 read_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE); 6891 } 6892 6893 static struct btrfs_fs_devices *open_seed_devices(struct btrfs_fs_info *fs_info, 6894 u8 *fsid) 6895 { 6896 struct btrfs_fs_devices *fs_devices; 6897 int ret; 6898 6899 lockdep_assert_held(&uuid_mutex); 6900 ASSERT(fsid); 6901 6902 /* This will match only for multi-device seed fs */ 6903 list_for_each_entry(fs_devices, &fs_info->fs_devices->seed_list, seed_list) 6904 if (!memcmp(fs_devices->fsid, fsid, BTRFS_FSID_SIZE)) 6905 return fs_devices; 6906 6907 6908 fs_devices = find_fsid(fsid, NULL); 6909 if (!fs_devices) { 6910 if (!btrfs_test_opt(fs_info, DEGRADED)) 6911 return ERR_PTR(-ENOENT); 6912 6913 fs_devices = alloc_fs_devices(fsid, NULL); 6914 if (IS_ERR(fs_devices)) 6915 return fs_devices; 6916 6917 fs_devices->seeding = true; 6918 fs_devices->opened = 1; 6919 return fs_devices; 6920 } 6921 6922 /* 6923 * Upon first call for a seed fs fsid, just create a private copy of the 6924 * respective fs_devices and anchor it at fs_info->fs_devices->seed_list 6925 */ 6926 fs_devices = clone_fs_devices(fs_devices); 6927 if (IS_ERR(fs_devices)) 6928 return fs_devices; 6929 6930 ret = open_fs_devices(fs_devices, BLK_OPEN_READ, fs_info->bdev_holder); 6931 if (ret) { 6932 free_fs_devices(fs_devices); 6933 return ERR_PTR(ret); 6934 } 6935 6936 if (!fs_devices->seeding) { 6937 close_fs_devices(fs_devices); 6938 free_fs_devices(fs_devices); 6939 return ERR_PTR(-EINVAL); 6940 } 6941 6942 list_add(&fs_devices->seed_list, &fs_info->fs_devices->seed_list); 6943 6944 return fs_devices; 6945 } 6946 6947 static int read_one_dev(struct extent_buffer *leaf, 6948 struct btrfs_dev_item *dev_item) 6949 { 6950 BTRFS_DEV_LOOKUP_ARGS(args); 6951 struct btrfs_fs_info *fs_info = leaf->fs_info; 6952 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices; 6953 struct btrfs_device *device; 6954 u64 devid; 6955 int ret; 6956 u8 fs_uuid[BTRFS_FSID_SIZE]; 6957 u8 dev_uuid[BTRFS_UUID_SIZE]; 6958 6959 devid = btrfs_device_id(leaf, dev_item); 6960 args.devid = devid; 6961 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item), 6962 BTRFS_UUID_SIZE); 6963 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item), 6964 BTRFS_FSID_SIZE); 6965 args.uuid = dev_uuid; 6966 args.fsid = fs_uuid; 6967 6968 if (memcmp(fs_uuid, fs_devices->metadata_uuid, BTRFS_FSID_SIZE)) { 6969 fs_devices = open_seed_devices(fs_info, fs_uuid); 6970 if (IS_ERR(fs_devices)) 6971 return PTR_ERR(fs_devices); 6972 } 6973 6974 device = btrfs_find_device(fs_info->fs_devices, &args); 6975 if (!device) { 6976 if (!btrfs_test_opt(fs_info, DEGRADED)) { 6977 btrfs_report_missing_device(fs_info, devid, 6978 dev_uuid, true); 6979 return -ENOENT; 6980 } 6981 6982 device = add_missing_dev(fs_devices, devid, dev_uuid); 6983 if (IS_ERR(device)) { 6984 btrfs_err(fs_info, 6985 "failed to add missing dev %llu: %ld", 6986 devid, PTR_ERR(device)); 6987 return PTR_ERR(device); 6988 } 6989 btrfs_report_missing_device(fs_info, devid, dev_uuid, false); 6990 } else { 6991 if (!device->bdev) { 6992 if (!btrfs_test_opt(fs_info, DEGRADED)) { 6993 btrfs_report_missing_device(fs_info, 6994 devid, dev_uuid, true); 6995 return -ENOENT; 6996 } 6997 btrfs_report_missing_device(fs_info, devid, 6998 dev_uuid, false); 6999 } 7000 7001 if (!device->bdev && 7002 !test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) { 7003 /* 7004 * this happens when a device that was properly setup 7005 * in the device info lists suddenly goes bad. 7006 * device->bdev is NULL, and so we have to set 7007 * device->missing to one here 7008 */ 7009 device->fs_devices->missing_devices++; 7010 set_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state); 7011 } 7012 7013 /* Move the device to its own fs_devices */ 7014 if (device->fs_devices != fs_devices) { 7015 ASSERT(test_bit(BTRFS_DEV_STATE_MISSING, 7016 &device->dev_state)); 7017 7018 list_move(&device->dev_list, &fs_devices->devices); 7019 device->fs_devices->num_devices--; 7020 fs_devices->num_devices++; 7021 7022 device->fs_devices->missing_devices--; 7023 fs_devices->missing_devices++; 7024 7025 device->fs_devices = fs_devices; 7026 } 7027 } 7028 7029 if (device->fs_devices != fs_info->fs_devices) { 7030 BUG_ON(test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)); 7031 if (device->generation != 7032 btrfs_device_generation(leaf, dev_item)) 7033 return -EINVAL; 7034 } 7035 7036 fill_device_from_item(leaf, dev_item, device); 7037 if (device->bdev) { 7038 u64 max_total_bytes = bdev_nr_bytes(device->bdev); 7039 7040 if (device->total_bytes > max_total_bytes) { 7041 btrfs_err(fs_info, 7042 "device total_bytes should be at most %llu but found %llu", 7043 max_total_bytes, device->total_bytes); 7044 return -EINVAL; 7045 } 7046 } 7047 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state); 7048 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) && 7049 !test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) { 7050 device->fs_devices->total_rw_bytes += device->total_bytes; 7051 atomic64_add(device->total_bytes - device->bytes_used, 7052 &fs_info->free_chunk_space); 7053 } 7054 ret = 0; 7055 return ret; 7056 } 7057 7058 int btrfs_read_sys_array(struct btrfs_fs_info *fs_info) 7059 { 7060 struct btrfs_super_block *super_copy = fs_info->super_copy; 7061 struct extent_buffer *sb; 7062 struct btrfs_disk_key *disk_key; 7063 struct btrfs_chunk *chunk; 7064 u8 *array_ptr; 7065 unsigned long sb_array_offset; 7066 int ret = 0; 7067 u32 num_stripes; 7068 u32 array_size; 7069 u32 len = 0; 7070 u32 cur_offset; 7071 u64 type; 7072 struct btrfs_key key; 7073 7074 ASSERT(BTRFS_SUPER_INFO_SIZE <= fs_info->nodesize); 7075 7076 /* 7077 * We allocated a dummy extent, just to use extent buffer accessors. 7078 * There will be unused space after BTRFS_SUPER_INFO_SIZE, but 7079 * that's fine, we will not go beyond system chunk array anyway. 7080 */ 7081 sb = alloc_dummy_extent_buffer(fs_info, BTRFS_SUPER_INFO_OFFSET); 7082 if (!sb) 7083 return -ENOMEM; 7084 set_extent_buffer_uptodate(sb); 7085 7086 write_extent_buffer(sb, super_copy, 0, BTRFS_SUPER_INFO_SIZE); 7087 array_size = btrfs_super_sys_array_size(super_copy); 7088 7089 array_ptr = super_copy->sys_chunk_array; 7090 sb_array_offset = offsetof(struct btrfs_super_block, sys_chunk_array); 7091 cur_offset = 0; 7092 7093 while (cur_offset < array_size) { 7094 disk_key = (struct btrfs_disk_key *)array_ptr; 7095 len = sizeof(*disk_key); 7096 if (cur_offset + len > array_size) 7097 goto out_short_read; 7098 7099 btrfs_disk_key_to_cpu(&key, disk_key); 7100 7101 array_ptr += len; 7102 sb_array_offset += len; 7103 cur_offset += len; 7104 7105 if (key.type != BTRFS_CHUNK_ITEM_KEY) { 7106 btrfs_err(fs_info, 7107 "unexpected item type %u in sys_array at offset %u", 7108 (u32)key.type, cur_offset); 7109 ret = -EIO; 7110 break; 7111 } 7112 7113 chunk = (struct btrfs_chunk *)sb_array_offset; 7114 /* 7115 * At least one btrfs_chunk with one stripe must be present, 7116 * exact stripe count check comes afterwards 7117 */ 7118 len = btrfs_chunk_item_size(1); 7119 if (cur_offset + len > array_size) 7120 goto out_short_read; 7121 7122 num_stripes = btrfs_chunk_num_stripes(sb, chunk); 7123 if (!num_stripes) { 7124 btrfs_err(fs_info, 7125 "invalid number of stripes %u in sys_array at offset %u", 7126 num_stripes, cur_offset); 7127 ret = -EIO; 7128 break; 7129 } 7130 7131 type = btrfs_chunk_type(sb, chunk); 7132 if ((type & BTRFS_BLOCK_GROUP_SYSTEM) == 0) { 7133 btrfs_err(fs_info, 7134 "invalid chunk type %llu in sys_array at offset %u", 7135 type, cur_offset); 7136 ret = -EIO; 7137 break; 7138 } 7139 7140 len = btrfs_chunk_item_size(num_stripes); 7141 if (cur_offset + len > array_size) 7142 goto out_short_read; 7143 7144 ret = read_one_chunk(&key, sb, chunk); 7145 if (ret) 7146 break; 7147 7148 array_ptr += len; 7149 sb_array_offset += len; 7150 cur_offset += len; 7151 } 7152 clear_extent_buffer_uptodate(sb); 7153 free_extent_buffer_stale(sb); 7154 return ret; 7155 7156 out_short_read: 7157 btrfs_err(fs_info, "sys_array too short to read %u bytes at offset %u", 7158 len, cur_offset); 7159 clear_extent_buffer_uptodate(sb); 7160 free_extent_buffer_stale(sb); 7161 return -EIO; 7162 } 7163 7164 /* 7165 * Check if all chunks in the fs are OK for read-write degraded mount 7166 * 7167 * If the @failing_dev is specified, it's accounted as missing. 7168 * 7169 * Return true if all chunks meet the minimal RW mount requirements. 7170 * Return false if any chunk doesn't meet the minimal RW mount requirements. 7171 */ 7172 bool btrfs_check_rw_degradable(struct btrfs_fs_info *fs_info, 7173 struct btrfs_device *failing_dev) 7174 { 7175 struct extent_map_tree *map_tree = &fs_info->mapping_tree; 7176 struct extent_map *em; 7177 u64 next_start = 0; 7178 bool ret = true; 7179 7180 read_lock(&map_tree->lock); 7181 em = lookup_extent_mapping(map_tree, 0, (u64)-1); 7182 read_unlock(&map_tree->lock); 7183 /* No chunk at all? Return false anyway */ 7184 if (!em) { 7185 ret = false; 7186 goto out; 7187 } 7188 while (em) { 7189 struct map_lookup *map; 7190 int missing = 0; 7191 int max_tolerated; 7192 int i; 7193 7194 map = em->map_lookup; 7195 max_tolerated = 7196 btrfs_get_num_tolerated_disk_barrier_failures( 7197 map->type); 7198 for (i = 0; i < map->num_stripes; i++) { 7199 struct btrfs_device *dev = map->stripes[i].dev; 7200 7201 if (!dev || !dev->bdev || 7202 test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state) || 7203 dev->last_flush_error) 7204 missing++; 7205 else if (failing_dev && failing_dev == dev) 7206 missing++; 7207 } 7208 if (missing > max_tolerated) { 7209 if (!failing_dev) 7210 btrfs_warn(fs_info, 7211 "chunk %llu missing %d devices, max tolerance is %d for writable mount", 7212 em->start, missing, max_tolerated); 7213 free_extent_map(em); 7214 ret = false; 7215 goto out; 7216 } 7217 next_start = extent_map_end(em); 7218 free_extent_map(em); 7219 7220 read_lock(&map_tree->lock); 7221 em = lookup_extent_mapping(map_tree, next_start, 7222 (u64)(-1) - next_start); 7223 read_unlock(&map_tree->lock); 7224 } 7225 out: 7226 return ret; 7227 } 7228 7229 static void readahead_tree_node_children(struct extent_buffer *node) 7230 { 7231 int i; 7232 const int nr_items = btrfs_header_nritems(node); 7233 7234 for (i = 0; i < nr_items; i++) 7235 btrfs_readahead_node_child(node, i); 7236 } 7237 7238 int btrfs_read_chunk_tree(struct btrfs_fs_info *fs_info) 7239 { 7240 struct btrfs_root *root = fs_info->chunk_root; 7241 struct btrfs_path *path; 7242 struct extent_buffer *leaf; 7243 struct btrfs_key key; 7244 struct btrfs_key found_key; 7245 int ret; 7246 int slot; 7247 int iter_ret = 0; 7248 u64 total_dev = 0; 7249 u64 last_ra_node = 0; 7250 7251 path = btrfs_alloc_path(); 7252 if (!path) 7253 return -ENOMEM; 7254 7255 /* 7256 * uuid_mutex is needed only if we are mounting a sprout FS 7257 * otherwise we don't need it. 7258 */ 7259 mutex_lock(&uuid_mutex); 7260 7261 /* 7262 * It is possible for mount and umount to race in such a way that 7263 * we execute this code path, but open_fs_devices failed to clear 7264 * total_rw_bytes. We certainly want it cleared before reading the 7265 * device items, so clear it here. 7266 */ 7267 fs_info->fs_devices->total_rw_bytes = 0; 7268 7269 /* 7270 * Lockdep complains about possible circular locking dependency between 7271 * a disk's open_mutex (struct gendisk.open_mutex), the rw semaphores 7272 * used for freeze procection of a fs (struct super_block.s_writers), 7273 * which we take when starting a transaction, and extent buffers of the 7274 * chunk tree if we call read_one_dev() while holding a lock on an 7275 * extent buffer of the chunk tree. Since we are mounting the filesystem 7276 * and at this point there can't be any concurrent task modifying the 7277 * chunk tree, to keep it simple, just skip locking on the chunk tree. 7278 */ 7279 ASSERT(!test_bit(BTRFS_FS_OPEN, &fs_info->flags)); 7280 path->skip_locking = 1; 7281 7282 /* 7283 * Read all device items, and then all the chunk items. All 7284 * device items are found before any chunk item (their object id 7285 * is smaller than the lowest possible object id for a chunk 7286 * item - BTRFS_FIRST_CHUNK_TREE_OBJECTID). 7287 */ 7288 key.objectid = BTRFS_DEV_ITEMS_OBJECTID; 7289 key.offset = 0; 7290 key.type = 0; 7291 btrfs_for_each_slot(root, &key, &found_key, path, iter_ret) { 7292 struct extent_buffer *node = path->nodes[1]; 7293 7294 leaf = path->nodes[0]; 7295 slot = path->slots[0]; 7296 7297 if (node) { 7298 if (last_ra_node != node->start) { 7299 readahead_tree_node_children(node); 7300 last_ra_node = node->start; 7301 } 7302 } 7303 if (found_key.type == BTRFS_DEV_ITEM_KEY) { 7304 struct btrfs_dev_item *dev_item; 7305 dev_item = btrfs_item_ptr(leaf, slot, 7306 struct btrfs_dev_item); 7307 ret = read_one_dev(leaf, dev_item); 7308 if (ret) 7309 goto error; 7310 total_dev++; 7311 } else if (found_key.type == BTRFS_CHUNK_ITEM_KEY) { 7312 struct btrfs_chunk *chunk; 7313 7314 /* 7315 * We are only called at mount time, so no need to take 7316 * fs_info->chunk_mutex. Plus, to avoid lockdep warnings, 7317 * we always lock first fs_info->chunk_mutex before 7318 * acquiring any locks on the chunk tree. This is a 7319 * requirement for chunk allocation, see the comment on 7320 * top of btrfs_chunk_alloc() for details. 7321 */ 7322 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk); 7323 ret = read_one_chunk(&found_key, leaf, chunk); 7324 if (ret) 7325 goto error; 7326 } 7327 } 7328 /* Catch error found during iteration */ 7329 if (iter_ret < 0) { 7330 ret = iter_ret; 7331 goto error; 7332 } 7333 7334 /* 7335 * After loading chunk tree, we've got all device information, 7336 * do another round of validation checks. 7337 */ 7338 if (total_dev != fs_info->fs_devices->total_devices) { 7339 btrfs_warn(fs_info, 7340 "super block num_devices %llu mismatch with DEV_ITEM count %llu, will be repaired on next transaction commit", 7341 btrfs_super_num_devices(fs_info->super_copy), 7342 total_dev); 7343 fs_info->fs_devices->total_devices = total_dev; 7344 btrfs_set_super_num_devices(fs_info->super_copy, total_dev); 7345 } 7346 if (btrfs_super_total_bytes(fs_info->super_copy) < 7347 fs_info->fs_devices->total_rw_bytes) { 7348 btrfs_err(fs_info, 7349 "super_total_bytes %llu mismatch with fs_devices total_rw_bytes %llu", 7350 btrfs_super_total_bytes(fs_info->super_copy), 7351 fs_info->fs_devices->total_rw_bytes); 7352 ret = -EINVAL; 7353 goto error; 7354 } 7355 ret = 0; 7356 error: 7357 mutex_unlock(&uuid_mutex); 7358 7359 btrfs_free_path(path); 7360 return ret; 7361 } 7362 7363 int btrfs_init_devices_late(struct btrfs_fs_info *fs_info) 7364 { 7365 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices, *seed_devs; 7366 struct btrfs_device *device; 7367 int ret = 0; 7368 7369 fs_devices->fs_info = fs_info; 7370 7371 mutex_lock(&fs_devices->device_list_mutex); 7372 list_for_each_entry(device, &fs_devices->devices, dev_list) 7373 device->fs_info = fs_info; 7374 7375 list_for_each_entry(seed_devs, &fs_devices->seed_list, seed_list) { 7376 list_for_each_entry(device, &seed_devs->devices, dev_list) { 7377 device->fs_info = fs_info; 7378 ret = btrfs_get_dev_zone_info(device, false); 7379 if (ret) 7380 break; 7381 } 7382 7383 seed_devs->fs_info = fs_info; 7384 } 7385 mutex_unlock(&fs_devices->device_list_mutex); 7386 7387 return ret; 7388 } 7389 7390 static u64 btrfs_dev_stats_value(const struct extent_buffer *eb, 7391 const struct btrfs_dev_stats_item *ptr, 7392 int index) 7393 { 7394 u64 val; 7395 7396 read_extent_buffer(eb, &val, 7397 offsetof(struct btrfs_dev_stats_item, values) + 7398 ((unsigned long)ptr) + (index * sizeof(u64)), 7399 sizeof(val)); 7400 return val; 7401 } 7402 7403 static void btrfs_set_dev_stats_value(struct extent_buffer *eb, 7404 struct btrfs_dev_stats_item *ptr, 7405 int index, u64 val) 7406 { 7407 write_extent_buffer(eb, &val, 7408 offsetof(struct btrfs_dev_stats_item, values) + 7409 ((unsigned long)ptr) + (index * sizeof(u64)), 7410 sizeof(val)); 7411 } 7412 7413 static int btrfs_device_init_dev_stats(struct btrfs_device *device, 7414 struct btrfs_path *path) 7415 { 7416 struct btrfs_dev_stats_item *ptr; 7417 struct extent_buffer *eb; 7418 struct btrfs_key key; 7419 int item_size; 7420 int i, ret, slot; 7421 7422 if (!device->fs_info->dev_root) 7423 return 0; 7424 7425 key.objectid = BTRFS_DEV_STATS_OBJECTID; 7426 key.type = BTRFS_PERSISTENT_ITEM_KEY; 7427 key.offset = device->devid; 7428 ret = btrfs_search_slot(NULL, device->fs_info->dev_root, &key, path, 0, 0); 7429 if (ret) { 7430 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) 7431 btrfs_dev_stat_set(device, i, 0); 7432 device->dev_stats_valid = 1; 7433 btrfs_release_path(path); 7434 return ret < 0 ? ret : 0; 7435 } 7436 slot = path->slots[0]; 7437 eb = path->nodes[0]; 7438 item_size = btrfs_item_size(eb, slot); 7439 7440 ptr = btrfs_item_ptr(eb, slot, struct btrfs_dev_stats_item); 7441 7442 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) { 7443 if (item_size >= (1 + i) * sizeof(__le64)) 7444 btrfs_dev_stat_set(device, i, 7445 btrfs_dev_stats_value(eb, ptr, i)); 7446 else 7447 btrfs_dev_stat_set(device, i, 0); 7448 } 7449 7450 device->dev_stats_valid = 1; 7451 btrfs_dev_stat_print_on_load(device); 7452 btrfs_release_path(path); 7453 7454 return 0; 7455 } 7456 7457 int btrfs_init_dev_stats(struct btrfs_fs_info *fs_info) 7458 { 7459 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices, *seed_devs; 7460 struct btrfs_device *device; 7461 struct btrfs_path *path = NULL; 7462 int ret = 0; 7463 7464 path = btrfs_alloc_path(); 7465 if (!path) 7466 return -ENOMEM; 7467 7468 mutex_lock(&fs_devices->device_list_mutex); 7469 list_for_each_entry(device, &fs_devices->devices, dev_list) { 7470 ret = btrfs_device_init_dev_stats(device, path); 7471 if (ret) 7472 goto out; 7473 } 7474 list_for_each_entry(seed_devs, &fs_devices->seed_list, seed_list) { 7475 list_for_each_entry(device, &seed_devs->devices, dev_list) { 7476 ret = btrfs_device_init_dev_stats(device, path); 7477 if (ret) 7478 goto out; 7479 } 7480 } 7481 out: 7482 mutex_unlock(&fs_devices->device_list_mutex); 7483 7484 btrfs_free_path(path); 7485 return ret; 7486 } 7487 7488 static int update_dev_stat_item(struct btrfs_trans_handle *trans, 7489 struct btrfs_device *device) 7490 { 7491 struct btrfs_fs_info *fs_info = trans->fs_info; 7492 struct btrfs_root *dev_root = fs_info->dev_root; 7493 struct btrfs_path *path; 7494 struct btrfs_key key; 7495 struct extent_buffer *eb; 7496 struct btrfs_dev_stats_item *ptr; 7497 int ret; 7498 int i; 7499 7500 key.objectid = BTRFS_DEV_STATS_OBJECTID; 7501 key.type = BTRFS_PERSISTENT_ITEM_KEY; 7502 key.offset = device->devid; 7503 7504 path = btrfs_alloc_path(); 7505 if (!path) 7506 return -ENOMEM; 7507 ret = btrfs_search_slot(trans, dev_root, &key, path, -1, 1); 7508 if (ret < 0) { 7509 btrfs_warn_in_rcu(fs_info, 7510 "error %d while searching for dev_stats item for device %s", 7511 ret, btrfs_dev_name(device)); 7512 goto out; 7513 } 7514 7515 if (ret == 0 && 7516 btrfs_item_size(path->nodes[0], path->slots[0]) < sizeof(*ptr)) { 7517 /* need to delete old one and insert a new one */ 7518 ret = btrfs_del_item(trans, dev_root, path); 7519 if (ret != 0) { 7520 btrfs_warn_in_rcu(fs_info, 7521 "delete too small dev_stats item for device %s failed %d", 7522 btrfs_dev_name(device), ret); 7523 goto out; 7524 } 7525 ret = 1; 7526 } 7527 7528 if (ret == 1) { 7529 /* need to insert a new item */ 7530 btrfs_release_path(path); 7531 ret = btrfs_insert_empty_item(trans, dev_root, path, 7532 &key, sizeof(*ptr)); 7533 if (ret < 0) { 7534 btrfs_warn_in_rcu(fs_info, 7535 "insert dev_stats item for device %s failed %d", 7536 btrfs_dev_name(device), ret); 7537 goto out; 7538 } 7539 } 7540 7541 eb = path->nodes[0]; 7542 ptr = btrfs_item_ptr(eb, path->slots[0], struct btrfs_dev_stats_item); 7543 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) 7544 btrfs_set_dev_stats_value(eb, ptr, i, 7545 btrfs_dev_stat_read(device, i)); 7546 btrfs_mark_buffer_dirty(eb); 7547 7548 out: 7549 btrfs_free_path(path); 7550 return ret; 7551 } 7552 7553 /* 7554 * called from commit_transaction. Writes all changed device stats to disk. 7555 */ 7556 int btrfs_run_dev_stats(struct btrfs_trans_handle *trans) 7557 { 7558 struct btrfs_fs_info *fs_info = trans->fs_info; 7559 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices; 7560 struct btrfs_device *device; 7561 int stats_cnt; 7562 int ret = 0; 7563 7564 mutex_lock(&fs_devices->device_list_mutex); 7565 list_for_each_entry(device, &fs_devices->devices, dev_list) { 7566 stats_cnt = atomic_read(&device->dev_stats_ccnt); 7567 if (!device->dev_stats_valid || stats_cnt == 0) 7568 continue; 7569 7570 7571 /* 7572 * There is a LOAD-LOAD control dependency between the value of 7573 * dev_stats_ccnt and updating the on-disk values which requires 7574 * reading the in-memory counters. Such control dependencies 7575 * require explicit read memory barriers. 7576 * 7577 * This memory barriers pairs with smp_mb__before_atomic in 7578 * btrfs_dev_stat_inc/btrfs_dev_stat_set and with the full 7579 * barrier implied by atomic_xchg in 7580 * btrfs_dev_stats_read_and_reset 7581 */ 7582 smp_rmb(); 7583 7584 ret = update_dev_stat_item(trans, device); 7585 if (!ret) 7586 atomic_sub(stats_cnt, &device->dev_stats_ccnt); 7587 } 7588 mutex_unlock(&fs_devices->device_list_mutex); 7589 7590 return ret; 7591 } 7592 7593 void btrfs_dev_stat_inc_and_print(struct btrfs_device *dev, int index) 7594 { 7595 btrfs_dev_stat_inc(dev, index); 7596 7597 if (!dev->dev_stats_valid) 7598 return; 7599 btrfs_err_rl_in_rcu(dev->fs_info, 7600 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u", 7601 btrfs_dev_name(dev), 7602 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS), 7603 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS), 7604 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS), 7605 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS), 7606 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS)); 7607 } 7608 7609 static void btrfs_dev_stat_print_on_load(struct btrfs_device *dev) 7610 { 7611 int i; 7612 7613 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) 7614 if (btrfs_dev_stat_read(dev, i) != 0) 7615 break; 7616 if (i == BTRFS_DEV_STAT_VALUES_MAX) 7617 return; /* all values == 0, suppress message */ 7618 7619 btrfs_info_in_rcu(dev->fs_info, 7620 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u", 7621 btrfs_dev_name(dev), 7622 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS), 7623 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS), 7624 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS), 7625 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS), 7626 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS)); 7627 } 7628 7629 int btrfs_get_dev_stats(struct btrfs_fs_info *fs_info, 7630 struct btrfs_ioctl_get_dev_stats *stats) 7631 { 7632 BTRFS_DEV_LOOKUP_ARGS(args); 7633 struct btrfs_device *dev; 7634 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices; 7635 int i; 7636 7637 mutex_lock(&fs_devices->device_list_mutex); 7638 args.devid = stats->devid; 7639 dev = btrfs_find_device(fs_info->fs_devices, &args); 7640 mutex_unlock(&fs_devices->device_list_mutex); 7641 7642 if (!dev) { 7643 btrfs_warn(fs_info, "get dev_stats failed, device not found"); 7644 return -ENODEV; 7645 } else if (!dev->dev_stats_valid) { 7646 btrfs_warn(fs_info, "get dev_stats failed, not yet valid"); 7647 return -ENODEV; 7648 } else if (stats->flags & BTRFS_DEV_STATS_RESET) { 7649 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) { 7650 if (stats->nr_items > i) 7651 stats->values[i] = 7652 btrfs_dev_stat_read_and_reset(dev, i); 7653 else 7654 btrfs_dev_stat_set(dev, i, 0); 7655 } 7656 btrfs_info(fs_info, "device stats zeroed by %s (%d)", 7657 current->comm, task_pid_nr(current)); 7658 } else { 7659 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) 7660 if (stats->nr_items > i) 7661 stats->values[i] = btrfs_dev_stat_read(dev, i); 7662 } 7663 if (stats->nr_items > BTRFS_DEV_STAT_VALUES_MAX) 7664 stats->nr_items = BTRFS_DEV_STAT_VALUES_MAX; 7665 return 0; 7666 } 7667 7668 /* 7669 * Update the size and bytes used for each device where it changed. This is 7670 * delayed since we would otherwise get errors while writing out the 7671 * superblocks. 7672 * 7673 * Must be invoked during transaction commit. 7674 */ 7675 void btrfs_commit_device_sizes(struct btrfs_transaction *trans) 7676 { 7677 struct btrfs_device *curr, *next; 7678 7679 ASSERT(trans->state == TRANS_STATE_COMMIT_DOING); 7680 7681 if (list_empty(&trans->dev_update_list)) 7682 return; 7683 7684 /* 7685 * We don't need the device_list_mutex here. This list is owned by the 7686 * transaction and the transaction must complete before the device is 7687 * released. 7688 */ 7689 mutex_lock(&trans->fs_info->chunk_mutex); 7690 list_for_each_entry_safe(curr, next, &trans->dev_update_list, 7691 post_commit_list) { 7692 list_del_init(&curr->post_commit_list); 7693 curr->commit_total_bytes = curr->disk_total_bytes; 7694 curr->commit_bytes_used = curr->bytes_used; 7695 } 7696 mutex_unlock(&trans->fs_info->chunk_mutex); 7697 } 7698 7699 /* 7700 * Multiplicity factor for simple profiles: DUP, RAID1-like and RAID10. 7701 */ 7702 int btrfs_bg_type_to_factor(u64 flags) 7703 { 7704 const int index = btrfs_bg_flags_to_raid_index(flags); 7705 7706 return btrfs_raid_array[index].ncopies; 7707 } 7708 7709 7710 7711 static int verify_one_dev_extent(struct btrfs_fs_info *fs_info, 7712 u64 chunk_offset, u64 devid, 7713 u64 physical_offset, u64 physical_len) 7714 { 7715 struct btrfs_dev_lookup_args args = { .devid = devid }; 7716 struct extent_map_tree *em_tree = &fs_info->mapping_tree; 7717 struct extent_map *em; 7718 struct map_lookup *map; 7719 struct btrfs_device *dev; 7720 u64 stripe_len; 7721 bool found = false; 7722 int ret = 0; 7723 int i; 7724 7725 read_lock(&em_tree->lock); 7726 em = lookup_extent_mapping(em_tree, chunk_offset, 1); 7727 read_unlock(&em_tree->lock); 7728 7729 if (!em) { 7730 btrfs_err(fs_info, 7731 "dev extent physical offset %llu on devid %llu doesn't have corresponding chunk", 7732 physical_offset, devid); 7733 ret = -EUCLEAN; 7734 goto out; 7735 } 7736 7737 map = em->map_lookup; 7738 stripe_len = btrfs_calc_stripe_length(em); 7739 if (physical_len != stripe_len) { 7740 btrfs_err(fs_info, 7741 "dev extent physical offset %llu on devid %llu length doesn't match chunk %llu, have %llu expect %llu", 7742 physical_offset, devid, em->start, physical_len, 7743 stripe_len); 7744 ret = -EUCLEAN; 7745 goto out; 7746 } 7747 7748 /* 7749 * Very old mkfs.btrfs (before v4.1) will not respect the reserved 7750 * space. Although kernel can handle it without problem, better to warn 7751 * the users. 7752 */ 7753 if (physical_offset < BTRFS_DEVICE_RANGE_RESERVED) 7754 btrfs_warn(fs_info, 7755 "devid %llu physical %llu len %llu inside the reserved space", 7756 devid, physical_offset, physical_len); 7757 7758 for (i = 0; i < map->num_stripes; i++) { 7759 if (map->stripes[i].dev->devid == devid && 7760 map->stripes[i].physical == physical_offset) { 7761 found = true; 7762 if (map->verified_stripes >= map->num_stripes) { 7763 btrfs_err(fs_info, 7764 "too many dev extents for chunk %llu found", 7765 em->start); 7766 ret = -EUCLEAN; 7767 goto out; 7768 } 7769 map->verified_stripes++; 7770 break; 7771 } 7772 } 7773 if (!found) { 7774 btrfs_err(fs_info, 7775 "dev extent physical offset %llu devid %llu has no corresponding chunk", 7776 physical_offset, devid); 7777 ret = -EUCLEAN; 7778 } 7779 7780 /* Make sure no dev extent is beyond device boundary */ 7781 dev = btrfs_find_device(fs_info->fs_devices, &args); 7782 if (!dev) { 7783 btrfs_err(fs_info, "failed to find devid %llu", devid); 7784 ret = -EUCLEAN; 7785 goto out; 7786 } 7787 7788 if (physical_offset + physical_len > dev->disk_total_bytes) { 7789 btrfs_err(fs_info, 7790 "dev extent devid %llu physical offset %llu len %llu is beyond device boundary %llu", 7791 devid, physical_offset, physical_len, 7792 dev->disk_total_bytes); 7793 ret = -EUCLEAN; 7794 goto out; 7795 } 7796 7797 if (dev->zone_info) { 7798 u64 zone_size = dev->zone_info->zone_size; 7799 7800 if (!IS_ALIGNED(physical_offset, zone_size) || 7801 !IS_ALIGNED(physical_len, zone_size)) { 7802 btrfs_err(fs_info, 7803 "zoned: dev extent devid %llu physical offset %llu len %llu is not aligned to device zone", 7804 devid, physical_offset, physical_len); 7805 ret = -EUCLEAN; 7806 goto out; 7807 } 7808 } 7809 7810 out: 7811 free_extent_map(em); 7812 return ret; 7813 } 7814 7815 static int verify_chunk_dev_extent_mapping(struct btrfs_fs_info *fs_info) 7816 { 7817 struct extent_map_tree *em_tree = &fs_info->mapping_tree; 7818 struct extent_map *em; 7819 struct rb_node *node; 7820 int ret = 0; 7821 7822 read_lock(&em_tree->lock); 7823 for (node = rb_first_cached(&em_tree->map); node; node = rb_next(node)) { 7824 em = rb_entry(node, struct extent_map, rb_node); 7825 if (em->map_lookup->num_stripes != 7826 em->map_lookup->verified_stripes) { 7827 btrfs_err(fs_info, 7828 "chunk %llu has missing dev extent, have %d expect %d", 7829 em->start, em->map_lookup->verified_stripes, 7830 em->map_lookup->num_stripes); 7831 ret = -EUCLEAN; 7832 goto out; 7833 } 7834 } 7835 out: 7836 read_unlock(&em_tree->lock); 7837 return ret; 7838 } 7839 7840 /* 7841 * Ensure that all dev extents are mapped to correct chunk, otherwise 7842 * later chunk allocation/free would cause unexpected behavior. 7843 * 7844 * NOTE: This will iterate through the whole device tree, which should be of 7845 * the same size level as the chunk tree. This slightly increases mount time. 7846 */ 7847 int btrfs_verify_dev_extents(struct btrfs_fs_info *fs_info) 7848 { 7849 struct btrfs_path *path; 7850 struct btrfs_root *root = fs_info->dev_root; 7851 struct btrfs_key key; 7852 u64 prev_devid = 0; 7853 u64 prev_dev_ext_end = 0; 7854 int ret = 0; 7855 7856 /* 7857 * We don't have a dev_root because we mounted with ignorebadroots and 7858 * failed to load the root, so we want to skip the verification in this 7859 * case for sure. 7860 * 7861 * However if the dev root is fine, but the tree itself is corrupted 7862 * we'd still fail to mount. This verification is only to make sure 7863 * writes can happen safely, so instead just bypass this check 7864 * completely in the case of IGNOREBADROOTS. 7865 */ 7866 if (btrfs_test_opt(fs_info, IGNOREBADROOTS)) 7867 return 0; 7868 7869 key.objectid = 1; 7870 key.type = BTRFS_DEV_EXTENT_KEY; 7871 key.offset = 0; 7872 7873 path = btrfs_alloc_path(); 7874 if (!path) 7875 return -ENOMEM; 7876 7877 path->reada = READA_FORWARD; 7878 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0); 7879 if (ret < 0) 7880 goto out; 7881 7882 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) { 7883 ret = btrfs_next_leaf(root, path); 7884 if (ret < 0) 7885 goto out; 7886 /* No dev extents at all? Not good */ 7887 if (ret > 0) { 7888 ret = -EUCLEAN; 7889 goto out; 7890 } 7891 } 7892 while (1) { 7893 struct extent_buffer *leaf = path->nodes[0]; 7894 struct btrfs_dev_extent *dext; 7895 int slot = path->slots[0]; 7896 u64 chunk_offset; 7897 u64 physical_offset; 7898 u64 physical_len; 7899 u64 devid; 7900 7901 btrfs_item_key_to_cpu(leaf, &key, slot); 7902 if (key.type != BTRFS_DEV_EXTENT_KEY) 7903 break; 7904 devid = key.objectid; 7905 physical_offset = key.offset; 7906 7907 dext = btrfs_item_ptr(leaf, slot, struct btrfs_dev_extent); 7908 chunk_offset = btrfs_dev_extent_chunk_offset(leaf, dext); 7909 physical_len = btrfs_dev_extent_length(leaf, dext); 7910 7911 /* Check if this dev extent overlaps with the previous one */ 7912 if (devid == prev_devid && physical_offset < prev_dev_ext_end) { 7913 btrfs_err(fs_info, 7914 "dev extent devid %llu physical offset %llu overlap with previous dev extent end %llu", 7915 devid, physical_offset, prev_dev_ext_end); 7916 ret = -EUCLEAN; 7917 goto out; 7918 } 7919 7920 ret = verify_one_dev_extent(fs_info, chunk_offset, devid, 7921 physical_offset, physical_len); 7922 if (ret < 0) 7923 goto out; 7924 prev_devid = devid; 7925 prev_dev_ext_end = physical_offset + physical_len; 7926 7927 ret = btrfs_next_item(root, path); 7928 if (ret < 0) 7929 goto out; 7930 if (ret > 0) { 7931 ret = 0; 7932 break; 7933 } 7934 } 7935 7936 /* Ensure all chunks have corresponding dev extents */ 7937 ret = verify_chunk_dev_extent_mapping(fs_info); 7938 out: 7939 btrfs_free_path(path); 7940 return ret; 7941 } 7942 7943 /* 7944 * Check whether the given block group or device is pinned by any inode being 7945 * used as a swapfile. 7946 */ 7947 bool btrfs_pinned_by_swapfile(struct btrfs_fs_info *fs_info, void *ptr) 7948 { 7949 struct btrfs_swapfile_pin *sp; 7950 struct rb_node *node; 7951 7952 spin_lock(&fs_info->swapfile_pins_lock); 7953 node = fs_info->swapfile_pins.rb_node; 7954 while (node) { 7955 sp = rb_entry(node, struct btrfs_swapfile_pin, node); 7956 if (ptr < sp->ptr) 7957 node = node->rb_left; 7958 else if (ptr > sp->ptr) 7959 node = node->rb_right; 7960 else 7961 break; 7962 } 7963 spin_unlock(&fs_info->swapfile_pins_lock); 7964 return node != NULL; 7965 } 7966 7967 static int relocating_repair_kthread(void *data) 7968 { 7969 struct btrfs_block_group *cache = data; 7970 struct btrfs_fs_info *fs_info = cache->fs_info; 7971 u64 target; 7972 int ret = 0; 7973 7974 target = cache->start; 7975 btrfs_put_block_group(cache); 7976 7977 sb_start_write(fs_info->sb); 7978 if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_BALANCE)) { 7979 btrfs_info(fs_info, 7980 "zoned: skip relocating block group %llu to repair: EBUSY", 7981 target); 7982 sb_end_write(fs_info->sb); 7983 return -EBUSY; 7984 } 7985 7986 mutex_lock(&fs_info->reclaim_bgs_lock); 7987 7988 /* Ensure block group still exists */ 7989 cache = btrfs_lookup_block_group(fs_info, target); 7990 if (!cache) 7991 goto out; 7992 7993 if (!test_bit(BLOCK_GROUP_FLAG_RELOCATING_REPAIR, &cache->runtime_flags)) 7994 goto out; 7995 7996 ret = btrfs_may_alloc_data_chunk(fs_info, target); 7997 if (ret < 0) 7998 goto out; 7999 8000 btrfs_info(fs_info, 8001 "zoned: relocating block group %llu to repair IO failure", 8002 target); 8003 ret = btrfs_relocate_chunk(fs_info, target); 8004 8005 out: 8006 if (cache) 8007 btrfs_put_block_group(cache); 8008 mutex_unlock(&fs_info->reclaim_bgs_lock); 8009 btrfs_exclop_finish(fs_info); 8010 sb_end_write(fs_info->sb); 8011 8012 return ret; 8013 } 8014 8015 bool btrfs_repair_one_zone(struct btrfs_fs_info *fs_info, u64 logical) 8016 { 8017 struct btrfs_block_group *cache; 8018 8019 if (!btrfs_is_zoned(fs_info)) 8020 return false; 8021 8022 /* Do not attempt to repair in degraded state */ 8023 if (btrfs_test_opt(fs_info, DEGRADED)) 8024 return true; 8025 8026 cache = btrfs_lookup_block_group(fs_info, logical); 8027 if (!cache) 8028 return true; 8029 8030 if (test_and_set_bit(BLOCK_GROUP_FLAG_RELOCATING_REPAIR, &cache->runtime_flags)) { 8031 btrfs_put_block_group(cache); 8032 return true; 8033 } 8034 8035 kthread_run(relocating_repair_kthread, cache, 8036 "btrfs-relocating-repair"); 8037 8038 return true; 8039 } 8040 8041 static void map_raid56_repair_block(struct btrfs_io_context *bioc, 8042 struct btrfs_io_stripe *smap, 8043 u64 logical) 8044 { 8045 int data_stripes = nr_bioc_data_stripes(bioc); 8046 int i; 8047 8048 for (i = 0; i < data_stripes; i++) { 8049 u64 stripe_start = bioc->full_stripe_logical + 8050 btrfs_stripe_nr_to_offset(i); 8051 8052 if (logical >= stripe_start && 8053 logical < stripe_start + BTRFS_STRIPE_LEN) 8054 break; 8055 } 8056 ASSERT(i < data_stripes); 8057 smap->dev = bioc->stripes[i].dev; 8058 smap->physical = bioc->stripes[i].physical + 8059 ((logical - bioc->full_stripe_logical) & 8060 BTRFS_STRIPE_LEN_MASK); 8061 } 8062 8063 /* 8064 * Map a repair write into a single device. 8065 * 8066 * A repair write is triggered by read time repair or scrub, which would only 8067 * update the contents of a single device. 8068 * Not update any other mirrors nor go through RMW path. 8069 * 8070 * Callers should ensure: 8071 * 8072 * - Call btrfs_bio_counter_inc_blocked() first 8073 * - The range does not cross stripe boundary 8074 * - Has a valid @mirror_num passed in. 8075 */ 8076 int btrfs_map_repair_block(struct btrfs_fs_info *fs_info, 8077 struct btrfs_io_stripe *smap, u64 logical, 8078 u32 length, int mirror_num) 8079 { 8080 struct btrfs_io_context *bioc = NULL; 8081 u64 map_length = length; 8082 int mirror_ret = mirror_num; 8083 int ret; 8084 8085 ASSERT(mirror_num > 0); 8086 8087 ret = btrfs_map_block(fs_info, BTRFS_MAP_WRITE, logical, &map_length, 8088 &bioc, smap, &mirror_ret, true); 8089 if (ret < 0) 8090 return ret; 8091 8092 /* The map range should not cross stripe boundary. */ 8093 ASSERT(map_length >= length); 8094 8095 /* Already mapped to single stripe. */ 8096 if (!bioc) 8097 goto out; 8098 8099 /* Map the RAID56 multi-stripe writes to a single one. */ 8100 if (bioc->map_type & BTRFS_BLOCK_GROUP_RAID56_MASK) { 8101 map_raid56_repair_block(bioc, smap, logical); 8102 goto out; 8103 } 8104 8105 ASSERT(mirror_num <= bioc->num_stripes); 8106 smap->dev = bioc->stripes[mirror_num - 1].dev; 8107 smap->physical = bioc->stripes[mirror_num - 1].physical; 8108 out: 8109 btrfs_put_bioc(bioc); 8110 ASSERT(smap->dev); 8111 return 0; 8112 } 8113