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