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