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