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