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