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