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