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