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