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