btrfs: ensure that a DUP or RAID1 block group has exactly two stripes
[sfrench/cifs-2.6.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 "ctree.h"
18 #include "extent_map.h"
19 #include "disk-io.h"
20 #include "transaction.h"
21 #include "print-tree.h"
22 #include "volumes.h"
23 #include "raid56.h"
24 #include "async-thread.h"
25 #include "check-integrity.h"
26 #include "rcu-string.h"
27 #include "math.h"
28 #include "dev-replace.h"
29 #include "sysfs.h"
30
31 const struct btrfs_raid_attr btrfs_raid_array[BTRFS_NR_RAID_TYPES] = {
32         [BTRFS_RAID_RAID10] = {
33                 .sub_stripes    = 2,
34                 .dev_stripes    = 1,
35                 .devs_max       = 0,    /* 0 == as many as possible */
36                 .devs_min       = 4,
37                 .tolerated_failures = 1,
38                 .devs_increment = 2,
39                 .ncopies        = 2,
40                 .nparity        = 0,
41                 .raid_name      = "raid10",
42                 .bg_flag        = BTRFS_BLOCK_GROUP_RAID10,
43                 .mindev_error   = BTRFS_ERROR_DEV_RAID10_MIN_NOT_MET,
44         },
45         [BTRFS_RAID_RAID1] = {
46                 .sub_stripes    = 1,
47                 .dev_stripes    = 1,
48                 .devs_max       = 2,
49                 .devs_min       = 2,
50                 .tolerated_failures = 1,
51                 .devs_increment = 2,
52                 .ncopies        = 2,
53                 .nparity        = 0,
54                 .raid_name      = "raid1",
55                 .bg_flag        = BTRFS_BLOCK_GROUP_RAID1,
56                 .mindev_error   = BTRFS_ERROR_DEV_RAID1_MIN_NOT_MET,
57         },
58         [BTRFS_RAID_DUP] = {
59                 .sub_stripes    = 1,
60                 .dev_stripes    = 2,
61                 .devs_max       = 1,
62                 .devs_min       = 1,
63                 .tolerated_failures = 0,
64                 .devs_increment = 1,
65                 .ncopies        = 2,
66                 .nparity        = 0,
67                 .raid_name      = "dup",
68                 .bg_flag        = BTRFS_BLOCK_GROUP_DUP,
69                 .mindev_error   = 0,
70         },
71         [BTRFS_RAID_RAID0] = {
72                 .sub_stripes    = 1,
73                 .dev_stripes    = 1,
74                 .devs_max       = 0,
75                 .devs_min       = 2,
76                 .tolerated_failures = 0,
77                 .devs_increment = 1,
78                 .ncopies        = 1,
79                 .nparity        = 0,
80                 .raid_name      = "raid0",
81                 .bg_flag        = BTRFS_BLOCK_GROUP_RAID0,
82                 .mindev_error   = 0,
83         },
84         [BTRFS_RAID_SINGLE] = {
85                 .sub_stripes    = 1,
86                 .dev_stripes    = 1,
87                 .devs_max       = 1,
88                 .devs_min       = 1,
89                 .tolerated_failures = 0,
90                 .devs_increment = 1,
91                 .ncopies        = 1,
92                 .nparity        = 0,
93                 .raid_name      = "single",
94                 .bg_flag        = 0,
95                 .mindev_error   = 0,
96         },
97         [BTRFS_RAID_RAID5] = {
98                 .sub_stripes    = 1,
99                 .dev_stripes    = 1,
100                 .devs_max       = 0,
101                 .devs_min       = 2,
102                 .tolerated_failures = 1,
103                 .devs_increment = 1,
104                 .ncopies        = 1,
105                 .nparity        = 1,
106                 .raid_name      = "raid5",
107                 .bg_flag        = BTRFS_BLOCK_GROUP_RAID5,
108                 .mindev_error   = BTRFS_ERROR_DEV_RAID5_MIN_NOT_MET,
109         },
110         [BTRFS_RAID_RAID6] = {
111                 .sub_stripes    = 1,
112                 .dev_stripes    = 1,
113                 .devs_max       = 0,
114                 .devs_min       = 3,
115                 .tolerated_failures = 2,
116                 .devs_increment = 1,
117                 .ncopies        = 1,
118                 .nparity        = 2,
119                 .raid_name      = "raid6",
120                 .bg_flag        = BTRFS_BLOCK_GROUP_RAID6,
121                 .mindev_error   = BTRFS_ERROR_DEV_RAID6_MIN_NOT_MET,
122         },
123 };
124
125 const char *get_raid_name(enum btrfs_raid_types type)
126 {
127         if (type >= BTRFS_NR_RAID_TYPES)
128                 return NULL;
129
130         return btrfs_raid_array[type].raid_name;
131 }
132
133 /*
134  * Fill @buf with textual description of @bg_flags, no more than @size_buf
135  * bytes including terminating null byte.
136  */
137 void btrfs_describe_block_groups(u64 bg_flags, char *buf, u32 size_buf)
138 {
139         int i;
140         int ret;
141         char *bp = buf;
142         u64 flags = bg_flags;
143         u32 size_bp = size_buf;
144
145         if (!flags) {
146                 strcpy(bp, "NONE");
147                 return;
148         }
149
150 #define DESCRIBE_FLAG(flag, desc)                                               \
151         do {                                                            \
152                 if (flags & (flag)) {                                   \
153                         ret = snprintf(bp, size_bp, "%s|", (desc));     \
154                         if (ret < 0 || ret >= size_bp)                  \
155                                 goto out_overflow;                      \
156                         size_bp -= ret;                                 \
157                         bp += ret;                                      \
158                         flags &= ~(flag);                               \
159                 }                                                       \
160         } while (0)
161
162         DESCRIBE_FLAG(BTRFS_BLOCK_GROUP_DATA, "data");
163         DESCRIBE_FLAG(BTRFS_BLOCK_GROUP_SYSTEM, "system");
164         DESCRIBE_FLAG(BTRFS_BLOCK_GROUP_METADATA, "metadata");
165
166         DESCRIBE_FLAG(BTRFS_AVAIL_ALLOC_BIT_SINGLE, "single");
167         for (i = 0; i < BTRFS_NR_RAID_TYPES; i++)
168                 DESCRIBE_FLAG(btrfs_raid_array[i].bg_flag,
169                               btrfs_raid_array[i].raid_name);
170 #undef DESCRIBE_FLAG
171
172         if (flags) {
173                 ret = snprintf(bp, size_bp, "0x%llx|", flags);
174                 size_bp -= ret;
175         }
176
177         if (size_bp < size_buf)
178                 buf[size_buf - size_bp - 1] = '\0'; /* remove last | */
179
180         /*
181          * The text is trimmed, it's up to the caller to provide sufficiently
182          * large buffer
183          */
184 out_overflow:;
185 }
186
187 static int init_first_rw_device(struct btrfs_trans_handle *trans,
188                                 struct btrfs_fs_info *fs_info);
189 static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info);
190 static void __btrfs_reset_dev_stats(struct btrfs_device *dev);
191 static void btrfs_dev_stat_print_on_error(struct btrfs_device *dev);
192 static void btrfs_dev_stat_print_on_load(struct btrfs_device *device);
193 static int __btrfs_map_block(struct btrfs_fs_info *fs_info,
194                              enum btrfs_map_op op,
195                              u64 logical, u64 *length,
196                              struct btrfs_bio **bbio_ret,
197                              int mirror_num, int need_raid_map);
198
199 /*
200  * Device locking
201  * ==============
202  *
203  * There are several mutexes that protect manipulation of devices and low-level
204  * structures like chunks but not block groups, extents or files
205  *
206  * uuid_mutex (global lock)
207  * ------------------------
208  * protects the fs_uuids list that tracks all per-fs fs_devices, resulting from
209  * the SCAN_DEV ioctl registration or from mount either implicitly (the first
210  * device) or requested by the device= mount option
211  *
212  * the mutex can be very coarse and can cover long-running operations
213  *
214  * protects: updates to fs_devices counters like missing devices, rw devices,
215  * seeding, structure cloning, opening/closing devices at mount/umount time
216  *
217  * global::fs_devs - add, remove, updates to the global list
218  *
219  * does not protect: manipulation of the fs_devices::devices list!
220  *
221  * btrfs_device::name - renames (write side), read is RCU
222  *
223  * fs_devices::device_list_mutex (per-fs, with RCU)
224  * ------------------------------------------------
225  * protects updates to fs_devices::devices, ie. adding and deleting
226  *
227  * simple list traversal with read-only actions can be done with RCU protection
228  *
229  * may be used to exclude some operations from running concurrently without any
230  * modifications to the list (see write_all_supers)
231  *
232  * balance_mutex
233  * -------------
234  * protects balance structures (status, state) and context accessed from
235  * several places (internally, ioctl)
236  *
237  * chunk_mutex
238  * -----------
239  * protects chunks, adding or removing during allocation, trim or when a new
240  * device is added/removed
241  *
242  * cleaner_mutex
243  * -------------
244  * a big lock that is held by the cleaner thread and prevents running subvolume
245  * cleaning together with relocation or delayed iputs
246  *
247  *
248  * Lock nesting
249  * ============
250  *
251  * uuid_mutex
252  *   volume_mutex
253  *     device_list_mutex
254  *       chunk_mutex
255  *     balance_mutex
256  *
257  *
258  * Exclusive operations, BTRFS_FS_EXCL_OP
259  * ======================================
260  *
261  * Maintains the exclusivity of the following operations that apply to the
262  * whole filesystem and cannot run in parallel.
263  *
264  * - Balance (*)
265  * - Device add
266  * - Device remove
267  * - Device replace (*)
268  * - Resize
269  *
270  * The device operations (as above) can be in one of the following states:
271  *
272  * - Running state
273  * - Paused state
274  * - Completed state
275  *
276  * Only device operations marked with (*) can go into the Paused state for the
277  * following reasons:
278  *
279  * - ioctl (only Balance can be Paused through ioctl)
280  * - filesystem remounted as read-only
281  * - filesystem unmounted and mounted as read-only
282  * - system power-cycle and filesystem mounted as read-only
283  * - filesystem or device errors leading to forced read-only
284  *
285  * BTRFS_FS_EXCL_OP flag is set and cleared using atomic operations.
286  * During the course of Paused state, the BTRFS_FS_EXCL_OP remains set.
287  * A device operation in Paused or Running state can be canceled or resumed
288  * either by ioctl (Balance only) or when remounted as read-write.
289  * BTRFS_FS_EXCL_OP flag is cleared when the device operation is canceled or
290  * completed.
291  */
292
293 DEFINE_MUTEX(uuid_mutex);
294 static LIST_HEAD(fs_uuids);
295 struct list_head *btrfs_get_fs_uuids(void)
296 {
297         return &fs_uuids;
298 }
299
300 /*
301  * alloc_fs_devices - allocate struct btrfs_fs_devices
302  * @fsid:               if not NULL, copy the UUID to fs_devices::fsid
303  * @metadata_fsid:      if not NULL, copy the UUID to fs_devices::metadata_fsid
304  *
305  * Return a pointer to a new struct btrfs_fs_devices on success, or ERR_PTR().
306  * The returned struct is not linked onto any lists and can be destroyed with
307  * kfree() right away.
308  */
309 static struct btrfs_fs_devices *alloc_fs_devices(const u8 *fsid,
310                                                  const u8 *metadata_fsid)
311 {
312         struct btrfs_fs_devices *fs_devs;
313
314         fs_devs = kzalloc(sizeof(*fs_devs), GFP_KERNEL);
315         if (!fs_devs)
316                 return ERR_PTR(-ENOMEM);
317
318         mutex_init(&fs_devs->device_list_mutex);
319
320         INIT_LIST_HEAD(&fs_devs->devices);
321         INIT_LIST_HEAD(&fs_devs->resized_devices);
322         INIT_LIST_HEAD(&fs_devs->alloc_list);
323         INIT_LIST_HEAD(&fs_devs->fs_list);
324         if (fsid)
325                 memcpy(fs_devs->fsid, fsid, BTRFS_FSID_SIZE);
326
327         if (metadata_fsid)
328                 memcpy(fs_devs->metadata_uuid, metadata_fsid, BTRFS_FSID_SIZE);
329         else if (fsid)
330                 memcpy(fs_devs->metadata_uuid, fsid, BTRFS_FSID_SIZE);
331
332         return fs_devs;
333 }
334
335 void btrfs_free_device(struct btrfs_device *device)
336 {
337         rcu_string_free(device->name);
338         bio_put(device->flush_bio);
339         kfree(device);
340 }
341
342 static void free_fs_devices(struct btrfs_fs_devices *fs_devices)
343 {
344         struct btrfs_device *device;
345         WARN_ON(fs_devices->opened);
346         while (!list_empty(&fs_devices->devices)) {
347                 device = list_entry(fs_devices->devices.next,
348                                     struct btrfs_device, dev_list);
349                 list_del(&device->dev_list);
350                 btrfs_free_device(device);
351         }
352         kfree(fs_devices);
353 }
354
355 static void btrfs_kobject_uevent(struct block_device *bdev,
356                                  enum kobject_action action)
357 {
358         int ret;
359
360         ret = kobject_uevent(&disk_to_dev(bdev->bd_disk)->kobj, action);
361         if (ret)
362                 pr_warn("BTRFS: Sending event '%d' to kobject: '%s' (%p): failed\n",
363                         action,
364                         kobject_name(&disk_to_dev(bdev->bd_disk)->kobj),
365                         &disk_to_dev(bdev->bd_disk)->kobj);
366 }
367
368 void __exit btrfs_cleanup_fs_uuids(void)
369 {
370         struct btrfs_fs_devices *fs_devices;
371
372         while (!list_empty(&fs_uuids)) {
373                 fs_devices = list_entry(fs_uuids.next,
374                                         struct btrfs_fs_devices, fs_list);
375                 list_del(&fs_devices->fs_list);
376                 free_fs_devices(fs_devices);
377         }
378 }
379
380 /*
381  * Returns a pointer to a new btrfs_device on success; ERR_PTR() on error.
382  * Returned struct is not linked onto any lists and must be destroyed using
383  * btrfs_free_device.
384  */
385 static struct btrfs_device *__alloc_device(void)
386 {
387         struct btrfs_device *dev;
388
389         dev = kzalloc(sizeof(*dev), GFP_KERNEL);
390         if (!dev)
391                 return ERR_PTR(-ENOMEM);
392
393         /*
394          * Preallocate a bio that's always going to be used for flushing device
395          * barriers and matches the device lifespan
396          */
397         dev->flush_bio = bio_alloc_bioset(GFP_KERNEL, 0, NULL);
398         if (!dev->flush_bio) {
399                 kfree(dev);
400                 return ERR_PTR(-ENOMEM);
401         }
402
403         INIT_LIST_HEAD(&dev->dev_list);
404         INIT_LIST_HEAD(&dev->dev_alloc_list);
405         INIT_LIST_HEAD(&dev->resized_list);
406
407         spin_lock_init(&dev->io_lock);
408
409         atomic_set(&dev->reada_in_flight, 0);
410         atomic_set(&dev->dev_stats_ccnt, 0);
411         btrfs_device_data_ordered_init(dev);
412         INIT_RADIX_TREE(&dev->reada_zones, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
413         INIT_RADIX_TREE(&dev->reada_extents, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
414
415         return dev;
416 }
417
418 static noinline struct btrfs_fs_devices *find_fsid(
419                 const u8 *fsid, const u8 *metadata_fsid)
420 {
421         struct btrfs_fs_devices *fs_devices;
422
423         ASSERT(fsid);
424
425         if (metadata_fsid) {
426                 /*
427                  * Handle scanned device having completed its fsid change but
428                  * belonging to a fs_devices that was created by first scanning
429                  * a device which didn't have its fsid/metadata_uuid changed
430                  * at all and the CHANGING_FSID_V2 flag set.
431                  */
432                 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
433                         if (fs_devices->fsid_change &&
434                             memcmp(metadata_fsid, fs_devices->fsid,
435                                    BTRFS_FSID_SIZE) == 0 &&
436                             memcmp(fs_devices->fsid, fs_devices->metadata_uuid,
437                                    BTRFS_FSID_SIZE) == 0) {
438                                 return fs_devices;
439                         }
440                 }
441                 /*
442                  * Handle scanned device having completed its fsid change but
443                  * belonging to a fs_devices that was created by a device that
444                  * has an outdated pair of fsid/metadata_uuid and
445                  * CHANGING_FSID_V2 flag set.
446                  */
447                 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
448                         if (fs_devices->fsid_change &&
449                             memcmp(fs_devices->metadata_uuid,
450                                    fs_devices->fsid, BTRFS_FSID_SIZE) != 0 &&
451                             memcmp(metadata_fsid, fs_devices->metadata_uuid,
452                                    BTRFS_FSID_SIZE) == 0) {
453                                 return fs_devices;
454                         }
455                 }
456         }
457
458         /* Handle non-split brain cases */
459         list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
460                 if (metadata_fsid) {
461                         if (memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE) == 0
462                             && memcmp(metadata_fsid, fs_devices->metadata_uuid,
463                                       BTRFS_FSID_SIZE) == 0)
464                                 return fs_devices;
465                 } else {
466                         if (memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE) == 0)
467                                 return fs_devices;
468                 }
469         }
470         return NULL;
471 }
472
473 static int
474 btrfs_get_bdev_and_sb(const char *device_path, fmode_t flags, void *holder,
475                       int flush, struct block_device **bdev,
476                       struct buffer_head **bh)
477 {
478         int ret;
479
480         *bdev = blkdev_get_by_path(device_path, flags, holder);
481
482         if (IS_ERR(*bdev)) {
483                 ret = PTR_ERR(*bdev);
484                 goto error;
485         }
486
487         if (flush)
488                 filemap_write_and_wait((*bdev)->bd_inode->i_mapping);
489         ret = set_blocksize(*bdev, BTRFS_BDEV_BLOCKSIZE);
490         if (ret) {
491                 blkdev_put(*bdev, flags);
492                 goto error;
493         }
494         invalidate_bdev(*bdev);
495         *bh = btrfs_read_dev_super(*bdev);
496         if (IS_ERR(*bh)) {
497                 ret = PTR_ERR(*bh);
498                 blkdev_put(*bdev, flags);
499                 goto error;
500         }
501
502         return 0;
503
504 error:
505         *bdev = NULL;
506         *bh = NULL;
507         return ret;
508 }
509
510 static void requeue_list(struct btrfs_pending_bios *pending_bios,
511                         struct bio *head, struct bio *tail)
512 {
513
514         struct bio *old_head;
515
516         old_head = pending_bios->head;
517         pending_bios->head = head;
518         if (pending_bios->tail)
519                 tail->bi_next = old_head;
520         else
521                 pending_bios->tail = tail;
522 }
523
524 /*
525  * we try to collect pending bios for a device so we don't get a large
526  * number of procs sending bios down to the same device.  This greatly
527  * improves the schedulers ability to collect and merge the bios.
528  *
529  * But, it also turns into a long list of bios to process and that is sure
530  * to eventually make the worker thread block.  The solution here is to
531  * make some progress and then put this work struct back at the end of
532  * the list if the block device is congested.  This way, multiple devices
533  * can make progress from a single worker thread.
534  */
535 static noinline void run_scheduled_bios(struct btrfs_device *device)
536 {
537         struct btrfs_fs_info *fs_info = device->fs_info;
538         struct bio *pending;
539         struct backing_dev_info *bdi;
540         struct btrfs_pending_bios *pending_bios;
541         struct bio *tail;
542         struct bio *cur;
543         int again = 0;
544         unsigned long num_run;
545         unsigned long batch_run = 0;
546         unsigned long last_waited = 0;
547         int force_reg = 0;
548         int sync_pending = 0;
549         struct blk_plug plug;
550
551         /*
552          * this function runs all the bios we've collected for
553          * a particular device.  We don't want to wander off to
554          * another device without first sending all of these down.
555          * So, setup a plug here and finish it off before we return
556          */
557         blk_start_plug(&plug);
558
559         bdi = device->bdev->bd_bdi;
560
561 loop:
562         spin_lock(&device->io_lock);
563
564 loop_lock:
565         num_run = 0;
566
567         /* take all the bios off the list at once and process them
568          * later on (without the lock held).  But, remember the
569          * tail and other pointers so the bios can be properly reinserted
570          * into the list if we hit congestion
571          */
572         if (!force_reg && device->pending_sync_bios.head) {
573                 pending_bios = &device->pending_sync_bios;
574                 force_reg = 1;
575         } else {
576                 pending_bios = &device->pending_bios;
577                 force_reg = 0;
578         }
579
580         pending = pending_bios->head;
581         tail = pending_bios->tail;
582         WARN_ON(pending && !tail);
583
584         /*
585          * if pending was null this time around, no bios need processing
586          * at all and we can stop.  Otherwise it'll loop back up again
587          * and do an additional check so no bios are missed.
588          *
589          * device->running_pending is used to synchronize with the
590          * schedule_bio code.
591          */
592         if (device->pending_sync_bios.head == NULL &&
593             device->pending_bios.head == NULL) {
594                 again = 0;
595                 device->running_pending = 0;
596         } else {
597                 again = 1;
598                 device->running_pending = 1;
599         }
600
601         pending_bios->head = NULL;
602         pending_bios->tail = NULL;
603
604         spin_unlock(&device->io_lock);
605
606         while (pending) {
607
608                 rmb();
609                 /* we want to work on both lists, but do more bios on the
610                  * sync list than the regular list
611                  */
612                 if ((num_run > 32 &&
613                     pending_bios != &device->pending_sync_bios &&
614                     device->pending_sync_bios.head) ||
615                    (num_run > 64 && pending_bios == &device->pending_sync_bios &&
616                     device->pending_bios.head)) {
617                         spin_lock(&device->io_lock);
618                         requeue_list(pending_bios, pending, tail);
619                         goto loop_lock;
620                 }
621
622                 cur = pending;
623                 pending = pending->bi_next;
624                 cur->bi_next = NULL;
625
626                 BUG_ON(atomic_read(&cur->__bi_cnt) == 0);
627
628                 /*
629                  * if we're doing the sync list, record that our
630                  * plug has some sync requests on it
631                  *
632                  * If we're doing the regular list and there are
633                  * sync requests sitting around, unplug before
634                  * we add more
635                  */
636                 if (pending_bios == &device->pending_sync_bios) {
637                         sync_pending = 1;
638                 } else if (sync_pending) {
639                         blk_finish_plug(&plug);
640                         blk_start_plug(&plug);
641                         sync_pending = 0;
642                 }
643
644                 btrfsic_submit_bio(cur);
645                 num_run++;
646                 batch_run++;
647
648                 cond_resched();
649
650                 /*
651                  * we made progress, there is more work to do and the bdi
652                  * is now congested.  Back off and let other work structs
653                  * run instead
654                  */
655                 if (pending && bdi_write_congested(bdi) && batch_run > 8 &&
656                     fs_info->fs_devices->open_devices > 1) {
657                         struct io_context *ioc;
658
659                         ioc = current->io_context;
660
661                         /*
662                          * the main goal here is that we don't want to
663                          * block if we're going to be able to submit
664                          * more requests without blocking.
665                          *
666                          * This code does two great things, it pokes into
667                          * the elevator code from a filesystem _and_
668                          * it makes assumptions about how batching works.
669                          */
670                         if (ioc && ioc->nr_batch_requests > 0 &&
671                             time_before(jiffies, ioc->last_waited + HZ/50UL) &&
672                             (last_waited == 0 ||
673                              ioc->last_waited == last_waited)) {
674                                 /*
675                                  * we want to go through our batch of
676                                  * requests and stop.  So, we copy out
677                                  * the ioc->last_waited time and test
678                                  * against it before looping
679                                  */
680                                 last_waited = ioc->last_waited;
681                                 cond_resched();
682                                 continue;
683                         }
684                         spin_lock(&device->io_lock);
685                         requeue_list(pending_bios, pending, tail);
686                         device->running_pending = 1;
687
688                         spin_unlock(&device->io_lock);
689                         btrfs_queue_work(fs_info->submit_workers,
690                                          &device->work);
691                         goto done;
692                 }
693         }
694
695         cond_resched();
696         if (again)
697                 goto loop;
698
699         spin_lock(&device->io_lock);
700         if (device->pending_bios.head || device->pending_sync_bios.head)
701                 goto loop_lock;
702         spin_unlock(&device->io_lock);
703
704 done:
705         blk_finish_plug(&plug);
706 }
707
708 static void pending_bios_fn(struct btrfs_work *work)
709 {
710         struct btrfs_device *device;
711
712         device = container_of(work, struct btrfs_device, work);
713         run_scheduled_bios(device);
714 }
715
716 static bool device_path_matched(const char *path, struct btrfs_device *device)
717 {
718         int found;
719
720         rcu_read_lock();
721         found = strcmp(rcu_str_deref(device->name), path);
722         rcu_read_unlock();
723
724         return found == 0;
725 }
726
727 /*
728  *  Search and remove all stale (devices which are not mounted) devices.
729  *  When both inputs are NULL, it will search and release all stale devices.
730  *  path:       Optional. When provided will it release all unmounted devices
731  *              matching this path only.
732  *  skip_dev:   Optional. Will skip this device when searching for the stale
733  *              devices.
734  *  Return:     0 for success or if @path is NULL.
735  *              -EBUSY if @path is a mounted device.
736  *              -ENOENT if @path does not match any device in the list.
737  */
738 static int btrfs_free_stale_devices(const char *path,
739                                      struct btrfs_device *skip_device)
740 {
741         struct btrfs_fs_devices *fs_devices, *tmp_fs_devices;
742         struct btrfs_device *device, *tmp_device;
743         int ret = 0;
744
745         if (path)
746                 ret = -ENOENT;
747
748         list_for_each_entry_safe(fs_devices, tmp_fs_devices, &fs_uuids, fs_list) {
749
750                 mutex_lock(&fs_devices->device_list_mutex);
751                 list_for_each_entry_safe(device, tmp_device,
752                                          &fs_devices->devices, dev_list) {
753                         if (skip_device && skip_device == device)
754                                 continue;
755                         if (path && !device->name)
756                                 continue;
757                         if (path && !device_path_matched(path, device))
758                                 continue;
759                         if (fs_devices->opened) {
760                                 /* for an already deleted device return 0 */
761                                 if (path && ret != 0)
762                                         ret = -EBUSY;
763                                 break;
764                         }
765
766                         /* delete the stale device */
767                         fs_devices->num_devices--;
768                         list_del(&device->dev_list);
769                         btrfs_free_device(device);
770
771                         ret = 0;
772                         if (fs_devices->num_devices == 0)
773                                 break;
774                 }
775                 mutex_unlock(&fs_devices->device_list_mutex);
776
777                 if (fs_devices->num_devices == 0) {
778                         btrfs_sysfs_remove_fsid(fs_devices);
779                         list_del(&fs_devices->fs_list);
780                         free_fs_devices(fs_devices);
781                 }
782         }
783
784         return ret;
785 }
786
787 static int btrfs_open_one_device(struct btrfs_fs_devices *fs_devices,
788                         struct btrfs_device *device, fmode_t flags,
789                         void *holder)
790 {
791         struct request_queue *q;
792         struct block_device *bdev;
793         struct buffer_head *bh;
794         struct btrfs_super_block *disk_super;
795         u64 devid;
796         int ret;
797
798         if (device->bdev)
799                 return -EINVAL;
800         if (!device->name)
801                 return -EINVAL;
802
803         ret = btrfs_get_bdev_and_sb(device->name->str, flags, holder, 1,
804                                     &bdev, &bh);
805         if (ret)
806                 return ret;
807
808         disk_super = (struct btrfs_super_block *)bh->b_data;
809         devid = btrfs_stack_device_id(&disk_super->dev_item);
810         if (devid != device->devid)
811                 goto error_brelse;
812
813         if (memcmp(device->uuid, disk_super->dev_item.uuid, BTRFS_UUID_SIZE))
814                 goto error_brelse;
815
816         device->generation = btrfs_super_generation(disk_super);
817
818         if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_SEEDING) {
819                 if (btrfs_super_incompat_flags(disk_super) &
820                     BTRFS_FEATURE_INCOMPAT_METADATA_UUID) {
821                         pr_err(
822                 "BTRFS: Invalid seeding and uuid-changed device detected\n");
823                         goto error_brelse;
824                 }
825
826                 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
827                 fs_devices->seeding = 1;
828         } else {
829                 if (bdev_read_only(bdev))
830                         clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
831                 else
832                         set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
833         }
834
835         q = bdev_get_queue(bdev);
836         if (!blk_queue_nonrot(q))
837                 fs_devices->rotating = 1;
838
839         device->bdev = bdev;
840         clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
841         device->mode = flags;
842
843         fs_devices->open_devices++;
844         if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
845             device->devid != BTRFS_DEV_REPLACE_DEVID) {
846                 fs_devices->rw_devices++;
847                 list_add_tail(&device->dev_alloc_list, &fs_devices->alloc_list);
848         }
849         brelse(bh);
850
851         return 0;
852
853 error_brelse:
854         brelse(bh);
855         blkdev_put(bdev, flags);
856
857         return -EINVAL;
858 }
859
860 /*
861  * Handle scanned device having its CHANGING_FSID_V2 flag set and the fs_devices
862  * being created with a disk that has already completed its fsid change.
863  */
864 static struct btrfs_fs_devices *find_fsid_inprogress(
865                                         struct btrfs_super_block *disk_super)
866 {
867         struct btrfs_fs_devices *fs_devices;
868
869         list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
870                 if (memcmp(fs_devices->metadata_uuid, fs_devices->fsid,
871                            BTRFS_FSID_SIZE) != 0 &&
872                     memcmp(fs_devices->metadata_uuid, disk_super->fsid,
873                            BTRFS_FSID_SIZE) == 0 && !fs_devices->fsid_change) {
874                         return fs_devices;
875                 }
876         }
877
878         return NULL;
879 }
880
881
882 static struct btrfs_fs_devices *find_fsid_changed(
883                                         struct btrfs_super_block *disk_super)
884 {
885         struct btrfs_fs_devices *fs_devices;
886
887         /*
888          * Handles the case where scanned device is part of an fs that had
889          * multiple successful changes of FSID but curently device didn't
890          * observe it. Meaning our fsid will be different than theirs.
891          */
892         list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
893                 if (memcmp(fs_devices->metadata_uuid, fs_devices->fsid,
894                            BTRFS_FSID_SIZE) != 0 &&
895                     memcmp(fs_devices->metadata_uuid, disk_super->metadata_uuid,
896                            BTRFS_FSID_SIZE) == 0 &&
897                     memcmp(fs_devices->fsid, disk_super->fsid,
898                            BTRFS_FSID_SIZE) != 0) {
899                         return fs_devices;
900                 }
901         }
902
903         return NULL;
904 }
905 /*
906  * Add new device to list of registered devices
907  *
908  * Returns:
909  * device pointer which was just added or updated when successful
910  * error pointer when failed
911  */
912 static noinline struct btrfs_device *device_list_add(const char *path,
913                            struct btrfs_super_block *disk_super,
914                            bool *new_device_added)
915 {
916         struct btrfs_device *device;
917         struct btrfs_fs_devices *fs_devices = NULL;
918         struct rcu_string *name;
919         u64 found_transid = btrfs_super_generation(disk_super);
920         u64 devid = btrfs_stack_device_id(&disk_super->dev_item);
921         bool has_metadata_uuid = (btrfs_super_incompat_flags(disk_super) &
922                 BTRFS_FEATURE_INCOMPAT_METADATA_UUID);
923         bool fsid_change_in_progress = (btrfs_super_flags(disk_super) &
924                                         BTRFS_SUPER_FLAG_CHANGING_FSID_V2);
925
926         if (fsid_change_in_progress) {
927                 if (!has_metadata_uuid) {
928                         /*
929                          * When we have an image which has CHANGING_FSID_V2 set
930                          * it might belong to either a filesystem which has
931                          * disks with completed fsid change or it might belong
932                          * to fs with no UUID changes in effect, handle both.
933                          */
934                         fs_devices = find_fsid_inprogress(disk_super);
935                         if (!fs_devices)
936                                 fs_devices = find_fsid(disk_super->fsid, NULL);
937                 } else {
938                         fs_devices = find_fsid_changed(disk_super);
939                 }
940         } else if (has_metadata_uuid) {
941                 fs_devices = find_fsid(disk_super->fsid,
942                                        disk_super->metadata_uuid);
943         } else {
944                 fs_devices = find_fsid(disk_super->fsid, NULL);
945         }
946
947
948         if (!fs_devices) {
949                 if (has_metadata_uuid)
950                         fs_devices = alloc_fs_devices(disk_super->fsid,
951                                                       disk_super->metadata_uuid);
952                 else
953                         fs_devices = alloc_fs_devices(disk_super->fsid, NULL);
954
955                 if (IS_ERR(fs_devices))
956                         return ERR_CAST(fs_devices);
957
958                 fs_devices->fsid_change = fsid_change_in_progress;
959
960                 mutex_lock(&fs_devices->device_list_mutex);
961                 list_add(&fs_devices->fs_list, &fs_uuids);
962
963                 device = NULL;
964         } else {
965                 mutex_lock(&fs_devices->device_list_mutex);
966                 device = btrfs_find_device(fs_devices, devid,
967                                 disk_super->dev_item.uuid, NULL, false);
968
969                 /*
970                  * If this disk has been pulled into an fs devices created by
971                  * a device which had the CHANGING_FSID_V2 flag then replace the
972                  * metadata_uuid/fsid values of the fs_devices.
973                  */
974                 if (has_metadata_uuid && fs_devices->fsid_change &&
975                     found_transid > fs_devices->latest_generation) {
976                         memcpy(fs_devices->fsid, disk_super->fsid,
977                                         BTRFS_FSID_SIZE);
978                         memcpy(fs_devices->metadata_uuid,
979                                         disk_super->metadata_uuid, BTRFS_FSID_SIZE);
980
981                         fs_devices->fsid_change = false;
982                 }
983         }
984
985         if (!device) {
986                 if (fs_devices->opened) {
987                         mutex_unlock(&fs_devices->device_list_mutex);
988                         return ERR_PTR(-EBUSY);
989                 }
990
991                 device = btrfs_alloc_device(NULL, &devid,
992                                             disk_super->dev_item.uuid);
993                 if (IS_ERR(device)) {
994                         mutex_unlock(&fs_devices->device_list_mutex);
995                         /* we can safely leave the fs_devices entry around */
996                         return device;
997                 }
998
999                 name = rcu_string_strdup(path, GFP_NOFS);
1000                 if (!name) {
1001                         btrfs_free_device(device);
1002                         mutex_unlock(&fs_devices->device_list_mutex);
1003                         return ERR_PTR(-ENOMEM);
1004                 }
1005                 rcu_assign_pointer(device->name, name);
1006
1007                 list_add_rcu(&device->dev_list, &fs_devices->devices);
1008                 fs_devices->num_devices++;
1009
1010                 device->fs_devices = fs_devices;
1011                 *new_device_added = true;
1012
1013                 if (disk_super->label[0])
1014                         pr_info("BTRFS: device label %s devid %llu transid %llu %s\n",
1015                                 disk_super->label, devid, found_transid, path);
1016                 else
1017                         pr_info("BTRFS: device fsid %pU devid %llu transid %llu %s\n",
1018                                 disk_super->fsid, devid, found_transid, path);
1019
1020         } else if (!device->name || strcmp(device->name->str, path)) {
1021                 /*
1022                  * When FS is already mounted.
1023                  * 1. If you are here and if the device->name is NULL that
1024                  *    means this device was missing at time of FS mount.
1025                  * 2. If you are here and if the device->name is different
1026                  *    from 'path' that means either
1027                  *      a. The same device disappeared and reappeared with
1028                  *         different name. or
1029                  *      b. The missing-disk-which-was-replaced, has
1030                  *         reappeared now.
1031                  *
1032                  * We must allow 1 and 2a above. But 2b would be a spurious
1033                  * and unintentional.
1034                  *
1035                  * Further in case of 1 and 2a above, the disk at 'path'
1036                  * would have missed some transaction when it was away and
1037                  * in case of 2a the stale bdev has to be updated as well.
1038                  * 2b must not be allowed at all time.
1039                  */
1040
1041                 /*
1042                  * For now, we do allow update to btrfs_fs_device through the
1043                  * btrfs dev scan cli after FS has been mounted.  We're still
1044                  * tracking a problem where systems fail mount by subvolume id
1045                  * when we reject replacement on a mounted FS.
1046                  */
1047                 if (!fs_devices->opened && found_transid < device->generation) {
1048                         /*
1049                          * That is if the FS is _not_ mounted and if you
1050                          * are here, that means there is more than one
1051                          * disk with same uuid and devid.We keep the one
1052                          * with larger generation number or the last-in if
1053                          * generation are equal.
1054                          */
1055                         mutex_unlock(&fs_devices->device_list_mutex);
1056                         return ERR_PTR(-EEXIST);
1057                 }
1058
1059                 /*
1060                  * We are going to replace the device path for a given devid,
1061                  * make sure it's the same device if the device is mounted
1062                  */
1063                 if (device->bdev) {
1064                         struct block_device *path_bdev;
1065
1066                         path_bdev = lookup_bdev(path);
1067                         if (IS_ERR(path_bdev)) {
1068                                 mutex_unlock(&fs_devices->device_list_mutex);
1069                                 return ERR_CAST(path_bdev);
1070                         }
1071
1072                         if (device->bdev != path_bdev) {
1073                                 bdput(path_bdev);
1074                                 mutex_unlock(&fs_devices->device_list_mutex);
1075                                 btrfs_warn_in_rcu(device->fs_info,
1076                         "duplicate device fsid:devid for %pU:%llu old:%s new:%s",
1077                                         disk_super->fsid, devid,
1078                                         rcu_str_deref(device->name), path);
1079                                 return ERR_PTR(-EEXIST);
1080                         }
1081                         bdput(path_bdev);
1082                         btrfs_info_in_rcu(device->fs_info,
1083                                 "device fsid %pU devid %llu moved old:%s new:%s",
1084                                 disk_super->fsid, devid,
1085                                 rcu_str_deref(device->name), path);
1086                 }
1087
1088                 name = rcu_string_strdup(path, GFP_NOFS);
1089                 if (!name) {
1090                         mutex_unlock(&fs_devices->device_list_mutex);
1091                         return ERR_PTR(-ENOMEM);
1092                 }
1093                 rcu_string_free(device->name);
1094                 rcu_assign_pointer(device->name, name);
1095                 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
1096                         fs_devices->missing_devices--;
1097                         clear_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
1098                 }
1099         }
1100
1101         /*
1102          * Unmount does not free the btrfs_device struct but would zero
1103          * generation along with most of the other members. So just update
1104          * it back. We need it to pick the disk with largest generation
1105          * (as above).
1106          */
1107         if (!fs_devices->opened) {
1108                 device->generation = found_transid;
1109                 fs_devices->latest_generation = max_t(u64, found_transid,
1110                                                 fs_devices->latest_generation);
1111         }
1112
1113         fs_devices->total_devices = btrfs_super_num_devices(disk_super);
1114
1115         mutex_unlock(&fs_devices->device_list_mutex);
1116         return device;
1117 }
1118
1119 static struct btrfs_fs_devices *clone_fs_devices(struct btrfs_fs_devices *orig)
1120 {
1121         struct btrfs_fs_devices *fs_devices;
1122         struct btrfs_device *device;
1123         struct btrfs_device *orig_dev;
1124
1125         fs_devices = alloc_fs_devices(orig->fsid, NULL);
1126         if (IS_ERR(fs_devices))
1127                 return fs_devices;
1128
1129         mutex_lock(&orig->device_list_mutex);
1130         fs_devices->total_devices = orig->total_devices;
1131
1132         list_for_each_entry(orig_dev, &orig->devices, dev_list) {
1133                 struct rcu_string *name;
1134
1135                 device = btrfs_alloc_device(NULL, &orig_dev->devid,
1136                                             orig_dev->uuid);
1137                 if (IS_ERR(device))
1138                         goto error;
1139
1140                 /*
1141                  * This is ok to do without rcu read locked because we hold the
1142                  * uuid mutex so nothing we touch in here is going to disappear.
1143                  */
1144                 if (orig_dev->name) {
1145                         name = rcu_string_strdup(orig_dev->name->str,
1146                                         GFP_KERNEL);
1147                         if (!name) {
1148                                 btrfs_free_device(device);
1149                                 goto error;
1150                         }
1151                         rcu_assign_pointer(device->name, name);
1152                 }
1153
1154                 list_add(&device->dev_list, &fs_devices->devices);
1155                 device->fs_devices = fs_devices;
1156                 fs_devices->num_devices++;
1157         }
1158         mutex_unlock(&orig->device_list_mutex);
1159         return fs_devices;
1160 error:
1161         mutex_unlock(&orig->device_list_mutex);
1162         free_fs_devices(fs_devices);
1163         return ERR_PTR(-ENOMEM);
1164 }
1165
1166 /*
1167  * After we have read the system tree and know devids belonging to
1168  * this filesystem, remove the device which does not belong there.
1169  */
1170 void btrfs_free_extra_devids(struct btrfs_fs_devices *fs_devices, int step)
1171 {
1172         struct btrfs_device *device, *next;
1173         struct btrfs_device *latest_dev = NULL;
1174
1175         mutex_lock(&uuid_mutex);
1176 again:
1177         /* This is the initialized path, it is safe to release the devices. */
1178         list_for_each_entry_safe(device, next, &fs_devices->devices, dev_list) {
1179                 if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
1180                                                         &device->dev_state)) {
1181                         if (!test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
1182                              &device->dev_state) &&
1183                              (!latest_dev ||
1184                               device->generation > latest_dev->generation)) {
1185                                 latest_dev = device;
1186                         }
1187                         continue;
1188                 }
1189
1190                 if (device->devid == BTRFS_DEV_REPLACE_DEVID) {
1191                         /*
1192                          * In the first step, keep the device which has
1193                          * the correct fsid and the devid that is used
1194                          * for the dev_replace procedure.
1195                          * In the second step, the dev_replace state is
1196                          * read from the device tree and it is known
1197                          * whether the procedure is really active or
1198                          * not, which means whether this device is
1199                          * used or whether it should be removed.
1200                          */
1201                         if (step == 0 || test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
1202                                                   &device->dev_state)) {
1203                                 continue;
1204                         }
1205                 }
1206                 if (device->bdev) {
1207                         blkdev_put(device->bdev, device->mode);
1208                         device->bdev = NULL;
1209                         fs_devices->open_devices--;
1210                 }
1211                 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
1212                         list_del_init(&device->dev_alloc_list);
1213                         clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
1214                         if (!test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
1215                                       &device->dev_state))
1216                                 fs_devices->rw_devices--;
1217                 }
1218                 list_del_init(&device->dev_list);
1219                 fs_devices->num_devices--;
1220                 btrfs_free_device(device);
1221         }
1222
1223         if (fs_devices->seed) {
1224                 fs_devices = fs_devices->seed;
1225                 goto again;
1226         }
1227
1228         fs_devices->latest_bdev = latest_dev->bdev;
1229
1230         mutex_unlock(&uuid_mutex);
1231 }
1232
1233 static void free_device_rcu(struct rcu_head *head)
1234 {
1235         struct btrfs_device *device;
1236
1237         device = container_of(head, struct btrfs_device, rcu);
1238         btrfs_free_device(device);
1239 }
1240
1241 static void btrfs_close_bdev(struct btrfs_device *device)
1242 {
1243         if (!device->bdev)
1244                 return;
1245
1246         if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
1247                 sync_blockdev(device->bdev);
1248                 invalidate_bdev(device->bdev);
1249         }
1250
1251         blkdev_put(device->bdev, device->mode);
1252 }
1253
1254 static void btrfs_close_one_device(struct btrfs_device *device)
1255 {
1256         struct btrfs_fs_devices *fs_devices = device->fs_devices;
1257         struct btrfs_device *new_device;
1258         struct rcu_string *name;
1259
1260         if (device->bdev)
1261                 fs_devices->open_devices--;
1262
1263         if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
1264             device->devid != BTRFS_DEV_REPLACE_DEVID) {
1265                 list_del_init(&device->dev_alloc_list);
1266                 fs_devices->rw_devices--;
1267         }
1268
1269         if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state))
1270                 fs_devices->missing_devices--;
1271
1272         btrfs_close_bdev(device);
1273
1274         new_device = btrfs_alloc_device(NULL, &device->devid,
1275                                         device->uuid);
1276         BUG_ON(IS_ERR(new_device)); /* -ENOMEM */
1277
1278         /* Safe because we are under uuid_mutex */
1279         if (device->name) {
1280                 name = rcu_string_strdup(device->name->str, GFP_NOFS);
1281                 BUG_ON(!name); /* -ENOMEM */
1282                 rcu_assign_pointer(new_device->name, name);
1283         }
1284
1285         list_replace_rcu(&device->dev_list, &new_device->dev_list);
1286         new_device->fs_devices = device->fs_devices;
1287
1288         call_rcu(&device->rcu, free_device_rcu);
1289 }
1290
1291 static int close_fs_devices(struct btrfs_fs_devices *fs_devices)
1292 {
1293         struct btrfs_device *device, *tmp;
1294
1295         if (--fs_devices->opened > 0)
1296                 return 0;
1297
1298         mutex_lock(&fs_devices->device_list_mutex);
1299         list_for_each_entry_safe(device, tmp, &fs_devices->devices, dev_list) {
1300                 btrfs_close_one_device(device);
1301         }
1302         mutex_unlock(&fs_devices->device_list_mutex);
1303
1304         WARN_ON(fs_devices->open_devices);
1305         WARN_ON(fs_devices->rw_devices);
1306         fs_devices->opened = 0;
1307         fs_devices->seeding = 0;
1308
1309         return 0;
1310 }
1311
1312 int btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
1313 {
1314         struct btrfs_fs_devices *seed_devices = NULL;
1315         int ret;
1316
1317         mutex_lock(&uuid_mutex);
1318         ret = close_fs_devices(fs_devices);
1319         if (!fs_devices->opened) {
1320                 seed_devices = fs_devices->seed;
1321                 fs_devices->seed = NULL;
1322         }
1323         mutex_unlock(&uuid_mutex);
1324
1325         while (seed_devices) {
1326                 fs_devices = seed_devices;
1327                 seed_devices = fs_devices->seed;
1328                 close_fs_devices(fs_devices);
1329                 free_fs_devices(fs_devices);
1330         }
1331         return ret;
1332 }
1333
1334 static int open_fs_devices(struct btrfs_fs_devices *fs_devices,
1335                                 fmode_t flags, void *holder)
1336 {
1337         struct btrfs_device *device;
1338         struct btrfs_device *latest_dev = NULL;
1339         int ret = 0;
1340
1341         flags |= FMODE_EXCL;
1342
1343         list_for_each_entry(device, &fs_devices->devices, dev_list) {
1344                 /* Just open everything we can; ignore failures here */
1345                 if (btrfs_open_one_device(fs_devices, device, flags, holder))
1346                         continue;
1347
1348                 if (!latest_dev ||
1349                     device->generation > latest_dev->generation)
1350                         latest_dev = device;
1351         }
1352         if (fs_devices->open_devices == 0) {
1353                 ret = -EINVAL;
1354                 goto out;
1355         }
1356         fs_devices->opened = 1;
1357         fs_devices->latest_bdev = latest_dev->bdev;
1358         fs_devices->total_rw_bytes = 0;
1359 out:
1360         return ret;
1361 }
1362
1363 static int devid_cmp(void *priv, struct list_head *a, struct list_head *b)
1364 {
1365         struct btrfs_device *dev1, *dev2;
1366
1367         dev1 = list_entry(a, struct btrfs_device, dev_list);
1368         dev2 = list_entry(b, struct btrfs_device, dev_list);
1369
1370         if (dev1->devid < dev2->devid)
1371                 return -1;
1372         else if (dev1->devid > dev2->devid)
1373                 return 1;
1374         return 0;
1375 }
1376
1377 int btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
1378                        fmode_t flags, void *holder)
1379 {
1380         int ret;
1381
1382         lockdep_assert_held(&uuid_mutex);
1383
1384         mutex_lock(&fs_devices->device_list_mutex);
1385         if (fs_devices->opened) {
1386                 fs_devices->opened++;
1387                 ret = 0;
1388         } else {
1389                 list_sort(NULL, &fs_devices->devices, devid_cmp);
1390                 ret = open_fs_devices(fs_devices, flags, holder);
1391         }
1392         mutex_unlock(&fs_devices->device_list_mutex);
1393
1394         return ret;
1395 }
1396
1397 static void btrfs_release_disk_super(struct page *page)
1398 {
1399         kunmap(page);
1400         put_page(page);
1401 }
1402
1403 static int btrfs_read_disk_super(struct block_device *bdev, u64 bytenr,
1404                                  struct page **page,
1405                                  struct btrfs_super_block **disk_super)
1406 {
1407         void *p;
1408         pgoff_t index;
1409
1410         /* make sure our super fits in the device */
1411         if (bytenr + PAGE_SIZE >= i_size_read(bdev->bd_inode))
1412                 return 1;
1413
1414         /* make sure our super fits in the page */
1415         if (sizeof(**disk_super) > PAGE_SIZE)
1416                 return 1;
1417
1418         /* make sure our super doesn't straddle pages on disk */
1419         index = bytenr >> PAGE_SHIFT;
1420         if ((bytenr + sizeof(**disk_super) - 1) >> PAGE_SHIFT != index)
1421                 return 1;
1422
1423         /* pull in the page with our super */
1424         *page = read_cache_page_gfp(bdev->bd_inode->i_mapping,
1425                                    index, GFP_KERNEL);
1426
1427         if (IS_ERR_OR_NULL(*page))
1428                 return 1;
1429
1430         p = kmap(*page);
1431
1432         /* align our pointer to the offset of the super block */
1433         *disk_super = p + offset_in_page(bytenr);
1434
1435         if (btrfs_super_bytenr(*disk_super) != bytenr ||
1436             btrfs_super_magic(*disk_super) != BTRFS_MAGIC) {
1437                 btrfs_release_disk_super(*page);
1438                 return 1;
1439         }
1440
1441         if ((*disk_super)->label[0] &&
1442                 (*disk_super)->label[BTRFS_LABEL_SIZE - 1])
1443                 (*disk_super)->label[BTRFS_LABEL_SIZE - 1] = '\0';
1444
1445         return 0;
1446 }
1447
1448 int btrfs_forget_devices(const char *path)
1449 {
1450         int ret;
1451
1452         mutex_lock(&uuid_mutex);
1453         ret = btrfs_free_stale_devices(strlen(path) ? path : NULL, NULL);
1454         mutex_unlock(&uuid_mutex);
1455
1456         return ret;
1457 }
1458
1459 /*
1460  * Look for a btrfs signature on a device. This may be called out of the mount path
1461  * and we are not allowed to call set_blocksize during the scan. The superblock
1462  * is read via pagecache
1463  */
1464 struct btrfs_device *btrfs_scan_one_device(const char *path, fmode_t flags,
1465                                            void *holder)
1466 {
1467         struct btrfs_super_block *disk_super;
1468         bool new_device_added = false;
1469         struct btrfs_device *device = NULL;
1470         struct block_device *bdev;
1471         struct page *page;
1472         u64 bytenr;
1473
1474         lockdep_assert_held(&uuid_mutex);
1475
1476         /*
1477          * we would like to check all the supers, but that would make
1478          * a btrfs mount succeed after a mkfs from a different FS.
1479          * So, we need to add a special mount option to scan for
1480          * later supers, using BTRFS_SUPER_MIRROR_MAX instead
1481          */
1482         bytenr = btrfs_sb_offset(0);
1483         flags |= FMODE_EXCL;
1484
1485         bdev = blkdev_get_by_path(path, flags, holder);
1486         if (IS_ERR(bdev))
1487                 return ERR_CAST(bdev);
1488
1489         if (btrfs_read_disk_super(bdev, bytenr, &page, &disk_super)) {
1490                 device = ERR_PTR(-EINVAL);
1491                 goto error_bdev_put;
1492         }
1493
1494         device = device_list_add(path, disk_super, &new_device_added);
1495         if (!IS_ERR(device)) {
1496                 if (new_device_added)
1497                         btrfs_free_stale_devices(path, device);
1498         }
1499
1500         btrfs_release_disk_super(page);
1501
1502 error_bdev_put:
1503         blkdev_put(bdev, flags);
1504
1505         return device;
1506 }
1507
1508 static int contains_pending_extent(struct btrfs_transaction *transaction,
1509                                    struct btrfs_device *device,
1510                                    u64 *start, u64 len)
1511 {
1512         struct btrfs_fs_info *fs_info = device->fs_info;
1513         struct extent_map *em;
1514         struct list_head *search_list = &fs_info->pinned_chunks;
1515         int ret = 0;
1516         u64 physical_start = *start;
1517
1518         if (transaction)
1519                 search_list = &transaction->pending_chunks;
1520 again:
1521         list_for_each_entry(em, search_list, list) {
1522                 struct map_lookup *map;
1523                 int i;
1524
1525                 map = em->map_lookup;
1526                 for (i = 0; i < map->num_stripes; i++) {
1527                         u64 end;
1528
1529                         if (map->stripes[i].dev != device)
1530                                 continue;
1531                         if (map->stripes[i].physical >= physical_start + len ||
1532                             map->stripes[i].physical + em->orig_block_len <=
1533                             physical_start)
1534                                 continue;
1535                         /*
1536                          * Make sure that while processing the pinned list we do
1537                          * not override our *start with a lower value, because
1538                          * we can have pinned chunks that fall within this
1539                          * device hole and that have lower physical addresses
1540                          * than the pending chunks we processed before. If we
1541                          * do not take this special care we can end up getting
1542                          * 2 pending chunks that start at the same physical
1543                          * device offsets because the end offset of a pinned
1544                          * chunk can be equal to the start offset of some
1545                          * pending chunk.
1546                          */
1547                         end = map->stripes[i].physical + em->orig_block_len;
1548                         if (end > *start) {
1549                                 *start = end;
1550                                 ret = 1;
1551                         }
1552                 }
1553         }
1554         if (search_list != &fs_info->pinned_chunks) {
1555                 search_list = &fs_info->pinned_chunks;
1556                 goto again;
1557         }
1558
1559         return ret;
1560 }
1561
1562
1563 /*
1564  * find_free_dev_extent_start - find free space in the specified device
1565  * @device:       the device which we search the free space in
1566  * @num_bytes:    the size of the free space that we need
1567  * @search_start: the position from which to begin the search
1568  * @start:        store the start of the free space.
1569  * @len:          the size of the free space. that we find, or the size
1570  *                of the max free space if we don't find suitable free space
1571  *
1572  * this uses a pretty simple search, the expectation is that it is
1573  * called very infrequently and that a given device has a small number
1574  * of extents
1575  *
1576  * @start is used to store the start of the free space if we find. But if we
1577  * don't find suitable free space, it will be used to store the start position
1578  * of the max free space.
1579  *
1580  * @len is used to store the size of the free space that we find.
1581  * But if we don't find suitable free space, it is used to store the size of
1582  * the max free space.
1583  */
1584 int find_free_dev_extent_start(struct btrfs_transaction *transaction,
1585                                struct btrfs_device *device, u64 num_bytes,
1586                                u64 search_start, u64 *start, u64 *len)
1587 {
1588         struct btrfs_fs_info *fs_info = device->fs_info;
1589         struct btrfs_root *root = fs_info->dev_root;
1590         struct btrfs_key key;
1591         struct btrfs_dev_extent *dev_extent;
1592         struct btrfs_path *path;
1593         u64 hole_size;
1594         u64 max_hole_start;
1595         u64 max_hole_size;
1596         u64 extent_end;
1597         u64 search_end = device->total_bytes;
1598         int ret;
1599         int slot;
1600         struct extent_buffer *l;
1601
1602         /*
1603          * We don't want to overwrite the superblock on the drive nor any area
1604          * used by the boot loader (grub for example), so we make sure to start
1605          * at an offset of at least 1MB.
1606          */
1607         search_start = max_t(u64, search_start, SZ_1M);
1608
1609         path = btrfs_alloc_path();
1610         if (!path)
1611                 return -ENOMEM;
1612
1613         max_hole_start = search_start;
1614         max_hole_size = 0;
1615
1616 again:
1617         if (search_start >= search_end ||
1618                 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
1619                 ret = -ENOSPC;
1620                 goto out;
1621         }
1622
1623         path->reada = READA_FORWARD;
1624         path->search_commit_root = 1;
1625         path->skip_locking = 1;
1626
1627         key.objectid = device->devid;
1628         key.offset = search_start;
1629         key.type = BTRFS_DEV_EXTENT_KEY;
1630
1631         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1632         if (ret < 0)
1633                 goto out;
1634         if (ret > 0) {
1635                 ret = btrfs_previous_item(root, path, key.objectid, key.type);
1636                 if (ret < 0)
1637                         goto out;
1638         }
1639
1640         while (1) {
1641                 l = path->nodes[0];
1642                 slot = path->slots[0];
1643                 if (slot >= btrfs_header_nritems(l)) {
1644                         ret = btrfs_next_leaf(root, path);
1645                         if (ret == 0)
1646                                 continue;
1647                         if (ret < 0)
1648                                 goto out;
1649
1650                         break;
1651                 }
1652                 btrfs_item_key_to_cpu(l, &key, slot);
1653
1654                 if (key.objectid < device->devid)
1655                         goto next;
1656
1657                 if (key.objectid > device->devid)
1658                         break;
1659
1660                 if (key.type != BTRFS_DEV_EXTENT_KEY)
1661                         goto next;
1662
1663                 if (key.offset > search_start) {
1664                         hole_size = key.offset - search_start;
1665
1666                         /*
1667                          * Have to check before we set max_hole_start, otherwise
1668                          * we could end up sending back this offset anyway.
1669                          */
1670                         if (contains_pending_extent(transaction, device,
1671                                                     &search_start,
1672                                                     hole_size)) {
1673                                 if (key.offset >= search_start) {
1674                                         hole_size = key.offset - search_start;
1675                                 } else {
1676                                         WARN_ON_ONCE(1);
1677                                         hole_size = 0;
1678                                 }
1679                         }
1680
1681                         if (hole_size > max_hole_size) {
1682                                 max_hole_start = search_start;
1683                                 max_hole_size = hole_size;
1684                         }
1685
1686                         /*
1687                          * If this free space is greater than which we need,
1688                          * it must be the max free space that we have found
1689                          * until now, so max_hole_start must point to the start
1690                          * of this free space and the length of this free space
1691                          * is stored in max_hole_size. Thus, we return
1692                          * max_hole_start and max_hole_size and go back to the
1693                          * caller.
1694                          */
1695                         if (hole_size >= num_bytes) {
1696                                 ret = 0;
1697                                 goto out;
1698                         }
1699                 }
1700
1701                 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
1702                 extent_end = key.offset + btrfs_dev_extent_length(l,
1703                                                                   dev_extent);
1704                 if (extent_end > search_start)
1705                         search_start = extent_end;
1706 next:
1707                 path->slots[0]++;
1708                 cond_resched();
1709         }
1710
1711         /*
1712          * At this point, search_start should be the end of
1713          * allocated dev extents, and when shrinking the device,
1714          * search_end may be smaller than search_start.
1715          */
1716         if (search_end > search_start) {
1717                 hole_size = search_end - search_start;
1718
1719                 if (contains_pending_extent(transaction, device, &search_start,
1720                                             hole_size)) {
1721                         btrfs_release_path(path);
1722                         goto again;
1723                 }
1724
1725                 if (hole_size > max_hole_size) {
1726                         max_hole_start = search_start;
1727                         max_hole_size = hole_size;
1728                 }
1729         }
1730
1731         /* See above. */
1732         if (max_hole_size < num_bytes)
1733                 ret = -ENOSPC;
1734         else
1735                 ret = 0;
1736
1737 out:
1738         btrfs_free_path(path);
1739         *start = max_hole_start;
1740         if (len)
1741                 *len = max_hole_size;
1742         return ret;
1743 }
1744
1745 int find_free_dev_extent(struct btrfs_trans_handle *trans,
1746                          struct btrfs_device *device, u64 num_bytes,
1747                          u64 *start, u64 *len)
1748 {
1749         /* FIXME use last free of some kind */
1750         return find_free_dev_extent_start(trans->transaction, device,
1751                                           num_bytes, 0, start, len);
1752 }
1753
1754 static int btrfs_free_dev_extent(struct btrfs_trans_handle *trans,
1755                           struct btrfs_device *device,
1756                           u64 start, u64 *dev_extent_len)
1757 {
1758         struct btrfs_fs_info *fs_info = device->fs_info;
1759         struct btrfs_root *root = fs_info->dev_root;
1760         int ret;
1761         struct btrfs_path *path;
1762         struct btrfs_key key;
1763         struct btrfs_key found_key;
1764         struct extent_buffer *leaf = NULL;
1765         struct btrfs_dev_extent *extent = NULL;
1766
1767         path = btrfs_alloc_path();
1768         if (!path)
1769                 return -ENOMEM;
1770
1771         key.objectid = device->devid;
1772         key.offset = start;
1773         key.type = BTRFS_DEV_EXTENT_KEY;
1774 again:
1775         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1776         if (ret > 0) {
1777                 ret = btrfs_previous_item(root, path, key.objectid,
1778                                           BTRFS_DEV_EXTENT_KEY);
1779                 if (ret)
1780                         goto out;
1781                 leaf = path->nodes[0];
1782                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1783                 extent = btrfs_item_ptr(leaf, path->slots[0],
1784                                         struct btrfs_dev_extent);
1785                 BUG_ON(found_key.offset > start || found_key.offset +
1786                        btrfs_dev_extent_length(leaf, extent) < start);
1787                 key = found_key;
1788                 btrfs_release_path(path);
1789                 goto again;
1790         } else if (ret == 0) {
1791                 leaf = path->nodes[0];
1792                 extent = btrfs_item_ptr(leaf, path->slots[0],
1793                                         struct btrfs_dev_extent);
1794         } else {
1795                 btrfs_handle_fs_error(fs_info, ret, "Slot search failed");
1796                 goto out;
1797         }
1798
1799         *dev_extent_len = btrfs_dev_extent_length(leaf, extent);
1800
1801         ret = btrfs_del_item(trans, root, path);
1802         if (ret) {
1803                 btrfs_handle_fs_error(fs_info, ret,
1804                                       "Failed to remove dev extent item");
1805         } else {
1806                 set_bit(BTRFS_TRANS_HAVE_FREE_BGS, &trans->transaction->flags);
1807         }
1808 out:
1809         btrfs_free_path(path);
1810         return ret;
1811 }
1812
1813 static int btrfs_alloc_dev_extent(struct btrfs_trans_handle *trans,
1814                                   struct btrfs_device *device,
1815                                   u64 chunk_offset, u64 start, u64 num_bytes)
1816 {
1817         int ret;
1818         struct btrfs_path *path;
1819         struct btrfs_fs_info *fs_info = device->fs_info;
1820         struct btrfs_root *root = fs_info->dev_root;
1821         struct btrfs_dev_extent *extent;
1822         struct extent_buffer *leaf;
1823         struct btrfs_key key;
1824
1825         WARN_ON(!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state));
1826         WARN_ON(test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state));
1827         path = btrfs_alloc_path();
1828         if (!path)
1829                 return -ENOMEM;
1830
1831         key.objectid = device->devid;
1832         key.offset = start;
1833         key.type = BTRFS_DEV_EXTENT_KEY;
1834         ret = btrfs_insert_empty_item(trans, root, path, &key,
1835                                       sizeof(*extent));
1836         if (ret)
1837                 goto out;
1838
1839         leaf = path->nodes[0];
1840         extent = btrfs_item_ptr(leaf, path->slots[0],
1841                                 struct btrfs_dev_extent);
1842         btrfs_set_dev_extent_chunk_tree(leaf, extent,
1843                                         BTRFS_CHUNK_TREE_OBJECTID);
1844         btrfs_set_dev_extent_chunk_objectid(leaf, extent,
1845                                             BTRFS_FIRST_CHUNK_TREE_OBJECTID);
1846         btrfs_set_dev_extent_chunk_offset(leaf, extent, chunk_offset);
1847
1848         btrfs_set_dev_extent_length(leaf, extent, num_bytes);
1849         btrfs_mark_buffer_dirty(leaf);
1850 out:
1851         btrfs_free_path(path);
1852         return ret;
1853 }
1854
1855 static u64 find_next_chunk(struct btrfs_fs_info *fs_info)
1856 {
1857         struct extent_map_tree *em_tree;
1858         struct extent_map *em;
1859         struct rb_node *n;
1860         u64 ret = 0;
1861
1862         em_tree = &fs_info->mapping_tree.map_tree;
1863         read_lock(&em_tree->lock);
1864         n = rb_last(&em_tree->map.rb_root);
1865         if (n) {
1866                 em = rb_entry(n, struct extent_map, rb_node);
1867                 ret = em->start + em->len;
1868         }
1869         read_unlock(&em_tree->lock);
1870
1871         return ret;
1872 }
1873
1874 static noinline int find_next_devid(struct btrfs_fs_info *fs_info,
1875                                     u64 *devid_ret)
1876 {
1877         int ret;
1878         struct btrfs_key key;
1879         struct btrfs_key found_key;
1880         struct btrfs_path *path;
1881
1882         path = btrfs_alloc_path();
1883         if (!path)
1884                 return -ENOMEM;
1885
1886         key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1887         key.type = BTRFS_DEV_ITEM_KEY;
1888         key.offset = (u64)-1;
1889
1890         ret = btrfs_search_slot(NULL, fs_info->chunk_root, &key, path, 0, 0);
1891         if (ret < 0)
1892                 goto error;
1893
1894         BUG_ON(ret == 0); /* Corruption */
1895
1896         ret = btrfs_previous_item(fs_info->chunk_root, path,
1897                                   BTRFS_DEV_ITEMS_OBJECTID,
1898                                   BTRFS_DEV_ITEM_KEY);
1899         if (ret) {
1900                 *devid_ret = 1;
1901         } else {
1902                 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
1903                                       path->slots[0]);
1904                 *devid_ret = found_key.offset + 1;
1905         }
1906         ret = 0;
1907 error:
1908         btrfs_free_path(path);
1909         return ret;
1910 }
1911
1912 /*
1913  * the device information is stored in the chunk root
1914  * the btrfs_device struct should be fully filled in
1915  */
1916 static int btrfs_add_dev_item(struct btrfs_trans_handle *trans,
1917                             struct btrfs_device *device)
1918 {
1919         int ret;
1920         struct btrfs_path *path;
1921         struct btrfs_dev_item *dev_item;
1922         struct extent_buffer *leaf;
1923         struct btrfs_key key;
1924         unsigned long ptr;
1925
1926         path = btrfs_alloc_path();
1927         if (!path)
1928                 return -ENOMEM;
1929
1930         key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1931         key.type = BTRFS_DEV_ITEM_KEY;
1932         key.offset = device->devid;
1933
1934         ret = btrfs_insert_empty_item(trans, trans->fs_info->chunk_root, path,
1935                                       &key, sizeof(*dev_item));
1936         if (ret)
1937                 goto out;
1938
1939         leaf = path->nodes[0];
1940         dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
1941
1942         btrfs_set_device_id(leaf, dev_item, device->devid);
1943         btrfs_set_device_generation(leaf, dev_item, 0);
1944         btrfs_set_device_type(leaf, dev_item, device->type);
1945         btrfs_set_device_io_align(leaf, dev_item, device->io_align);
1946         btrfs_set_device_io_width(leaf, dev_item, device->io_width);
1947         btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
1948         btrfs_set_device_total_bytes(leaf, dev_item,
1949                                      btrfs_device_get_disk_total_bytes(device));
1950         btrfs_set_device_bytes_used(leaf, dev_item,
1951                                     btrfs_device_get_bytes_used(device));
1952         btrfs_set_device_group(leaf, dev_item, 0);
1953         btrfs_set_device_seek_speed(leaf, dev_item, 0);
1954         btrfs_set_device_bandwidth(leaf, dev_item, 0);
1955         btrfs_set_device_start_offset(leaf, dev_item, 0);
1956
1957         ptr = btrfs_device_uuid(dev_item);
1958         write_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
1959         ptr = btrfs_device_fsid(dev_item);
1960         write_extent_buffer(leaf, trans->fs_info->fs_devices->metadata_uuid,
1961                             ptr, BTRFS_FSID_SIZE);
1962         btrfs_mark_buffer_dirty(leaf);
1963
1964         ret = 0;
1965 out:
1966         btrfs_free_path(path);
1967         return ret;
1968 }
1969
1970 /*
1971  * Function to update ctime/mtime for a given device path.
1972  * Mainly used for ctime/mtime based probe like libblkid.
1973  */
1974 static void update_dev_time(const char *path_name)
1975 {
1976         struct file *filp;
1977
1978         filp = filp_open(path_name, O_RDWR, 0);
1979         if (IS_ERR(filp))
1980                 return;
1981         file_update_time(filp);
1982         filp_close(filp, NULL);
1983 }
1984
1985 static int btrfs_rm_dev_item(struct btrfs_fs_info *fs_info,
1986                              struct btrfs_device *device)
1987 {
1988         struct btrfs_root *root = fs_info->chunk_root;
1989         int ret;
1990         struct btrfs_path *path;
1991         struct btrfs_key key;
1992         struct btrfs_trans_handle *trans;
1993
1994         path = btrfs_alloc_path();
1995         if (!path)
1996                 return -ENOMEM;
1997
1998         trans = btrfs_start_transaction(root, 0);
1999         if (IS_ERR(trans)) {
2000                 btrfs_free_path(path);
2001                 return PTR_ERR(trans);
2002         }
2003         key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2004         key.type = BTRFS_DEV_ITEM_KEY;
2005         key.offset = device->devid;
2006
2007         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
2008         if (ret) {
2009                 if (ret > 0)
2010                         ret = -ENOENT;
2011                 btrfs_abort_transaction(trans, ret);
2012                 btrfs_end_transaction(trans);
2013                 goto out;
2014         }
2015
2016         ret = btrfs_del_item(trans, root, path);
2017         if (ret) {
2018                 btrfs_abort_transaction(trans, ret);
2019                 btrfs_end_transaction(trans);
2020         }
2021
2022 out:
2023         btrfs_free_path(path);
2024         if (!ret)
2025                 ret = btrfs_commit_transaction(trans);
2026         return ret;
2027 }
2028
2029 /*
2030  * Verify that @num_devices satisfies the RAID profile constraints in the whole
2031  * filesystem. It's up to the caller to adjust that number regarding eg. device
2032  * replace.
2033  */
2034 static int btrfs_check_raid_min_devices(struct btrfs_fs_info *fs_info,
2035                 u64 num_devices)
2036 {
2037         u64 all_avail;
2038         unsigned seq;
2039         int i;
2040
2041         do {
2042                 seq = read_seqbegin(&fs_info->profiles_lock);
2043
2044                 all_avail = fs_info->avail_data_alloc_bits |
2045                             fs_info->avail_system_alloc_bits |
2046                             fs_info->avail_metadata_alloc_bits;
2047         } while (read_seqretry(&fs_info->profiles_lock, seq));
2048
2049         for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
2050                 if (!(all_avail & btrfs_raid_array[i].bg_flag))
2051                         continue;
2052
2053                 if (num_devices < btrfs_raid_array[i].devs_min) {
2054                         int ret = btrfs_raid_array[i].mindev_error;
2055
2056                         if (ret)
2057                                 return ret;
2058                 }
2059         }
2060
2061         return 0;
2062 }
2063
2064 static struct btrfs_device * btrfs_find_next_active_device(
2065                 struct btrfs_fs_devices *fs_devs, struct btrfs_device *device)
2066 {
2067         struct btrfs_device *next_device;
2068
2069         list_for_each_entry(next_device, &fs_devs->devices, dev_list) {
2070                 if (next_device != device &&
2071                     !test_bit(BTRFS_DEV_STATE_MISSING, &next_device->dev_state)
2072                     && next_device->bdev)
2073                         return next_device;
2074         }
2075
2076         return NULL;
2077 }
2078
2079 /*
2080  * Helper function to check if the given device is part of s_bdev / latest_bdev
2081  * and replace it with the provided or the next active device, in the context
2082  * where this function called, there should be always be another device (or
2083  * this_dev) which is active.
2084  */
2085 void btrfs_assign_next_active_device(struct btrfs_device *device,
2086                                      struct btrfs_device *this_dev)
2087 {
2088         struct btrfs_fs_info *fs_info = device->fs_info;
2089         struct btrfs_device *next_device;
2090
2091         if (this_dev)
2092                 next_device = this_dev;
2093         else
2094                 next_device = btrfs_find_next_active_device(fs_info->fs_devices,
2095                                                                 device);
2096         ASSERT(next_device);
2097
2098         if (fs_info->sb->s_bdev &&
2099                         (fs_info->sb->s_bdev == device->bdev))
2100                 fs_info->sb->s_bdev = next_device->bdev;
2101
2102         if (fs_info->fs_devices->latest_bdev == device->bdev)
2103                 fs_info->fs_devices->latest_bdev = next_device->bdev;
2104 }
2105
2106 /*
2107  * Return btrfs_fs_devices::num_devices excluding the device that's being
2108  * currently replaced.
2109  */
2110 static u64 btrfs_num_devices(struct btrfs_fs_info *fs_info)
2111 {
2112         u64 num_devices = fs_info->fs_devices->num_devices;
2113
2114         down_read(&fs_info->dev_replace.rwsem);
2115         if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace)) {
2116                 ASSERT(num_devices > 1);
2117                 num_devices--;
2118         }
2119         up_read(&fs_info->dev_replace.rwsem);
2120
2121         return num_devices;
2122 }
2123
2124 int btrfs_rm_device(struct btrfs_fs_info *fs_info, const char *device_path,
2125                 u64 devid)
2126 {
2127         struct btrfs_device *device;
2128         struct btrfs_fs_devices *cur_devices;
2129         struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2130         u64 num_devices;
2131         int ret = 0;
2132
2133         mutex_lock(&uuid_mutex);
2134
2135         num_devices = btrfs_num_devices(fs_info);
2136
2137         ret = btrfs_check_raid_min_devices(fs_info, num_devices - 1);
2138         if (ret)
2139                 goto out;
2140
2141         device = btrfs_find_device_by_devspec(fs_info, devid, device_path);
2142
2143         if (IS_ERR(device)) {
2144                 if (PTR_ERR(device) == -ENOENT &&
2145                     strcmp(device_path, "missing") == 0)
2146                         ret = BTRFS_ERROR_DEV_MISSING_NOT_FOUND;
2147                 else
2148                         ret = PTR_ERR(device);
2149                 goto out;
2150         }
2151
2152         if (btrfs_pinned_by_swapfile(fs_info, device)) {
2153                 btrfs_warn_in_rcu(fs_info,
2154                   "cannot remove device %s (devid %llu) due to active swapfile",
2155                                   rcu_str_deref(device->name), device->devid);
2156                 ret = -ETXTBSY;
2157                 goto out;
2158         }
2159
2160         if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
2161                 ret = BTRFS_ERROR_DEV_TGT_REPLACE;
2162                 goto out;
2163         }
2164
2165         if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
2166             fs_info->fs_devices->rw_devices == 1) {
2167                 ret = BTRFS_ERROR_DEV_ONLY_WRITABLE;
2168                 goto out;
2169         }
2170
2171         if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
2172                 mutex_lock(&fs_info->chunk_mutex);
2173                 list_del_init(&device->dev_alloc_list);
2174                 device->fs_devices->rw_devices--;
2175                 mutex_unlock(&fs_info->chunk_mutex);
2176         }
2177
2178         mutex_unlock(&uuid_mutex);
2179         ret = btrfs_shrink_device(device, 0);
2180         mutex_lock(&uuid_mutex);
2181         if (ret)
2182                 goto error_undo;
2183
2184         /*
2185          * TODO: the superblock still includes this device in its num_devices
2186          * counter although write_all_supers() is not locked out. This
2187          * could give a filesystem state which requires a degraded mount.
2188          */
2189         ret = btrfs_rm_dev_item(fs_info, device);
2190         if (ret)
2191                 goto error_undo;
2192
2193         clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
2194         btrfs_scrub_cancel_dev(fs_info, device);
2195
2196         /*
2197          * the device list mutex makes sure that we don't change
2198          * the device list while someone else is writing out all
2199          * the device supers. Whoever is writing all supers, should
2200          * lock the device list mutex before getting the number of
2201          * devices in the super block (super_copy). Conversely,
2202          * whoever updates the number of devices in the super block
2203          * (super_copy) should hold the device list mutex.
2204          */
2205
2206         /*
2207          * In normal cases the cur_devices == fs_devices. But in case
2208          * of deleting a seed device, the cur_devices should point to
2209          * its own fs_devices listed under the fs_devices->seed.
2210          */
2211         cur_devices = device->fs_devices;
2212         mutex_lock(&fs_devices->device_list_mutex);
2213         list_del_rcu(&device->dev_list);
2214
2215         cur_devices->num_devices--;
2216         cur_devices->total_devices--;
2217         /* Update total_devices of the parent fs_devices if it's seed */
2218         if (cur_devices != fs_devices)
2219                 fs_devices->total_devices--;
2220
2221         if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state))
2222                 cur_devices->missing_devices--;
2223
2224         btrfs_assign_next_active_device(device, NULL);
2225
2226         if (device->bdev) {
2227                 cur_devices->open_devices--;
2228                 /* remove sysfs entry */
2229                 btrfs_sysfs_rm_device_link(fs_devices, device);
2230         }
2231
2232         num_devices = btrfs_super_num_devices(fs_info->super_copy) - 1;
2233         btrfs_set_super_num_devices(fs_info->super_copy, num_devices);
2234         mutex_unlock(&fs_devices->device_list_mutex);
2235
2236         /*
2237          * at this point, the device is zero sized and detached from
2238          * the devices list.  All that's left is to zero out the old
2239          * supers and free the device.
2240          */
2241         if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
2242                 btrfs_scratch_superblocks(device->bdev, device->name->str);
2243
2244         btrfs_close_bdev(device);
2245         call_rcu(&device->rcu, free_device_rcu);
2246
2247         if (cur_devices->open_devices == 0) {
2248                 while (fs_devices) {
2249                         if (fs_devices->seed == cur_devices) {
2250                                 fs_devices->seed = cur_devices->seed;
2251                                 break;
2252                         }
2253                         fs_devices = fs_devices->seed;
2254                 }
2255                 cur_devices->seed = NULL;
2256                 close_fs_devices(cur_devices);
2257                 free_fs_devices(cur_devices);
2258         }
2259
2260 out:
2261         mutex_unlock(&uuid_mutex);
2262         return ret;
2263
2264 error_undo:
2265         if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
2266                 mutex_lock(&fs_info->chunk_mutex);
2267                 list_add(&device->dev_alloc_list,
2268                          &fs_devices->alloc_list);
2269                 device->fs_devices->rw_devices++;
2270                 mutex_unlock(&fs_info->chunk_mutex);
2271         }
2272         goto out;
2273 }
2274
2275 void btrfs_rm_dev_replace_remove_srcdev(struct btrfs_device *srcdev)
2276 {
2277         struct btrfs_fs_devices *fs_devices;
2278
2279         lockdep_assert_held(&srcdev->fs_info->fs_devices->device_list_mutex);
2280
2281         /*
2282          * in case of fs with no seed, srcdev->fs_devices will point
2283          * to fs_devices of fs_info. However when the dev being replaced is
2284          * a seed dev it will point to the seed's local fs_devices. In short
2285          * srcdev will have its correct fs_devices in both the cases.
2286          */
2287         fs_devices = srcdev->fs_devices;
2288
2289         list_del_rcu(&srcdev->dev_list);
2290         list_del(&srcdev->dev_alloc_list);
2291         fs_devices->num_devices--;
2292         if (test_bit(BTRFS_DEV_STATE_MISSING, &srcdev->dev_state))
2293                 fs_devices->missing_devices--;
2294
2295         if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &srcdev->dev_state))
2296                 fs_devices->rw_devices--;
2297
2298         if (srcdev->bdev)
2299                 fs_devices->open_devices--;
2300 }
2301
2302 void btrfs_rm_dev_replace_free_srcdev(struct btrfs_fs_info *fs_info,
2303                                       struct btrfs_device *srcdev)
2304 {
2305         struct btrfs_fs_devices *fs_devices = srcdev->fs_devices;
2306
2307         if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &srcdev->dev_state)) {
2308                 /* zero out the old super if it is writable */
2309                 btrfs_scratch_superblocks(srcdev->bdev, srcdev->name->str);
2310         }
2311
2312         btrfs_close_bdev(srcdev);
2313         call_rcu(&srcdev->rcu, free_device_rcu);
2314
2315         /* if this is no devs we rather delete the fs_devices */
2316         if (!fs_devices->num_devices) {
2317                 struct btrfs_fs_devices *tmp_fs_devices;
2318
2319                 /*
2320                  * On a mounted FS, num_devices can't be zero unless it's a
2321                  * seed. In case of a seed device being replaced, the replace
2322                  * target added to the sprout FS, so there will be no more
2323                  * device left under the seed FS.
2324                  */
2325                 ASSERT(fs_devices->seeding);
2326
2327                 tmp_fs_devices = fs_info->fs_devices;
2328                 while (tmp_fs_devices) {
2329                         if (tmp_fs_devices->seed == fs_devices) {
2330                                 tmp_fs_devices->seed = fs_devices->seed;
2331                                 break;
2332                         }
2333                         tmp_fs_devices = tmp_fs_devices->seed;
2334                 }
2335                 fs_devices->seed = NULL;
2336                 close_fs_devices(fs_devices);
2337                 free_fs_devices(fs_devices);
2338         }
2339 }
2340
2341 void btrfs_destroy_dev_replace_tgtdev(struct btrfs_device *tgtdev)
2342 {
2343         struct btrfs_fs_devices *fs_devices = tgtdev->fs_info->fs_devices;
2344
2345         WARN_ON(!tgtdev);
2346         mutex_lock(&fs_devices->device_list_mutex);
2347
2348         btrfs_sysfs_rm_device_link(fs_devices, tgtdev);
2349
2350         if (tgtdev->bdev)
2351                 fs_devices->open_devices--;
2352
2353         fs_devices->num_devices--;
2354
2355         btrfs_assign_next_active_device(tgtdev, NULL);
2356
2357         list_del_rcu(&tgtdev->dev_list);
2358
2359         mutex_unlock(&fs_devices->device_list_mutex);
2360
2361         /*
2362          * The update_dev_time() with in btrfs_scratch_superblocks()
2363          * may lead to a call to btrfs_show_devname() which will try
2364          * to hold device_list_mutex. And here this device
2365          * is already out of device list, so we don't have to hold
2366          * the device_list_mutex lock.
2367          */
2368         btrfs_scratch_superblocks(tgtdev->bdev, tgtdev->name->str);
2369
2370         btrfs_close_bdev(tgtdev);
2371         call_rcu(&tgtdev->rcu, free_device_rcu);
2372 }
2373
2374 static struct btrfs_device *btrfs_find_device_by_path(
2375                 struct btrfs_fs_info *fs_info, const char *device_path)
2376 {
2377         int ret = 0;
2378         struct btrfs_super_block *disk_super;
2379         u64 devid;
2380         u8 *dev_uuid;
2381         struct block_device *bdev;
2382         struct buffer_head *bh;
2383         struct btrfs_device *device;
2384
2385         ret = btrfs_get_bdev_and_sb(device_path, FMODE_READ,
2386                                     fs_info->bdev_holder, 0, &bdev, &bh);
2387         if (ret)
2388                 return ERR_PTR(ret);
2389         disk_super = (struct btrfs_super_block *)bh->b_data;
2390         devid = btrfs_stack_device_id(&disk_super->dev_item);
2391         dev_uuid = disk_super->dev_item.uuid;
2392         if (btrfs_fs_incompat(fs_info, METADATA_UUID))
2393                 device = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid,
2394                                            disk_super->metadata_uuid, true);
2395         else
2396                 device = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid,
2397                                            disk_super->fsid, true);
2398
2399         brelse(bh);
2400         if (!device)
2401                 device = ERR_PTR(-ENOENT);
2402         blkdev_put(bdev, FMODE_READ);
2403         return device;
2404 }
2405
2406 /*
2407  * Lookup a device given by device id, or the path if the id is 0.
2408  */
2409 struct btrfs_device *btrfs_find_device_by_devspec(
2410                 struct btrfs_fs_info *fs_info, u64 devid,
2411                 const char *device_path)
2412 {
2413         struct btrfs_device *device;
2414
2415         if (devid) {
2416                 device = btrfs_find_device(fs_info->fs_devices, devid, NULL,
2417                                            NULL, true);
2418                 if (!device)
2419                         return ERR_PTR(-ENOENT);
2420                 return device;
2421         }
2422
2423         if (!device_path || !device_path[0])
2424                 return ERR_PTR(-EINVAL);
2425
2426         if (strcmp(device_path, "missing") == 0) {
2427                 /* Find first missing device */
2428                 list_for_each_entry(device, &fs_info->fs_devices->devices,
2429                                     dev_list) {
2430                         if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
2431                                      &device->dev_state) && !device->bdev)
2432                                 return device;
2433                 }
2434                 return ERR_PTR(-ENOENT);
2435         }
2436
2437         return btrfs_find_device_by_path(fs_info, device_path);
2438 }
2439
2440 /*
2441  * does all the dirty work required for changing file system's UUID.
2442  */
2443 static int btrfs_prepare_sprout(struct btrfs_fs_info *fs_info)
2444 {
2445         struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2446         struct btrfs_fs_devices *old_devices;
2447         struct btrfs_fs_devices *seed_devices;
2448         struct btrfs_super_block *disk_super = fs_info->super_copy;
2449         struct btrfs_device *device;
2450         u64 super_flags;
2451
2452         lockdep_assert_held(&uuid_mutex);
2453         if (!fs_devices->seeding)
2454                 return -EINVAL;
2455
2456         seed_devices = alloc_fs_devices(NULL, NULL);
2457         if (IS_ERR(seed_devices))
2458                 return PTR_ERR(seed_devices);
2459
2460         old_devices = clone_fs_devices(fs_devices);
2461         if (IS_ERR(old_devices)) {
2462                 kfree(seed_devices);
2463                 return PTR_ERR(old_devices);
2464         }
2465
2466         list_add(&old_devices->fs_list, &fs_uuids);
2467
2468         memcpy(seed_devices, fs_devices, sizeof(*seed_devices));
2469         seed_devices->opened = 1;
2470         INIT_LIST_HEAD(&seed_devices->devices);
2471         INIT_LIST_HEAD(&seed_devices->alloc_list);
2472         mutex_init(&seed_devices->device_list_mutex);
2473
2474         mutex_lock(&fs_devices->device_list_mutex);
2475         list_splice_init_rcu(&fs_devices->devices, &seed_devices->devices,
2476                               synchronize_rcu);
2477         list_for_each_entry(device, &seed_devices->devices, dev_list)
2478                 device->fs_devices = seed_devices;
2479
2480         mutex_lock(&fs_info->chunk_mutex);
2481         list_splice_init(&fs_devices->alloc_list, &seed_devices->alloc_list);
2482         mutex_unlock(&fs_info->chunk_mutex);
2483
2484         fs_devices->seeding = 0;
2485         fs_devices->num_devices = 0;
2486         fs_devices->open_devices = 0;
2487         fs_devices->missing_devices = 0;
2488         fs_devices->rotating = 0;
2489         fs_devices->seed = seed_devices;
2490
2491         generate_random_uuid(fs_devices->fsid);
2492         memcpy(fs_devices->metadata_uuid, fs_devices->fsid, BTRFS_FSID_SIZE);
2493         memcpy(disk_super->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
2494         mutex_unlock(&fs_devices->device_list_mutex);
2495
2496         super_flags = btrfs_super_flags(disk_super) &
2497                       ~BTRFS_SUPER_FLAG_SEEDING;
2498         btrfs_set_super_flags(disk_super, super_flags);
2499
2500         return 0;
2501 }
2502
2503 /*
2504  * Store the expected generation for seed devices in device items.
2505  */
2506 static int btrfs_finish_sprout(struct btrfs_trans_handle *trans,
2507                                struct btrfs_fs_info *fs_info)
2508 {
2509         struct btrfs_root *root = fs_info->chunk_root;
2510         struct btrfs_path *path;
2511         struct extent_buffer *leaf;
2512         struct btrfs_dev_item *dev_item;
2513         struct btrfs_device *device;
2514         struct btrfs_key key;
2515         u8 fs_uuid[BTRFS_FSID_SIZE];
2516         u8 dev_uuid[BTRFS_UUID_SIZE];
2517         u64 devid;
2518         int ret;
2519
2520         path = btrfs_alloc_path();
2521         if (!path)
2522                 return -ENOMEM;
2523
2524         key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2525         key.offset = 0;
2526         key.type = BTRFS_DEV_ITEM_KEY;
2527
2528         while (1) {
2529                 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2530                 if (ret < 0)
2531                         goto error;
2532
2533                 leaf = path->nodes[0];
2534 next_slot:
2535                 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
2536                         ret = btrfs_next_leaf(root, path);
2537                         if (ret > 0)
2538                                 break;
2539                         if (ret < 0)
2540                                 goto error;
2541                         leaf = path->nodes[0];
2542                         btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2543                         btrfs_release_path(path);
2544                         continue;
2545                 }
2546
2547                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2548                 if (key.objectid != BTRFS_DEV_ITEMS_OBJECTID ||
2549                     key.type != BTRFS_DEV_ITEM_KEY)
2550                         break;
2551
2552                 dev_item = btrfs_item_ptr(leaf, path->slots[0],
2553                                           struct btrfs_dev_item);
2554                 devid = btrfs_device_id(leaf, dev_item);
2555                 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
2556                                    BTRFS_UUID_SIZE);
2557                 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
2558                                    BTRFS_FSID_SIZE);
2559                 device = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid,
2560                                            fs_uuid, true);
2561                 BUG_ON(!device); /* Logic error */
2562
2563                 if (device->fs_devices->seeding) {
2564                         btrfs_set_device_generation(leaf, dev_item,
2565                                                     device->generation);
2566                         btrfs_mark_buffer_dirty(leaf);
2567                 }
2568
2569                 path->slots[0]++;
2570                 goto next_slot;
2571         }
2572         ret = 0;
2573 error:
2574         btrfs_free_path(path);
2575         return ret;
2576 }
2577
2578 int btrfs_init_new_device(struct btrfs_fs_info *fs_info, const char *device_path)
2579 {
2580         struct btrfs_root *root = fs_info->dev_root;
2581         struct request_queue *q;
2582         struct btrfs_trans_handle *trans;
2583         struct btrfs_device *device;
2584         struct block_device *bdev;
2585         struct super_block *sb = fs_info->sb;
2586         struct rcu_string *name;
2587         struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2588         u64 orig_super_total_bytes;
2589         u64 orig_super_num_devices;
2590         int seeding_dev = 0;
2591         int ret = 0;
2592         bool unlocked = false;
2593
2594         if (sb_rdonly(sb) && !fs_devices->seeding)
2595                 return -EROFS;
2596
2597         bdev = blkdev_get_by_path(device_path, FMODE_WRITE | FMODE_EXCL,
2598                                   fs_info->bdev_holder);
2599         if (IS_ERR(bdev))
2600                 return PTR_ERR(bdev);
2601
2602         if (fs_devices->seeding) {
2603                 seeding_dev = 1;
2604                 down_write(&sb->s_umount);
2605                 mutex_lock(&uuid_mutex);
2606         }
2607
2608         filemap_write_and_wait(bdev->bd_inode->i_mapping);
2609
2610         mutex_lock(&fs_devices->device_list_mutex);
2611         list_for_each_entry(device, &fs_devices->devices, dev_list) {
2612                 if (device->bdev == bdev) {
2613                         ret = -EEXIST;
2614                         mutex_unlock(
2615                                 &fs_devices->device_list_mutex);
2616                         goto error;
2617                 }
2618         }
2619         mutex_unlock(&fs_devices->device_list_mutex);
2620
2621         device = btrfs_alloc_device(fs_info, NULL, NULL);
2622         if (IS_ERR(device)) {
2623                 /* we can safely leave the fs_devices entry around */
2624                 ret = PTR_ERR(device);
2625                 goto error;
2626         }
2627
2628         name = rcu_string_strdup(device_path, GFP_KERNEL);
2629         if (!name) {
2630                 ret = -ENOMEM;
2631                 goto error_free_device;
2632         }
2633         rcu_assign_pointer(device->name, name);
2634
2635         trans = btrfs_start_transaction(root, 0);
2636         if (IS_ERR(trans)) {
2637                 ret = PTR_ERR(trans);
2638                 goto error_free_device;
2639         }
2640
2641         q = bdev_get_queue(bdev);
2642         set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
2643         device->generation = trans->transid;
2644         device->io_width = fs_info->sectorsize;
2645         device->io_align = fs_info->sectorsize;
2646         device->sector_size = fs_info->sectorsize;
2647         device->total_bytes = round_down(i_size_read(bdev->bd_inode),
2648                                          fs_info->sectorsize);
2649         device->disk_total_bytes = device->total_bytes;
2650         device->commit_total_bytes = device->total_bytes;
2651         device->fs_info = fs_info;
2652         device->bdev = bdev;
2653         set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
2654         clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
2655         device->mode = FMODE_EXCL;
2656         device->dev_stats_valid = 1;
2657         set_blocksize(device->bdev, BTRFS_BDEV_BLOCKSIZE);
2658
2659         if (seeding_dev) {
2660                 sb->s_flags &= ~SB_RDONLY;
2661                 ret = btrfs_prepare_sprout(fs_info);
2662                 if (ret) {
2663                         btrfs_abort_transaction(trans, ret);
2664                         goto error_trans;
2665                 }
2666         }
2667
2668         device->fs_devices = fs_devices;
2669
2670         mutex_lock(&fs_devices->device_list_mutex);
2671         mutex_lock(&fs_info->chunk_mutex);
2672         list_add_rcu(&device->dev_list, &fs_devices->devices);
2673         list_add(&device->dev_alloc_list, &fs_devices->alloc_list);
2674         fs_devices->num_devices++;
2675         fs_devices->open_devices++;
2676         fs_devices->rw_devices++;
2677         fs_devices->total_devices++;
2678         fs_devices->total_rw_bytes += device->total_bytes;
2679
2680         atomic64_add(device->total_bytes, &fs_info->free_chunk_space);
2681
2682         if (!blk_queue_nonrot(q))
2683                 fs_devices->rotating = 1;
2684
2685         orig_super_total_bytes = btrfs_super_total_bytes(fs_info->super_copy);
2686         btrfs_set_super_total_bytes(fs_info->super_copy,
2687                 round_down(orig_super_total_bytes + device->total_bytes,
2688                            fs_info->sectorsize));
2689
2690         orig_super_num_devices = btrfs_super_num_devices(fs_info->super_copy);
2691         btrfs_set_super_num_devices(fs_info->super_copy,
2692                                     orig_super_num_devices + 1);
2693
2694         /* add sysfs device entry */
2695         btrfs_sysfs_add_device_link(fs_devices, device);
2696
2697         /*
2698          * we've got more storage, clear any full flags on the space
2699          * infos
2700          */
2701         btrfs_clear_space_info_full(fs_info);
2702
2703         mutex_unlock(&fs_info->chunk_mutex);
2704         mutex_unlock(&fs_devices->device_list_mutex);
2705
2706         if (seeding_dev) {
2707                 mutex_lock(&fs_info->chunk_mutex);
2708                 ret = init_first_rw_device(trans, fs_info);
2709                 mutex_unlock(&fs_info->chunk_mutex);
2710                 if (ret) {
2711                         btrfs_abort_transaction(trans, ret);
2712                         goto error_sysfs;
2713                 }
2714         }
2715
2716         ret = btrfs_add_dev_item(trans, device);
2717         if (ret) {
2718                 btrfs_abort_transaction(trans, ret);
2719                 goto error_sysfs;
2720         }
2721
2722         if (seeding_dev) {
2723                 char fsid_buf[BTRFS_UUID_UNPARSED_SIZE];
2724
2725                 ret = btrfs_finish_sprout(trans, fs_info);
2726                 if (ret) {
2727                         btrfs_abort_transaction(trans, ret);
2728                         goto error_sysfs;
2729                 }
2730
2731                 /* Sprouting would change fsid of the mounted root,
2732                  * so rename the fsid on the sysfs
2733                  */
2734                 snprintf(fsid_buf, BTRFS_UUID_UNPARSED_SIZE, "%pU",
2735                                                 fs_info->fs_devices->fsid);
2736                 if (kobject_rename(&fs_devices->fsid_kobj, fsid_buf))
2737                         btrfs_warn(fs_info,
2738                                    "sysfs: failed to create fsid for sprout");
2739         }
2740
2741         ret = btrfs_commit_transaction(trans);
2742
2743         if (seeding_dev) {
2744                 mutex_unlock(&uuid_mutex);
2745                 up_write(&sb->s_umount);
2746                 unlocked = true;
2747
2748                 if (ret) /* transaction commit */
2749                         return ret;
2750
2751                 ret = btrfs_relocate_sys_chunks(fs_info);
2752                 if (ret < 0)
2753                         btrfs_handle_fs_error(fs_info, ret,
2754                                     "Failed to relocate sys chunks after device initialization. This can be fixed using the \"btrfs balance\" command.");
2755                 trans = btrfs_attach_transaction(root);
2756                 if (IS_ERR(trans)) {
2757                         if (PTR_ERR(trans) == -ENOENT)
2758                                 return 0;
2759                         ret = PTR_ERR(trans);
2760                         trans = NULL;
2761                         goto error_sysfs;
2762                 }
2763                 ret = btrfs_commit_transaction(trans);
2764         }
2765
2766         /* Update ctime/mtime for libblkid */
2767         update_dev_time(device_path);
2768         return ret;
2769
2770 error_sysfs:
2771         btrfs_sysfs_rm_device_link(fs_devices, device);
2772         mutex_lock(&fs_info->fs_devices->device_list_mutex);
2773         mutex_lock(&fs_info->chunk_mutex);
2774         list_del_rcu(&device->dev_list);
2775         list_del(&device->dev_alloc_list);
2776         fs_info->fs_devices->num_devices--;
2777         fs_info->fs_devices->open_devices--;
2778         fs_info->fs_devices->rw_devices--;
2779         fs_info->fs_devices->total_devices--;
2780         fs_info->fs_devices->total_rw_bytes -= device->total_bytes;
2781         atomic64_sub(device->total_bytes, &fs_info->free_chunk_space);
2782         btrfs_set_super_total_bytes(fs_info->super_copy,
2783                                     orig_super_total_bytes);
2784         btrfs_set_super_num_devices(fs_info->super_copy,
2785                                     orig_super_num_devices);
2786         mutex_unlock(&fs_info->chunk_mutex);
2787         mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2788 error_trans:
2789         if (seeding_dev)
2790                 sb->s_flags |= SB_RDONLY;
2791         if (trans)
2792                 btrfs_end_transaction(trans);
2793 error_free_device:
2794         btrfs_free_device(device);
2795 error:
2796         blkdev_put(bdev, FMODE_EXCL);
2797         if (seeding_dev && !unlocked) {
2798                 mutex_unlock(&uuid_mutex);
2799                 up_write(&sb->s_umount);
2800         }
2801         return ret;
2802 }
2803
2804 static noinline int btrfs_update_device(struct btrfs_trans_handle *trans,
2805                                         struct btrfs_device *device)
2806 {
2807         int ret;
2808         struct btrfs_path *path;
2809         struct btrfs_root *root = device->fs_info->chunk_root;
2810         struct btrfs_dev_item *dev_item;
2811         struct extent_buffer *leaf;
2812         struct btrfs_key key;
2813
2814         path = btrfs_alloc_path();
2815         if (!path)
2816                 return -ENOMEM;
2817
2818         key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2819         key.type = BTRFS_DEV_ITEM_KEY;
2820         key.offset = device->devid;
2821
2822         ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2823         if (ret < 0)
2824                 goto out;
2825
2826         if (ret > 0) {
2827                 ret = -ENOENT;
2828                 goto out;
2829         }
2830
2831         leaf = path->nodes[0];
2832         dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
2833
2834         btrfs_set_device_id(leaf, dev_item, device->devid);
2835         btrfs_set_device_type(leaf, dev_item, device->type);
2836         btrfs_set_device_io_align(leaf, dev_item, device->io_align);
2837         btrfs_set_device_io_width(leaf, dev_item, device->io_width);
2838         btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
2839         btrfs_set_device_total_bytes(leaf, dev_item,
2840                                      btrfs_device_get_disk_total_bytes(device));
2841         btrfs_set_device_bytes_used(leaf, dev_item,
2842                                     btrfs_device_get_bytes_used(device));
2843         btrfs_mark_buffer_dirty(leaf);
2844
2845 out:
2846         btrfs_free_path(path);
2847         return ret;
2848 }
2849
2850 int btrfs_grow_device(struct btrfs_trans_handle *trans,
2851                       struct btrfs_device *device, u64 new_size)
2852 {
2853         struct btrfs_fs_info *fs_info = device->fs_info;
2854         struct btrfs_super_block *super_copy = fs_info->super_copy;
2855         struct btrfs_fs_devices *fs_devices;
2856         u64 old_total;
2857         u64 diff;
2858
2859         if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
2860                 return -EACCES;
2861
2862         new_size = round_down(new_size, fs_info->sectorsize);
2863
2864         mutex_lock(&fs_info->chunk_mutex);
2865         old_total = btrfs_super_total_bytes(super_copy);
2866         diff = round_down(new_size - device->total_bytes, fs_info->sectorsize);
2867
2868         if (new_size <= device->total_bytes ||
2869             test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
2870                 mutex_unlock(&fs_info->chunk_mutex);
2871                 return -EINVAL;
2872         }
2873
2874         fs_devices = fs_info->fs_devices;
2875
2876         btrfs_set_super_total_bytes(super_copy,
2877                         round_down(old_total + diff, fs_info->sectorsize));
2878         device->fs_devices->total_rw_bytes += diff;
2879
2880         btrfs_device_set_total_bytes(device, new_size);
2881         btrfs_device_set_disk_total_bytes(device, new_size);
2882         btrfs_clear_space_info_full(device->fs_info);
2883         if (list_empty(&device->resized_list))
2884                 list_add_tail(&device->resized_list,
2885                               &fs_devices->resized_devices);
2886         mutex_unlock(&fs_info->chunk_mutex);
2887
2888         return btrfs_update_device(trans, device);
2889 }
2890
2891 static int btrfs_free_chunk(struct btrfs_trans_handle *trans, u64 chunk_offset)
2892 {
2893         struct btrfs_fs_info *fs_info = trans->fs_info;
2894         struct btrfs_root *root = fs_info->chunk_root;
2895         int ret;
2896         struct btrfs_path *path;
2897         struct btrfs_key key;
2898
2899         path = btrfs_alloc_path();
2900         if (!path)
2901                 return -ENOMEM;
2902
2903         key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2904         key.offset = chunk_offset;
2905         key.type = BTRFS_CHUNK_ITEM_KEY;
2906
2907         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
2908         if (ret < 0)
2909                 goto out;
2910         else if (ret > 0) { /* Logic error or corruption */
2911                 btrfs_handle_fs_error(fs_info, -ENOENT,
2912                                       "Failed lookup while freeing chunk.");
2913                 ret = -ENOENT;
2914                 goto out;
2915         }
2916
2917         ret = btrfs_del_item(trans, root, path);
2918         if (ret < 0)
2919                 btrfs_handle_fs_error(fs_info, ret,
2920                                       "Failed to delete chunk item.");
2921 out:
2922         btrfs_free_path(path);
2923         return ret;
2924 }
2925
2926 static int btrfs_del_sys_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
2927 {
2928         struct btrfs_super_block *super_copy = fs_info->super_copy;
2929         struct btrfs_disk_key *disk_key;
2930         struct btrfs_chunk *chunk;
2931         u8 *ptr;
2932         int ret = 0;
2933         u32 num_stripes;
2934         u32 array_size;
2935         u32 len = 0;
2936         u32 cur;
2937         struct btrfs_key key;
2938
2939         mutex_lock(&fs_info->chunk_mutex);
2940         array_size = btrfs_super_sys_array_size(super_copy);
2941
2942         ptr = super_copy->sys_chunk_array;
2943         cur = 0;
2944
2945         while (cur < array_size) {
2946                 disk_key = (struct btrfs_disk_key *)ptr;
2947                 btrfs_disk_key_to_cpu(&key, disk_key);
2948
2949                 len = sizeof(*disk_key);
2950
2951                 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
2952                         chunk = (struct btrfs_chunk *)(ptr + len);
2953                         num_stripes = btrfs_stack_chunk_num_stripes(chunk);
2954                         len += btrfs_chunk_item_size(num_stripes);
2955                 } else {
2956                         ret = -EIO;
2957                         break;
2958                 }
2959                 if (key.objectid == BTRFS_FIRST_CHUNK_TREE_OBJECTID &&
2960                     key.offset == chunk_offset) {
2961                         memmove(ptr, ptr + len, array_size - (cur + len));
2962                         array_size -= len;
2963                         btrfs_set_super_sys_array_size(super_copy, array_size);
2964                 } else {
2965                         ptr += len;
2966                         cur += len;
2967                 }
2968         }
2969         mutex_unlock(&fs_info->chunk_mutex);
2970         return ret;
2971 }
2972
2973 /*
2974  * btrfs_get_chunk_map() - Find the mapping containing the given logical extent.
2975  * @logical: Logical block offset in bytes.
2976  * @length: Length of extent in bytes.
2977  *
2978  * Return: Chunk mapping or ERR_PTR.
2979  */
2980 struct extent_map *btrfs_get_chunk_map(struct btrfs_fs_info *fs_info,
2981                                        u64 logical, u64 length)
2982 {
2983         struct extent_map_tree *em_tree;
2984         struct extent_map *em;
2985
2986         em_tree = &fs_info->mapping_tree.map_tree;
2987         read_lock(&em_tree->lock);
2988         em = lookup_extent_mapping(em_tree, logical, length);
2989         read_unlock(&em_tree->lock);
2990
2991         if (!em) {
2992                 btrfs_crit(fs_info, "unable to find logical %llu length %llu",
2993                            logical, length);
2994                 return ERR_PTR(-EINVAL);
2995         }
2996
2997         if (em->start > logical || em->start + em->len < logical) {
2998                 btrfs_crit(fs_info,
2999                            "found a bad mapping, wanted %llu-%llu, found %llu-%llu",
3000                            logical, length, em->start, em->start + em->len);
3001                 free_extent_map(em);
3002                 return ERR_PTR(-EINVAL);
3003         }
3004
3005         /* callers are responsible for dropping em's ref. */
3006         return em;
3007 }
3008
3009 int btrfs_remove_chunk(struct btrfs_trans_handle *trans, u64 chunk_offset)
3010 {
3011         struct btrfs_fs_info *fs_info = trans->fs_info;
3012         struct extent_map *em;
3013         struct map_lookup *map;
3014         u64 dev_extent_len = 0;
3015         int i, ret = 0;
3016         struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
3017
3018         em = btrfs_get_chunk_map(fs_info, chunk_offset, 1);
3019         if (IS_ERR(em)) {
3020                 /*
3021                  * This is a logic error, but we don't want to just rely on the
3022                  * user having built with ASSERT enabled, so if ASSERT doesn't
3023                  * do anything we still error out.
3024                  */
3025                 ASSERT(0);
3026                 return PTR_ERR(em);
3027         }
3028         map = em->map_lookup;
3029         mutex_lock(&fs_info->chunk_mutex);
3030         check_system_chunk(trans, map->type);
3031         mutex_unlock(&fs_info->chunk_mutex);
3032
3033         /*
3034          * Take the device list mutex to prevent races with the final phase of
3035          * a device replace operation that replaces the device object associated
3036          * with map stripes (dev-replace.c:btrfs_dev_replace_finishing()).
3037          */
3038         mutex_lock(&fs_devices->device_list_mutex);
3039         for (i = 0; i < map->num_stripes; i++) {
3040                 struct btrfs_device *device = map->stripes[i].dev;
3041                 ret = btrfs_free_dev_extent(trans, device,
3042                                             map->stripes[i].physical,
3043                                             &dev_extent_len);
3044                 if (ret) {
3045                         mutex_unlock(&fs_devices->device_list_mutex);
3046                         btrfs_abort_transaction(trans, ret);
3047                         goto out;
3048                 }
3049
3050                 if (device->bytes_used > 0) {
3051                         mutex_lock(&fs_info->chunk_mutex);
3052                         btrfs_device_set_bytes_used(device,
3053                                         device->bytes_used - dev_extent_len);
3054                         atomic64_add(dev_extent_len, &fs_info->free_chunk_space);
3055                         btrfs_clear_space_info_full(fs_info);
3056                         mutex_unlock(&fs_info->chunk_mutex);
3057                 }
3058
3059                 ret = btrfs_update_device(trans, device);
3060                 if (ret) {
3061                         mutex_unlock(&fs_devices->device_list_mutex);
3062                         btrfs_abort_transaction(trans, ret);
3063                         goto out;
3064                 }
3065         }
3066         mutex_unlock(&fs_devices->device_list_mutex);
3067
3068         ret = btrfs_free_chunk(trans, chunk_offset);
3069         if (ret) {
3070                 btrfs_abort_transaction(trans, ret);
3071                 goto out;
3072         }
3073
3074         trace_btrfs_chunk_free(fs_info, map, chunk_offset, em->len);
3075
3076         if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
3077                 ret = btrfs_del_sys_chunk(fs_info, chunk_offset);
3078                 if (ret) {
3079                         btrfs_abort_transaction(trans, ret);
3080                         goto out;
3081                 }
3082         }
3083
3084         ret = btrfs_remove_block_group(trans, chunk_offset, em);
3085         if (ret) {
3086                 btrfs_abort_transaction(trans, ret);
3087                 goto out;
3088         }
3089
3090 out:
3091         /* once for us */
3092         free_extent_map(em);
3093         return ret;
3094 }
3095
3096 static int btrfs_relocate_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
3097 {
3098         struct btrfs_root *root = fs_info->chunk_root;
3099         struct btrfs_trans_handle *trans;
3100         int ret;
3101
3102         /*
3103          * Prevent races with automatic removal of unused block groups.
3104          * After we relocate and before we remove the chunk with offset
3105          * chunk_offset, automatic removal of the block group can kick in,
3106          * resulting in a failure when calling btrfs_remove_chunk() below.
3107          *
3108          * Make sure to acquire this mutex before doing a tree search (dev
3109          * or chunk trees) to find chunks. Otherwise the cleaner kthread might
3110          * call btrfs_remove_chunk() (through btrfs_delete_unused_bgs()) after
3111          * we release the path used to search the chunk/dev tree and before
3112          * the current task acquires this mutex and calls us.
3113          */
3114         lockdep_assert_held(&fs_info->delete_unused_bgs_mutex);
3115
3116         ret = btrfs_can_relocate(fs_info, chunk_offset);
3117         if (ret)
3118                 return -ENOSPC;
3119
3120         /* step one, relocate all the extents inside this chunk */
3121         btrfs_scrub_pause(fs_info);
3122         ret = btrfs_relocate_block_group(fs_info, chunk_offset);
3123         btrfs_scrub_continue(fs_info);
3124         if (ret)
3125                 return ret;
3126
3127         /*
3128          * We add the kobjects here (and after forcing data chunk creation)
3129          * since relocation is the only place we'll create chunks of a new
3130          * type at runtime.  The only place where we'll remove the last
3131          * chunk of a type is the call immediately below this one.  Even
3132          * so, we're protected against races with the cleaner thread since
3133          * we're covered by the delete_unused_bgs_mutex.
3134          */
3135         btrfs_add_raid_kobjects(fs_info);
3136
3137         trans = btrfs_start_trans_remove_block_group(root->fs_info,
3138                                                      chunk_offset);
3139         if (IS_ERR(trans)) {
3140                 ret = PTR_ERR(trans);
3141                 btrfs_handle_fs_error(root->fs_info, ret, NULL);
3142                 return ret;
3143         }
3144
3145         /*
3146          * step two, delete the device extents and the
3147          * chunk tree entries
3148          */
3149         ret = btrfs_remove_chunk(trans, chunk_offset);
3150         btrfs_end_transaction(trans);
3151         return ret;
3152 }
3153
3154 static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info)
3155 {
3156         struct btrfs_root *chunk_root = fs_info->chunk_root;
3157         struct btrfs_path *path;
3158         struct extent_buffer *leaf;
3159         struct btrfs_chunk *chunk;
3160         struct btrfs_key key;
3161         struct btrfs_key found_key;
3162         u64 chunk_type;
3163         bool retried = false;
3164         int failed = 0;
3165         int ret;
3166
3167         path = btrfs_alloc_path();
3168         if (!path)
3169                 return -ENOMEM;
3170
3171 again:
3172         key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
3173         key.offset = (u64)-1;
3174         key.type = BTRFS_CHUNK_ITEM_KEY;
3175
3176         while (1) {
3177                 mutex_lock(&fs_info->delete_unused_bgs_mutex);
3178                 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
3179                 if (ret < 0) {
3180                         mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3181                         goto error;
3182                 }
3183                 BUG_ON(ret == 0); /* Corruption */
3184
3185                 ret = btrfs_previous_item(chunk_root, path, key.objectid,
3186                                           key.type);
3187                 if (ret)
3188                         mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3189                 if (ret < 0)
3190                         goto error;
3191                 if (ret > 0)
3192                         break;
3193
3194                 leaf = path->nodes[0];
3195                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3196
3197                 chunk = btrfs_item_ptr(leaf, path->slots[0],
3198                                        struct btrfs_chunk);
3199                 chunk_type = btrfs_chunk_type(leaf, chunk);
3200                 btrfs_release_path(path);
3201
3202                 if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) {
3203                         ret = btrfs_relocate_chunk(fs_info, found_key.offset);
3204                         if (ret == -ENOSPC)
3205                                 failed++;
3206                         else
3207                                 BUG_ON(ret);