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