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