a25d5bf4462f500b1a39669e2a5340b06e3e4d03
[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->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, list);
312                 list_del(&fs_devices->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, 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, 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->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->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 __btrfs_close_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 = __btrfs_close_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                 __btrfs_close_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 list_head *head = &fs_devices->devices;
1108         struct btrfs_device *device;
1109         struct btrfs_device *latest_dev = NULL;
1110         int ret = 0;
1111
1112         flags |= FMODE_EXCL;
1113
1114         list_for_each_entry(device, head, dev_list) {
1115                 /* Just open everything we can; ignore failures here */
1116                 if (btrfs_open_one_device(fs_devices, device, flags, holder))
1117                         continue;
1118
1119                 if (!latest_dev ||
1120                     device->generation > latest_dev->generation)
1121                         latest_dev = device;
1122         }
1123         if (fs_devices->open_devices == 0) {
1124                 ret = -EINVAL;
1125                 goto out;
1126         }
1127         fs_devices->opened = 1;
1128         fs_devices->latest_bdev = latest_dev->bdev;
1129         fs_devices->total_rw_bytes = 0;
1130 out:
1131         return ret;
1132 }
1133
1134 static int devid_cmp(void *priv, struct list_head *a, struct list_head *b)
1135 {
1136         struct btrfs_device *dev1, *dev2;
1137
1138         dev1 = list_entry(a, struct btrfs_device, dev_list);
1139         dev2 = list_entry(b, struct btrfs_device, dev_list);
1140
1141         if (dev1->devid < dev2->devid)
1142                 return -1;
1143         else if (dev1->devid > dev2->devid)
1144                 return 1;
1145         return 0;
1146 }
1147
1148 int btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
1149                        fmode_t flags, void *holder)
1150 {
1151         int ret;
1152
1153         mutex_lock(&uuid_mutex);
1154         if (fs_devices->opened) {
1155                 fs_devices->opened++;
1156                 ret = 0;
1157         } else {
1158                 list_sort(NULL, &fs_devices->devices, devid_cmp);
1159                 ret = __btrfs_open_devices(fs_devices, flags, holder);
1160         }
1161         mutex_unlock(&uuid_mutex);
1162         return ret;
1163 }
1164
1165 static void btrfs_release_disk_super(struct page *page)
1166 {
1167         kunmap(page);
1168         put_page(page);
1169 }
1170
1171 static int btrfs_read_disk_super(struct block_device *bdev, u64 bytenr,
1172                                  struct page **page,
1173                                  struct btrfs_super_block **disk_super)
1174 {
1175         void *p;
1176         pgoff_t index;
1177
1178         /* make sure our super fits in the device */
1179         if (bytenr + PAGE_SIZE >= i_size_read(bdev->bd_inode))
1180                 return 1;
1181
1182         /* make sure our super fits in the page */
1183         if (sizeof(**disk_super) > PAGE_SIZE)
1184                 return 1;
1185
1186         /* make sure our super doesn't straddle pages on disk */
1187         index = bytenr >> PAGE_SHIFT;
1188         if ((bytenr + sizeof(**disk_super) - 1) >> PAGE_SHIFT != index)
1189                 return 1;
1190
1191         /* pull in the page with our super */
1192         *page = read_cache_page_gfp(bdev->bd_inode->i_mapping,
1193                                    index, GFP_KERNEL);
1194
1195         if (IS_ERR_OR_NULL(*page))
1196                 return 1;
1197
1198         p = kmap(*page);
1199
1200         /* align our pointer to the offset of the super block */
1201         *disk_super = p + (bytenr & ~PAGE_MASK);
1202
1203         if (btrfs_super_bytenr(*disk_super) != bytenr ||
1204             btrfs_super_magic(*disk_super) != BTRFS_MAGIC) {
1205                 btrfs_release_disk_super(*page);
1206                 return 1;
1207         }
1208
1209         if ((*disk_super)->label[0] &&
1210                 (*disk_super)->label[BTRFS_LABEL_SIZE - 1])
1211                 (*disk_super)->label[BTRFS_LABEL_SIZE - 1] = '\0';
1212
1213         return 0;
1214 }
1215
1216 /*
1217  * Look for a btrfs signature on a device. This may be called out of the mount path
1218  * and we are not allowed to call set_blocksize during the scan. The superblock
1219  * is read via pagecache
1220  */
1221 int btrfs_scan_one_device(const char *path, fmode_t flags, void *holder,
1222                           struct btrfs_fs_devices **fs_devices_ret)
1223 {
1224         struct btrfs_super_block *disk_super;
1225         struct btrfs_device *device;
1226         struct block_device *bdev;
1227         struct page *page;
1228         int ret = 0;
1229         u64 bytenr;
1230
1231         /*
1232          * we would like to check all the supers, but that would make
1233          * a btrfs mount succeed after a mkfs from a different FS.
1234          * So, we need to add a special mount option to scan for
1235          * later supers, using BTRFS_SUPER_MIRROR_MAX instead
1236          */
1237         bytenr = btrfs_sb_offset(0);
1238         flags |= FMODE_EXCL;
1239         mutex_lock(&uuid_mutex);
1240
1241         bdev = blkdev_get_by_path(path, flags, holder);
1242         if (IS_ERR(bdev)) {
1243                 ret = PTR_ERR(bdev);
1244                 goto error;
1245         }
1246
1247         if (btrfs_read_disk_super(bdev, bytenr, &page, &disk_super)) {
1248                 ret = -EINVAL;
1249                 goto error_bdev_put;
1250         }
1251
1252         device = device_list_add(path, disk_super);
1253         if (IS_ERR(device))
1254                 ret = PTR_ERR(device);
1255         else
1256                 *fs_devices_ret = device->fs_devices;
1257
1258         btrfs_release_disk_super(page);
1259
1260 error_bdev_put:
1261         blkdev_put(bdev, flags);
1262 error:
1263         mutex_unlock(&uuid_mutex);
1264         return ret;
1265 }
1266
1267 /* helper to account the used device space in the range */
1268 int btrfs_account_dev_extents_size(struct btrfs_device *device, u64 start,
1269                                    u64 end, u64 *length)
1270 {
1271         struct btrfs_key key;
1272         struct btrfs_root *root = device->fs_info->dev_root;
1273         struct btrfs_dev_extent *dev_extent;
1274         struct btrfs_path *path;
1275         u64 extent_end;
1276         int ret;
1277         int slot;
1278         struct extent_buffer *l;
1279
1280         *length = 0;
1281
1282         if (start >= device->total_bytes ||
1283                 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
1284                 return 0;
1285
1286         path = btrfs_alloc_path();
1287         if (!path)
1288                 return -ENOMEM;
1289         path->reada = READA_FORWARD;
1290
1291         key.objectid = device->devid;
1292         key.offset = start;
1293         key.type = BTRFS_DEV_EXTENT_KEY;
1294
1295         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1296         if (ret < 0)
1297                 goto out;
1298         if (ret > 0) {
1299                 ret = btrfs_previous_item(root, path, key.objectid, key.type);
1300                 if (ret < 0)
1301                         goto out;
1302         }
1303
1304         while (1) {
1305                 l = path->nodes[0];
1306                 slot = path->slots[0];
1307                 if (slot >= btrfs_header_nritems(l)) {
1308                         ret = btrfs_next_leaf(root, path);
1309                         if (ret == 0)
1310                                 continue;
1311                         if (ret < 0)
1312                                 goto out;
1313
1314                         break;
1315                 }
1316                 btrfs_item_key_to_cpu(l, &key, slot);
1317
1318                 if (key.objectid < device->devid)
1319                         goto next;
1320
1321                 if (key.objectid > device->devid)
1322                         break;
1323
1324                 if (key.type != BTRFS_DEV_EXTENT_KEY)
1325                         goto next;
1326
1327                 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
1328                 extent_end = key.offset + btrfs_dev_extent_length(l,
1329                                                                   dev_extent);
1330                 if (key.offset <= start && extent_end > end) {
1331                         *length = end - start + 1;
1332                         break;
1333                 } else if (key.offset <= start && extent_end > start)
1334                         *length += extent_end - start;
1335                 else if (key.offset > start && extent_end <= end)
1336                         *length += extent_end - key.offset;
1337                 else if (key.offset > start && key.offset <= end) {
1338                         *length += end - key.offset + 1;
1339                         break;
1340                 } else if (key.offset > end)
1341                         break;
1342
1343 next:
1344                 path->slots[0]++;
1345         }
1346         ret = 0;
1347 out:
1348         btrfs_free_path(path);
1349         return ret;
1350 }
1351
1352 static int contains_pending_extent(struct btrfs_transaction *transaction,
1353                                    struct btrfs_device *device,
1354                                    u64 *start, u64 len)
1355 {
1356         struct btrfs_fs_info *fs_info = device->fs_info;
1357         struct extent_map *em;
1358         struct list_head *search_list = &fs_info->pinned_chunks;
1359         int ret = 0;
1360         u64 physical_start = *start;
1361
1362         if (transaction)
1363                 search_list = &transaction->pending_chunks;
1364 again:
1365         list_for_each_entry(em, search_list, list) {
1366                 struct map_lookup *map;
1367                 int i;
1368
1369                 map = em->map_lookup;
1370                 for (i = 0; i < map->num_stripes; i++) {
1371                         u64 end;
1372
1373                         if (map->stripes[i].dev != device)
1374                                 continue;
1375                         if (map->stripes[i].physical >= physical_start + len ||
1376                             map->stripes[i].physical + em->orig_block_len <=
1377                             physical_start)
1378                                 continue;
1379                         /*
1380                          * Make sure that while processing the pinned list we do
1381                          * not override our *start with a lower value, because
1382                          * we can have pinned chunks that fall within this
1383                          * device hole and that have lower physical addresses
1384                          * than the pending chunks we processed before. If we
1385                          * do not take this special care we can end up getting
1386                          * 2 pending chunks that start at the same physical
1387                          * device offsets because the end offset of a pinned
1388                          * chunk can be equal to the start offset of some
1389                          * pending chunk.
1390                          */
1391                         end = map->stripes[i].physical + em->orig_block_len;
1392                         if (end > *start) {
1393                                 *start = end;
1394                                 ret = 1;
1395                         }
1396                 }
1397         }
1398         if (search_list != &fs_info->pinned_chunks) {
1399                 search_list = &fs_info->pinned_chunks;
1400                 goto again;
1401         }
1402
1403         return ret;
1404 }
1405
1406
1407 /*
1408  * find_free_dev_extent_start - find free space in the specified device
1409  * @device:       the device which we search the free space in
1410  * @num_bytes:    the size of the free space that we need
1411  * @search_start: the position from which to begin the search
1412  * @start:        store the start of the free space.
1413  * @len:          the size of the free space. that we find, or the size
1414  *                of the max free space if we don't find suitable free space
1415  *
1416  * this uses a pretty simple search, the expectation is that it is
1417  * called very infrequently and that a given device has a small number
1418  * of extents
1419  *
1420  * @start is used to store the start of the free space if we find. But if we
1421  * don't find suitable free space, it will be used to store the start position
1422  * of the max free space.
1423  *
1424  * @len is used to store the size of the free space that we find.
1425  * But if we don't find suitable free space, it is used to store the size of
1426  * the max free space.
1427  */
1428 int find_free_dev_extent_start(struct btrfs_transaction *transaction,
1429                                struct btrfs_device *device, u64 num_bytes,
1430                                u64 search_start, u64 *start, u64 *len)
1431 {
1432         struct btrfs_fs_info *fs_info = device->fs_info;
1433         struct btrfs_root *root = fs_info->dev_root;
1434         struct btrfs_key key;
1435         struct btrfs_dev_extent *dev_extent;
1436         struct btrfs_path *path;
1437         u64 hole_size;
1438         u64 max_hole_start;
1439         u64 max_hole_size;
1440         u64 extent_end;
1441         u64 search_end = device->total_bytes;
1442         int ret;
1443         int slot;
1444         struct extent_buffer *l;
1445
1446         /*
1447          * We don't want to overwrite the superblock on the drive nor any area
1448          * used by the boot loader (grub for example), so we make sure to start
1449          * at an offset of at least 1MB.
1450          */
1451         search_start = max_t(u64, search_start, SZ_1M);
1452
1453         path = btrfs_alloc_path();
1454         if (!path)
1455                 return -ENOMEM;
1456
1457         max_hole_start = search_start;
1458         max_hole_size = 0;
1459
1460 again:
1461         if (search_start >= search_end ||
1462                 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
1463                 ret = -ENOSPC;
1464                 goto out;
1465         }
1466
1467         path->reada = READA_FORWARD;
1468         path->search_commit_root = 1;
1469         path->skip_locking = 1;
1470
1471         key.objectid = device->devid;
1472         key.offset = search_start;
1473         key.type = BTRFS_DEV_EXTENT_KEY;
1474
1475         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1476         if (ret < 0)
1477                 goto out;
1478         if (ret > 0) {
1479                 ret = btrfs_previous_item(root, path, key.objectid, key.type);
1480                 if (ret < 0)
1481                         goto out;
1482         }
1483
1484         while (1) {
1485                 l = path->nodes[0];
1486                 slot = path->slots[0];
1487                 if (slot >= btrfs_header_nritems(l)) {
1488                         ret = btrfs_next_leaf(root, path);
1489                         if (ret == 0)
1490                                 continue;
1491                         if (ret < 0)
1492                                 goto out;
1493
1494                         break;
1495                 }
1496                 btrfs_item_key_to_cpu(l, &key, slot);
1497
1498                 if (key.objectid < device->devid)
1499                         goto next;
1500
1501                 if (key.objectid > device->devid)
1502                         break;
1503
1504                 if (key.type != BTRFS_DEV_EXTENT_KEY)
1505                         goto next;
1506
1507                 if (key.offset > search_start) {
1508                         hole_size = key.offset - search_start;
1509
1510                         /*
1511                          * Have to check before we set max_hole_start, otherwise
1512                          * we could end up sending back this offset anyway.
1513                          */
1514                         if (contains_pending_extent(transaction, device,
1515                                                     &search_start,
1516                                                     hole_size)) {
1517                                 if (key.offset >= search_start) {
1518                                         hole_size = key.offset - search_start;
1519                                 } else {
1520                                         WARN_ON_ONCE(1);
1521                                         hole_size = 0;
1522                                 }
1523                         }
1524
1525                         if (hole_size > max_hole_size) {
1526                                 max_hole_start = search_start;
1527                                 max_hole_size = hole_size;
1528                         }
1529
1530                         /*
1531                          * If this free space is greater than which we need,
1532                          * it must be the max free space that we have found
1533                          * until now, so max_hole_start must point to the start
1534                          * of this free space and the length of this free space
1535                          * is stored in max_hole_size. Thus, we return
1536                          * max_hole_start and max_hole_size and go back to the
1537                          * caller.
1538                          */
1539                         if (hole_size >= num_bytes) {
1540                                 ret = 0;
1541                                 goto out;
1542                         }
1543                 }
1544
1545                 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
1546                 extent_end = key.offset + btrfs_dev_extent_length(l,
1547                                                                   dev_extent);
1548                 if (extent_end > search_start)
1549                         search_start = extent_end;
1550 next:
1551                 path->slots[0]++;
1552                 cond_resched();
1553         }
1554
1555         /*
1556          * At this point, search_start should be the end of
1557          * allocated dev extents, and when shrinking the device,
1558          * search_end may be smaller than search_start.
1559          */
1560         if (search_end > search_start) {
1561                 hole_size = search_end - search_start;
1562
1563                 if (contains_pending_extent(transaction, device, &search_start,
1564                                             hole_size)) {
1565                         btrfs_release_path(path);
1566                         goto again;
1567                 }
1568
1569                 if (hole_size > max_hole_size) {
1570                         max_hole_start = search_start;
1571                         max_hole_size = hole_size;
1572                 }
1573         }
1574
1575         /* See above. */
1576         if (max_hole_size < num_bytes)
1577                 ret = -ENOSPC;
1578         else
1579                 ret = 0;
1580
1581 out:
1582         btrfs_free_path(path);
1583         *start = max_hole_start;
1584         if (len)
1585                 *len = max_hole_size;
1586         return ret;
1587 }
1588
1589 int find_free_dev_extent(struct btrfs_trans_handle *trans,
1590                          struct btrfs_device *device, u64 num_bytes,
1591                          u64 *start, u64 *len)
1592 {
1593         /* FIXME use last free of some kind */
1594         return find_free_dev_extent_start(trans->transaction, device,
1595                                           num_bytes, 0, start, len);
1596 }
1597
1598 static int btrfs_free_dev_extent(struct btrfs_trans_handle *trans,
1599                           struct btrfs_device *device,
1600                           u64 start, u64 *dev_extent_len)
1601 {
1602         struct btrfs_fs_info *fs_info = device->fs_info;
1603         struct btrfs_root *root = fs_info->dev_root;
1604         int ret;
1605         struct btrfs_path *path;
1606         struct btrfs_key key;
1607         struct btrfs_key found_key;
1608         struct extent_buffer *leaf = NULL;
1609         struct btrfs_dev_extent *extent = NULL;
1610
1611         path = btrfs_alloc_path();
1612         if (!path)
1613                 return -ENOMEM;
1614
1615         key.objectid = device->devid;
1616         key.offset = start;
1617         key.type = BTRFS_DEV_EXTENT_KEY;
1618 again:
1619         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1620         if (ret > 0) {
1621                 ret = btrfs_previous_item(root, path, key.objectid,
1622                                           BTRFS_DEV_EXTENT_KEY);
1623                 if (ret)
1624                         goto out;
1625                 leaf = path->nodes[0];
1626                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1627                 extent = btrfs_item_ptr(leaf, path->slots[0],
1628                                         struct btrfs_dev_extent);
1629                 BUG_ON(found_key.offset > start || found_key.offset +
1630                        btrfs_dev_extent_length(leaf, extent) < start);
1631                 key = found_key;
1632                 btrfs_release_path(path);
1633                 goto again;
1634         } else if (ret == 0) {
1635                 leaf = path->nodes[0];
1636                 extent = btrfs_item_ptr(leaf, path->slots[0],
1637                                         struct btrfs_dev_extent);
1638         } else {
1639                 btrfs_handle_fs_error(fs_info, ret, "Slot search failed");
1640                 goto out;
1641         }
1642
1643         *dev_extent_len = btrfs_dev_extent_length(leaf, extent);
1644
1645         ret = btrfs_del_item(trans, root, path);
1646         if (ret) {
1647                 btrfs_handle_fs_error(fs_info, ret,
1648                                       "Failed to remove dev extent item");
1649         } else {
1650                 set_bit(BTRFS_TRANS_HAVE_FREE_BGS, &trans->transaction->flags);
1651         }
1652 out:
1653         btrfs_free_path(path);
1654         return ret;
1655 }
1656
1657 static int btrfs_alloc_dev_extent(struct btrfs_trans_handle *trans,
1658                                   struct btrfs_device *device,
1659                                   u64 chunk_offset, u64 start, u64 num_bytes)
1660 {
1661         int ret;
1662         struct btrfs_path *path;
1663         struct btrfs_fs_info *fs_info = device->fs_info;
1664         struct btrfs_root *root = fs_info->dev_root;
1665         struct btrfs_dev_extent *extent;
1666         struct extent_buffer *leaf;
1667         struct btrfs_key key;
1668
1669         WARN_ON(!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state));
1670         WARN_ON(test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state));
1671         path = btrfs_alloc_path();
1672         if (!path)
1673                 return -ENOMEM;
1674
1675         key.objectid = device->devid;
1676         key.offset = start;
1677         key.type = BTRFS_DEV_EXTENT_KEY;
1678         ret = btrfs_insert_empty_item(trans, root, path, &key,
1679                                       sizeof(*extent));
1680         if (ret)
1681                 goto out;
1682
1683         leaf = path->nodes[0];
1684         extent = btrfs_item_ptr(leaf, path->slots[0],
1685                                 struct btrfs_dev_extent);
1686         btrfs_set_dev_extent_chunk_tree(leaf, extent,
1687                                         BTRFS_CHUNK_TREE_OBJECTID);
1688         btrfs_set_dev_extent_chunk_objectid(leaf, extent,
1689                                             BTRFS_FIRST_CHUNK_TREE_OBJECTID);
1690         btrfs_set_dev_extent_chunk_offset(leaf, extent, chunk_offset);
1691
1692         btrfs_set_dev_extent_length(leaf, extent, num_bytes);
1693         btrfs_mark_buffer_dirty(leaf);
1694 out:
1695         btrfs_free_path(path);
1696         return ret;
1697 }
1698
1699 static u64 find_next_chunk(struct btrfs_fs_info *fs_info)
1700 {
1701         struct extent_map_tree *em_tree;
1702         struct extent_map *em;
1703         struct rb_node *n;
1704         u64 ret = 0;
1705
1706         em_tree = &fs_info->mapping_tree.map_tree;
1707         read_lock(&em_tree->lock);
1708         n = rb_last(&em_tree->map);
1709         if (n) {
1710                 em = rb_entry(n, struct extent_map, rb_node);
1711                 ret = em->start + em->len;
1712         }
1713         read_unlock(&em_tree->lock);
1714
1715         return ret;
1716 }
1717
1718 static noinline int find_next_devid(struct btrfs_fs_info *fs_info,
1719                                     u64 *devid_ret)
1720 {
1721         int ret;
1722         struct btrfs_key key;
1723         struct btrfs_key found_key;
1724         struct btrfs_path *path;
1725
1726         path = btrfs_alloc_path();
1727         if (!path)
1728                 return -ENOMEM;
1729
1730         key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1731         key.type = BTRFS_DEV_ITEM_KEY;
1732         key.offset = (u64)-1;
1733
1734         ret = btrfs_search_slot(NULL, fs_info->chunk_root, &key, path, 0, 0);
1735         if (ret < 0)
1736                 goto error;
1737
1738         BUG_ON(ret == 0); /* Corruption */
1739
1740         ret = btrfs_previous_item(fs_info->chunk_root, path,
1741                                   BTRFS_DEV_ITEMS_OBJECTID,
1742                                   BTRFS_DEV_ITEM_KEY);
1743         if (ret) {
1744                 *devid_ret = 1;
1745         } else {
1746                 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
1747                                       path->slots[0]);
1748                 *devid_ret = found_key.offset + 1;
1749         }
1750         ret = 0;
1751 error:
1752         btrfs_free_path(path);
1753         return ret;
1754 }
1755
1756 /*
1757  * the device information is stored in the chunk root
1758  * the btrfs_device struct should be fully filled in
1759  */
1760 static int btrfs_add_dev_item(struct btrfs_trans_handle *trans,
1761                             struct btrfs_fs_info *fs_info,
1762                             struct btrfs_device *device)
1763 {
1764         struct btrfs_root *root = fs_info->chunk_root;
1765         int ret;
1766         struct btrfs_path *path;
1767         struct btrfs_dev_item *dev_item;
1768         struct extent_buffer *leaf;
1769         struct btrfs_key key;
1770         unsigned long ptr;
1771
1772         path = btrfs_alloc_path();
1773         if (!path)
1774                 return -ENOMEM;
1775
1776         key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1777         key.type = BTRFS_DEV_ITEM_KEY;
1778         key.offset = device->devid;
1779
1780         ret = btrfs_insert_empty_item(trans, root, path, &key,
1781                                       sizeof(*dev_item));
1782         if (ret)
1783                 goto out;
1784
1785         leaf = path->nodes[0];
1786         dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
1787
1788         btrfs_set_device_id(leaf, dev_item, device->devid);
1789         btrfs_set_device_generation(leaf, dev_item, 0);
1790         btrfs_set_device_type(leaf, dev_item, device->type);
1791         btrfs_set_device_io_align(leaf, dev_item, device->io_align);
1792         btrfs_set_device_io_width(leaf, dev_item, device->io_width);
1793         btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
1794         btrfs_set_device_total_bytes(leaf, dev_item,
1795                                      btrfs_device_get_disk_total_bytes(device));
1796         btrfs_set_device_bytes_used(leaf, dev_item,
1797                                     btrfs_device_get_bytes_used(device));
1798         btrfs_set_device_group(leaf, dev_item, 0);
1799         btrfs_set_device_seek_speed(leaf, dev_item, 0);
1800         btrfs_set_device_bandwidth(leaf, dev_item, 0);
1801         btrfs_set_device_start_offset(leaf, dev_item, 0);
1802
1803         ptr = btrfs_device_uuid(dev_item);
1804         write_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
1805         ptr = btrfs_device_fsid(dev_item);
1806         write_extent_buffer(leaf, fs_info->fsid, ptr, BTRFS_FSID_SIZE);
1807         btrfs_mark_buffer_dirty(leaf);
1808
1809         ret = 0;
1810 out:
1811         btrfs_free_path(path);
1812         return ret;
1813 }
1814
1815 /*
1816  * Function to update ctime/mtime for a given device path.
1817  * Mainly used for ctime/mtime based probe like libblkid.
1818  */
1819 static void update_dev_time(const char *path_name)
1820 {
1821         struct file *filp;
1822
1823         filp = filp_open(path_name, O_RDWR, 0);
1824         if (IS_ERR(filp))
1825                 return;
1826         file_update_time(filp);
1827         filp_close(filp, NULL);
1828 }
1829
1830 static int btrfs_rm_dev_item(struct btrfs_fs_info *fs_info,
1831                              struct btrfs_device *device)
1832 {
1833         struct btrfs_root *root = fs_info->chunk_root;
1834         int ret;
1835         struct btrfs_path *path;
1836         struct btrfs_key key;
1837         struct btrfs_trans_handle *trans;
1838
1839         path = btrfs_alloc_path();
1840         if (!path)
1841                 return -ENOMEM;
1842
1843         trans = btrfs_start_transaction(root, 0);
1844         if (IS_ERR(trans)) {
1845                 btrfs_free_path(path);
1846                 return PTR_ERR(trans);
1847         }
1848         key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1849         key.type = BTRFS_DEV_ITEM_KEY;
1850         key.offset = device->devid;
1851
1852         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1853         if (ret) {
1854                 if (ret > 0)
1855                         ret = -ENOENT;
1856                 btrfs_abort_transaction(trans, ret);
1857                 btrfs_end_transaction(trans);
1858                 goto out;
1859         }
1860
1861         ret = btrfs_del_item(trans, root, path);
1862         if (ret) {
1863                 btrfs_abort_transaction(trans, ret);
1864                 btrfs_end_transaction(trans);
1865         }
1866
1867 out:
1868         btrfs_free_path(path);
1869         if (!ret)
1870                 ret = btrfs_commit_transaction(trans);
1871         return ret;
1872 }
1873
1874 /*
1875  * Verify that @num_devices satisfies the RAID profile constraints in the whole
1876  * filesystem. It's up to the caller to adjust that number regarding eg. device
1877  * replace.
1878  */
1879 static int btrfs_check_raid_min_devices(struct btrfs_fs_info *fs_info,
1880                 u64 num_devices)
1881 {
1882         u64 all_avail;
1883         unsigned seq;
1884         int i;
1885
1886         do {
1887                 seq = read_seqbegin(&fs_info->profiles_lock);
1888
1889                 all_avail = fs_info->avail_data_alloc_bits |
1890                             fs_info->avail_system_alloc_bits |
1891                             fs_info->avail_metadata_alloc_bits;
1892         } while (read_seqretry(&fs_info->profiles_lock, seq));
1893
1894         for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
1895                 if (!(all_avail & btrfs_raid_group[i]))
1896                         continue;
1897
1898                 if (num_devices < btrfs_raid_array[i].devs_min) {
1899                         int ret = btrfs_raid_mindev_error[i];
1900
1901                         if (ret)
1902                                 return ret;
1903                 }
1904         }
1905
1906         return 0;
1907 }
1908
1909 static struct btrfs_device * btrfs_find_next_active_device(
1910                 struct btrfs_fs_devices *fs_devs, struct btrfs_device *device)
1911 {
1912         struct btrfs_device *next_device;
1913
1914         list_for_each_entry(next_device, &fs_devs->devices, dev_list) {
1915                 if (next_device != device &&
1916                     !test_bit(BTRFS_DEV_STATE_MISSING, &next_device->dev_state)
1917                     && next_device->bdev)
1918                         return next_device;
1919         }
1920
1921         return NULL;
1922 }
1923
1924 /*
1925  * Helper function to check if the given device is part of s_bdev / latest_bdev
1926  * and replace it with the provided or the next active device, in the context
1927  * where this function called, there should be always be another device (or
1928  * this_dev) which is active.
1929  */
1930 void btrfs_assign_next_active_device(struct btrfs_fs_info *fs_info,
1931                 struct btrfs_device *device, struct btrfs_device *this_dev)
1932 {
1933         struct btrfs_device *next_device;
1934
1935         if (this_dev)
1936                 next_device = this_dev;
1937         else
1938                 next_device = btrfs_find_next_active_device(fs_info->fs_devices,
1939                                                                 device);
1940         ASSERT(next_device);
1941
1942         if (fs_info->sb->s_bdev &&
1943                         (fs_info->sb->s_bdev == device->bdev))
1944                 fs_info->sb->s_bdev = next_device->bdev;
1945
1946         if (fs_info->fs_devices->latest_bdev == device->bdev)
1947                 fs_info->fs_devices->latest_bdev = next_device->bdev;
1948 }
1949
1950 int btrfs_rm_device(struct btrfs_fs_info *fs_info, const char *device_path,
1951                 u64 devid)
1952 {
1953         struct btrfs_device *device;
1954         struct btrfs_fs_devices *cur_devices;
1955         u64 num_devices;
1956         int ret = 0;
1957
1958         mutex_lock(&fs_info->volume_mutex);
1959         mutex_lock(&uuid_mutex);
1960
1961         num_devices = fs_info->fs_devices->num_devices;
1962         btrfs_dev_replace_read_lock(&fs_info->dev_replace);
1963         if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace)) {
1964                 WARN_ON(num_devices < 1);
1965                 num_devices--;
1966         }
1967         btrfs_dev_replace_read_unlock(&fs_info->dev_replace);
1968
1969         ret = btrfs_check_raid_min_devices(fs_info, num_devices - 1);
1970         if (ret)
1971                 goto out;
1972
1973         ret = btrfs_find_device_by_devspec(fs_info, devid, device_path,
1974                                            &device);
1975         if (ret)
1976                 goto out;
1977
1978         if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
1979                 ret = BTRFS_ERROR_DEV_TGT_REPLACE;
1980                 goto out;
1981         }
1982
1983         if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
1984             fs_info->fs_devices->rw_devices == 1) {
1985                 ret = BTRFS_ERROR_DEV_ONLY_WRITABLE;
1986                 goto out;
1987         }
1988
1989         if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
1990                 mutex_lock(&fs_info->chunk_mutex);
1991                 list_del_init(&device->dev_alloc_list);
1992                 device->fs_devices->rw_devices--;
1993                 mutex_unlock(&fs_info->chunk_mutex);
1994         }
1995
1996         mutex_unlock(&uuid_mutex);
1997         ret = btrfs_shrink_device(device, 0);
1998         mutex_lock(&uuid_mutex);
1999         if (ret)
2000                 goto error_undo;
2001
2002         /*
2003          * TODO: the superblock still includes this device in its num_devices
2004          * counter although write_all_supers() is not locked out. This
2005          * could give a filesystem state which requires a degraded mount.
2006          */
2007         ret = btrfs_rm_dev_item(fs_info, device);
2008         if (ret)
2009                 goto error_undo;
2010
2011         clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
2012         btrfs_scrub_cancel_dev(fs_info, device);
2013
2014         /*
2015          * the device list mutex makes sure that we don't change
2016          * the device list while someone else is writing out all
2017          * the device supers. Whoever is writing all supers, should
2018          * lock the device list mutex before getting the number of
2019          * devices in the super block (super_copy). Conversely,
2020          * whoever updates the number of devices in the super block
2021          * (super_copy) should hold the device list mutex.
2022          */
2023
2024         cur_devices = device->fs_devices;
2025         mutex_lock(&fs_info->fs_devices->device_list_mutex);
2026         list_del_rcu(&device->dev_list);
2027
2028         device->fs_devices->num_devices--;
2029         device->fs_devices->total_devices--;
2030
2031         if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state))
2032                 device->fs_devices->missing_devices--;
2033
2034         btrfs_assign_next_active_device(fs_info, device, NULL);
2035
2036         if (device->bdev) {
2037                 device->fs_devices->open_devices--;
2038                 /* remove sysfs entry */
2039                 btrfs_sysfs_rm_device_link(fs_info->fs_devices, device);
2040         }
2041
2042         num_devices = btrfs_super_num_devices(fs_info->super_copy) - 1;
2043         btrfs_set_super_num_devices(fs_info->super_copy, num_devices);
2044         mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2045
2046         /*
2047          * at this point, the device is zero sized and detached from
2048          * the devices list.  All that's left is to zero out the old
2049          * supers and free the device.
2050          */
2051         if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
2052                 btrfs_scratch_superblocks(device->bdev, device->name->str);
2053
2054         btrfs_close_bdev(device);
2055         call_rcu(&device->rcu, free_device_rcu);
2056
2057         if (cur_devices->open_devices == 0) {
2058                 struct btrfs_fs_devices *fs_devices;
2059                 fs_devices = fs_info->fs_devices;
2060                 while (fs_devices) {
2061                         if (fs_devices->seed == cur_devices) {
2062                                 fs_devices->seed = cur_devices->seed;
2063                                 break;
2064                         }
2065                         fs_devices = fs_devices->seed;
2066                 }
2067                 cur_devices->seed = NULL;
2068                 __btrfs_close_devices(cur_devices);
2069                 free_fs_devices(cur_devices);
2070         }
2071
2072 out:
2073         mutex_unlock(&uuid_mutex);
2074         mutex_unlock(&fs_info->volume_mutex);
2075         return ret;
2076
2077 error_undo:
2078         if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
2079                 mutex_lock(&fs_info->chunk_mutex);
2080                 list_add(&device->dev_alloc_list,
2081                          &fs_info->fs_devices->alloc_list);
2082                 device->fs_devices->rw_devices++;
2083                 mutex_unlock(&fs_info->chunk_mutex);
2084         }
2085         goto out;
2086 }
2087
2088 void btrfs_rm_dev_replace_remove_srcdev(struct btrfs_fs_info *fs_info,
2089                                         struct btrfs_device *srcdev)
2090 {
2091         struct btrfs_fs_devices *fs_devices;
2092
2093         lockdep_assert_held(&fs_info->fs_devices->device_list_mutex);
2094
2095         /*
2096          * in case of fs with no seed, srcdev->fs_devices will point
2097          * to fs_devices of fs_info. However when the dev being replaced is
2098          * a seed dev it will point to the seed's local fs_devices. In short
2099          * srcdev will have its correct fs_devices in both the cases.
2100          */
2101         fs_devices = srcdev->fs_devices;
2102
2103         list_del_rcu(&srcdev->dev_list);
2104         list_del(&srcdev->dev_alloc_list);
2105         fs_devices->num_devices--;
2106         if (test_bit(BTRFS_DEV_STATE_MISSING, &srcdev->dev_state))
2107                 fs_devices->missing_devices--;
2108
2109         if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &srcdev->dev_state))
2110                 fs_devices->rw_devices--;
2111
2112         if (srcdev->bdev)
2113                 fs_devices->open_devices--;
2114 }
2115
2116 void btrfs_rm_dev_replace_free_srcdev(struct btrfs_fs_info *fs_info,
2117                                       struct btrfs_device *srcdev)
2118 {
2119         struct btrfs_fs_devices *fs_devices = srcdev->fs_devices;
2120
2121         if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &srcdev->dev_state)) {
2122                 /* zero out the old super if it is writable */
2123                 btrfs_scratch_superblocks(srcdev->bdev, srcdev->name->str);
2124         }
2125
2126         btrfs_close_bdev(srcdev);
2127         call_rcu(&srcdev->rcu, free_device_rcu);
2128
2129         /* if this is no devs we rather delete the fs_devices */
2130         if (!fs_devices->num_devices) {
2131                 struct btrfs_fs_devices *tmp_fs_devices;
2132
2133                 /*
2134                  * On a mounted FS, num_devices can't be zero unless it's a
2135                  * seed. In case of a seed device being replaced, the replace
2136                  * target added to the sprout FS, so there will be no more
2137                  * device left under the seed FS.
2138                  */
2139                 ASSERT(fs_devices->seeding);
2140
2141                 tmp_fs_devices = fs_info->fs_devices;
2142                 while (tmp_fs_devices) {
2143                         if (tmp_fs_devices->seed == fs_devices) {
2144                                 tmp_fs_devices->seed = fs_devices->seed;
2145                                 break;
2146                         }
2147                         tmp_fs_devices = tmp_fs_devices->seed;
2148                 }
2149                 fs_devices->seed = NULL;
2150                 __btrfs_close_devices(fs_devices);
2151                 free_fs_devices(fs_devices);
2152         }
2153 }
2154
2155 void btrfs_destroy_dev_replace_tgtdev(struct btrfs_fs_info *fs_info,
2156                                       struct btrfs_device *tgtdev)
2157 {
2158         mutex_lock(&uuid_mutex);
2159         WARN_ON(!tgtdev);
2160         mutex_lock(&fs_info->fs_devices->device_list_mutex);
2161
2162         btrfs_sysfs_rm_device_link(fs_info->fs_devices, tgtdev);
2163
2164         if (tgtdev->bdev)
2165                 fs_info->fs_devices->open_devices--;
2166
2167         fs_info->fs_devices->num_devices--;
2168
2169         btrfs_assign_next_active_device(fs_info, tgtdev, NULL);
2170
2171         list_del_rcu(&tgtdev->dev_list);
2172
2173         mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2174         mutex_unlock(&uuid_mutex);
2175
2176         /*
2177          * The update_dev_time() with in btrfs_scratch_superblocks()
2178          * may lead to a call to btrfs_show_devname() which will try
2179          * to hold device_list_mutex. And here this device
2180          * is already out of device list, so we don't have to hold
2181          * the device_list_mutex lock.
2182          */
2183         btrfs_scratch_superblocks(tgtdev->bdev, tgtdev->name->str);
2184
2185         btrfs_close_bdev(tgtdev);
2186         call_rcu(&tgtdev->rcu, free_device_rcu);
2187 }
2188
2189 static int btrfs_find_device_by_path(struct btrfs_fs_info *fs_info,
2190                                      const char *device_path,
2191                                      struct btrfs_device **device)
2192 {
2193         int ret = 0;
2194         struct btrfs_super_block *disk_super;
2195         u64 devid;
2196         u8 *dev_uuid;
2197         struct block_device *bdev;
2198         struct buffer_head *bh;
2199
2200         *device = NULL;
2201         ret = btrfs_get_bdev_and_sb(device_path, FMODE_READ,
2202                                     fs_info->bdev_holder, 0, &bdev, &bh);
2203         if (ret)
2204                 return ret;
2205         disk_super = (struct btrfs_super_block *)bh->b_data;
2206         devid = btrfs_stack_device_id(&disk_super->dev_item);
2207         dev_uuid = disk_super->dev_item.uuid;
2208         *device = btrfs_find_device(fs_info, devid, dev_uuid, disk_super->fsid);
2209         brelse(bh);
2210         if (!*device)
2211                 ret = -ENOENT;
2212         blkdev_put(bdev, FMODE_READ);
2213         return ret;
2214 }
2215
2216 int btrfs_find_device_missing_or_by_path(struct btrfs_fs_info *fs_info,
2217                                          const char *device_path,
2218                                          struct btrfs_device **device)
2219 {
2220         *device = NULL;
2221         if (strcmp(device_path, "missing") == 0) {
2222                 struct list_head *devices;
2223                 struct btrfs_device *tmp;
2224
2225                 devices = &fs_info->fs_devices->devices;
2226                 /*
2227                  * It is safe to read the devices since the volume_mutex
2228                  * is held by the caller.
2229                  */
2230                 list_for_each_entry(tmp, devices, dev_list) {
2231                         if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
2232                                         &tmp->dev_state) && !tmp->bdev) {
2233                                 *device = tmp;
2234                                 break;
2235                         }
2236                 }
2237
2238                 if (!*device)
2239                         return BTRFS_ERROR_DEV_MISSING_NOT_FOUND;
2240
2241                 return 0;
2242         } else {
2243                 return btrfs_find_device_by_path(fs_info, device_path, device);
2244         }
2245 }
2246
2247 /*
2248  * Lookup a device given by device id, or the path if the id is 0.
2249  */
2250 int btrfs_find_device_by_devspec(struct btrfs_fs_info *fs_info, u64 devid,
2251                                  const char *devpath,
2252                                  struct btrfs_device **device)
2253 {
2254         int ret;
2255
2256         if (devid) {
2257                 ret = 0;
2258                 *device = btrfs_find_device(fs_info, devid, NULL, NULL);
2259                 if (!*device)
2260                         ret = -ENOENT;
2261         } else {
2262                 if (!devpath || !devpath[0])
2263                         return -EINVAL;
2264
2265                 ret = btrfs_find_device_missing_or_by_path(fs_info, devpath,
2266                                                            device);
2267         }
2268         return ret;
2269 }
2270
2271 /*
2272  * does all the dirty work required for changing file system's UUID.
2273  */
2274 static int btrfs_prepare_sprout(struct btrfs_fs_info *fs_info)
2275 {
2276         struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2277         struct btrfs_fs_devices *old_devices;
2278         struct btrfs_fs_devices *seed_devices;
2279         struct btrfs_super_block *disk_super = fs_info->super_copy;
2280         struct btrfs_device *device;
2281         u64 super_flags;
2282
2283         lockdep_assert_held(&uuid_mutex);
2284         if (!fs_devices->seeding)
2285                 return -EINVAL;
2286
2287         seed_devices = alloc_fs_devices(NULL);
2288         if (IS_ERR(seed_devices))
2289                 return PTR_ERR(seed_devices);
2290
2291         old_devices = clone_fs_devices(fs_devices);
2292         if (IS_ERR(old_devices)) {
2293                 kfree(seed_devices);
2294                 return PTR_ERR(old_devices);
2295         }
2296
2297         list_add(&old_devices->list, &fs_uuids);
2298
2299         memcpy(seed_devices, fs_devices, sizeof(*seed_devices));
2300         seed_devices->opened = 1;
2301         INIT_LIST_HEAD(&seed_devices->devices);
2302         INIT_LIST_HEAD(&seed_devices->alloc_list);
2303         mutex_init(&seed_devices->device_list_mutex);
2304
2305         mutex_lock(&fs_info->fs_devices->device_list_mutex);
2306         list_splice_init_rcu(&fs_devices->devices, &seed_devices->devices,
2307                               synchronize_rcu);
2308         list_for_each_entry(device, &seed_devices->devices, dev_list)
2309                 device->fs_devices = seed_devices;
2310
2311         mutex_lock(&fs_info->chunk_mutex);
2312         list_splice_init(&fs_devices->alloc_list, &seed_devices->alloc_list);
2313         mutex_unlock(&fs_info->chunk_mutex);
2314
2315         fs_devices->seeding = 0;
2316         fs_devices->num_devices = 0;
2317         fs_devices->open_devices = 0;
2318         fs_devices->missing_devices = 0;
2319         fs_devices->rotating = 0;
2320         fs_devices->seed = seed_devices;
2321
2322         generate_random_uuid(fs_devices->fsid);
2323         memcpy(fs_info->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
2324         memcpy(disk_super->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
2325         mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2326
2327         super_flags = btrfs_super_flags(disk_super) &
2328                       ~BTRFS_SUPER_FLAG_SEEDING;
2329         btrfs_set_super_flags(disk_super, super_flags);
2330
2331         return 0;
2332 }
2333
2334 /*
2335  * Store the expected generation for seed devices in device items.
2336  */
2337 static int btrfs_finish_sprout(struct btrfs_trans_handle *trans,
2338                                struct btrfs_fs_info *fs_info)
2339 {
2340         struct btrfs_root *root = fs_info->chunk_root;
2341         struct btrfs_path *path;
2342         struct extent_buffer *leaf;
2343         struct btrfs_dev_item *dev_item;
2344         struct btrfs_device *device;
2345         struct btrfs_key key;
2346         u8 fs_uuid[BTRFS_FSID_SIZE];
2347         u8 dev_uuid[BTRFS_UUID_SIZE];
2348         u64 devid;
2349         int ret;
2350
2351         path = btrfs_alloc_path();
2352         if (!path)
2353                 return -ENOMEM;
2354
2355         key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2356         key.offset = 0;
2357         key.type = BTRFS_DEV_ITEM_KEY;
2358
2359         while (1) {
2360                 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2361                 if (ret < 0)
2362                         goto error;
2363
2364                 leaf = path->nodes[0];
2365 next_slot:
2366                 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
2367                         ret = btrfs_next_leaf(root, path);
2368                         if (ret > 0)
2369                                 break;
2370                         if (ret < 0)
2371                                 goto error;
2372                         leaf = path->nodes[0];
2373                         btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2374                         btrfs_release_path(path);
2375                         continue;
2376                 }
2377
2378                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2379                 if (key.objectid != BTRFS_DEV_ITEMS_OBJECTID ||
2380                     key.type != BTRFS_DEV_ITEM_KEY)
2381                         break;
2382
2383                 dev_item = btrfs_item_ptr(leaf, path->slots[0],
2384                                           struct btrfs_dev_item);
2385                 devid = btrfs_device_id(leaf, dev_item);
2386                 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
2387                                    BTRFS_UUID_SIZE);
2388                 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
2389                                    BTRFS_FSID_SIZE);
2390                 device = btrfs_find_device(fs_info, devid, dev_uuid, fs_uuid);
2391                 BUG_ON(!device); /* Logic error */
2392
2393                 if (device->fs_devices->seeding) {
2394                         btrfs_set_device_generation(leaf, dev_item,
2395                                                     device->generation);
2396                         btrfs_mark_buffer_dirty(leaf);
2397                 }
2398
2399                 path->slots[0]++;
2400                 goto next_slot;
2401         }
2402         ret = 0;
2403 error:
2404         btrfs_free_path(path);
2405         return ret;
2406 }
2407
2408 int btrfs_init_new_device(struct btrfs_fs_info *fs_info, const char *device_path)
2409 {
2410         struct btrfs_root *root = fs_info->dev_root;
2411         struct request_queue *q;
2412         struct btrfs_trans_handle *trans;
2413         struct btrfs_device *device;
2414         struct block_device *bdev;
2415         struct list_head *devices;
2416         struct super_block *sb = fs_info->sb;
2417         struct rcu_string *name;
2418         u64 tmp;
2419         int seeding_dev = 0;
2420         int ret = 0;
2421         bool unlocked = false;
2422
2423         if (sb_rdonly(sb) && !fs_info->fs_devices->seeding)
2424                 return -EROFS;
2425
2426         bdev = blkdev_get_by_path(device_path, FMODE_WRITE | FMODE_EXCL,
2427                                   fs_info->bdev_holder);
2428         if (IS_ERR(bdev))
2429                 return PTR_ERR(bdev);
2430
2431         if (fs_info->fs_devices->seeding) {
2432                 seeding_dev = 1;
2433                 down_write(&sb->s_umount);
2434                 mutex_lock(&uuid_mutex);
2435         }
2436
2437         filemap_write_and_wait(bdev->bd_inode->i_mapping);
2438
2439         devices = &fs_info->fs_devices->devices;
2440
2441         mutex_lock(&fs_info->fs_devices->device_list_mutex);
2442         list_for_each_entry(device, devices, dev_list) {
2443                 if (device->bdev == bdev) {
2444                         ret = -EEXIST;
2445                         mutex_unlock(
2446                                 &fs_info->fs_devices->device_list_mutex);
2447                         goto error;
2448                 }
2449         }
2450         mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2451
2452         device = btrfs_alloc_device(fs_info, NULL, NULL);
2453         if (IS_ERR(device)) {
2454                 /* we can safely leave the fs_devices entry around */
2455                 ret = PTR_ERR(device);
2456                 goto error;
2457         }
2458
2459         name = rcu_string_strdup(device_path, GFP_KERNEL);
2460         if (!name) {
2461                 ret = -ENOMEM;
2462                 goto error_free_device;
2463         }
2464         rcu_assign_pointer(device->name, name);
2465
2466         trans = btrfs_start_transaction(root, 0);
2467         if (IS_ERR(trans)) {
2468                 ret = PTR_ERR(trans);
2469                 goto error_free_device;
2470         }
2471
2472         q = bdev_get_queue(bdev);
2473         set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
2474         device->generation = trans->transid;
2475         device->io_width = fs_info->sectorsize;
2476         device->io_align = fs_info->sectorsize;
2477         device->sector_size = fs_info->sectorsize;
2478         device->total_bytes = round_down(i_size_read(bdev->bd_inode),
2479                                          fs_info->sectorsize);
2480         device->disk_total_bytes = device->total_bytes;
2481         device->commit_total_bytes = device->total_bytes;
2482         device->fs_info = fs_info;
2483         device->bdev = bdev;
2484         set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
2485         clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
2486         device->mode = FMODE_EXCL;
2487         device->dev_stats_valid = 1;
2488         set_blocksize(device->bdev, BTRFS_BDEV_BLOCKSIZE);
2489
2490         if (seeding_dev) {
2491                 sb->s_flags &= ~SB_RDONLY;
2492                 ret = btrfs_prepare_sprout(fs_info);
2493                 if (ret) {
2494                         btrfs_abort_transaction(trans, ret);
2495                         goto error_trans;
2496                 }
2497         }
2498
2499         device->fs_devices = fs_info->fs_devices;
2500
2501         mutex_lock(&fs_info->fs_devices->device_list_mutex);
2502         mutex_lock(&fs_info->chunk_mutex);
2503         list_add_rcu(&device->dev_list, &fs_info->fs_devices->devices);
2504         list_add(&device->dev_alloc_list,
2505                  &fs_info->fs_devices->alloc_list);
2506         fs_info->fs_devices->num_devices++;
2507         fs_info->fs_devices->open_devices++;
2508         fs_info->fs_devices->rw_devices++;
2509         fs_info->fs_devices->total_devices++;
2510         fs_info->fs_devices->total_rw_bytes += device->total_bytes;
2511
2512         atomic64_add(device->total_bytes, &fs_info->free_chunk_space);
2513
2514         if (!blk_queue_nonrot(q))
2515                 fs_info->fs_devices->rotating = 1;
2516
2517         tmp = btrfs_super_total_bytes(fs_info->super_copy);
2518         btrfs_set_super_total_bytes(fs_info->super_copy,
2519                 round_down(tmp + device->total_bytes, fs_info->sectorsize));
2520
2521         tmp = btrfs_super_num_devices(fs_info->super_copy);
2522         btrfs_set_super_num_devices(fs_info->super_copy, tmp + 1);
2523
2524         /* add sysfs device entry */
2525         btrfs_sysfs_add_device_link(fs_info->fs_devices, device);
2526
2527         /*
2528          * we've got more storage, clear any full flags on the space
2529          * infos
2530          */
2531         btrfs_clear_space_info_full(fs_info);
2532
2533         mutex_unlock(&fs_info->chunk_mutex);
2534         mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2535
2536         if (seeding_dev) {
2537                 mutex_lock(&fs_info->chunk_mutex);
2538                 ret = init_first_rw_device(trans, fs_info);
2539                 mutex_unlock(&fs_info->chunk_mutex);
2540                 if (ret) {
2541                         btrfs_abort_transaction(trans, ret);
2542                         goto error_sysfs;
2543                 }
2544         }
2545
2546         ret = btrfs_add_dev_item(trans, fs_info, device);
2547         if (ret) {
2548                 btrfs_abort_transaction(trans, ret);
2549                 goto error_sysfs;
2550         }
2551
2552         if (seeding_dev) {
2553                 char fsid_buf[BTRFS_UUID_UNPARSED_SIZE];
2554
2555                 ret = btrfs_finish_sprout(trans, fs_info);
2556                 if (ret) {
2557                         btrfs_abort_transaction(trans, ret);
2558                         goto error_sysfs;
2559                 }
2560
2561                 /* Sprouting would change fsid of the mounted root,
2562                  * so rename the fsid on the sysfs
2563                  */
2564                 snprintf(fsid_buf, BTRFS_UUID_UNPARSED_SIZE, "%pU",
2565                                                 fs_info->fsid);
2566                 if (kobject_rename(&fs_info->fs_devices->fsid_kobj, fsid_buf))
2567                         btrfs_warn(fs_info,
2568                                    "sysfs: failed to create fsid for sprout");
2569         }
2570
2571         ret = btrfs_commit_transaction(trans);
2572
2573         if (seeding_dev) {
2574                 mutex_unlock(&uuid_mutex);
2575                 up_write(&sb->s_umount);
2576                 unlocked = true;
2577
2578                 if (ret) /* transaction commit */
2579                         return ret;
2580
2581                 ret = btrfs_relocate_sys_chunks(fs_info);
2582                 if (ret < 0)
2583                         btrfs_handle_fs_error(fs_info, ret,
2584                                     "Failed to relocate sys chunks after device initialization. This can be fixed using the \"btrfs balance\" command.");
2585                 trans = btrfs_attach_transaction(root);
2586                 if (IS_ERR(trans)) {
2587                         if (PTR_ERR(trans) == -ENOENT)
2588                                 return 0;
2589                         ret = PTR_ERR(trans);
2590                         trans = NULL;
2591                         goto error_sysfs;
2592                 }
2593                 ret = btrfs_commit_transaction(trans);
2594         }
2595
2596         /* Update ctime/mtime for libblkid */
2597         update_dev_time(device_path);
2598         return ret;
2599
2600 error_sysfs:
2601         btrfs_sysfs_rm_device_link(fs_info->fs_devices, device);
2602 error_trans:
2603         if (seeding_dev)
2604                 sb->s_flags |= SB_RDONLY;
2605         if (trans)
2606                 btrfs_end_transaction(trans);
2607 error_free_device:
2608         free_device(device);
2609 error:
2610         blkdev_put(bdev, FMODE_EXCL);
2611         if (seeding_dev && !unlocked) {
2612                 mutex_unlock(&uuid_mutex);
2613                 up_write(&sb->s_umount);
2614         }
2615         return ret;
2616 }
2617
2618 int btrfs_init_dev_replace_tgtdev(struct btrfs_fs_info *fs_info,
2619                                   const char *device_path,
2620                                   struct btrfs_device *srcdev,
2621                                   struct btrfs_device **device_out)
2622 {
2623         struct btrfs_device *device;
2624         struct block_device *bdev;
2625         struct list_head *devices;
2626         struct rcu_string *name;
2627         u64 devid = BTRFS_DEV_REPLACE_DEVID;
2628         int ret = 0;
2629
2630         *device_out = NULL;
2631         if (fs_info->fs_devices->seeding) {
2632                 btrfs_err(fs_info, "the filesystem is a seed filesystem!");
2633                 return -EINVAL;
2634         }
2635
2636         bdev = blkdev_get_by_path(device_path, FMODE_WRITE | FMODE_EXCL,
2637                                   fs_info->bdev_holder);
2638         if (IS_ERR(bdev)) {
2639                 btrfs_err(fs_info, "target device %s is invalid!", device_path);
2640                 return PTR_ERR(bdev);
2641         }
2642
2643         filemap_write_and_wait(bdev->bd_inode->i_mapping);
2644
2645         devices = &fs_info->fs_devices->devices;
2646         list_for_each_entry(device, devices, dev_list) {
2647                 if (device->bdev == bdev) {
2648                         btrfs_err(fs_info,
2649                                   "target device is in the filesystem!");
2650                         ret = -EEXIST;
2651                         goto error;
2652                 }
2653         }
2654
2655
2656         if (i_size_read(bdev->bd_inode) <
2657             btrfs_device_get_total_bytes(srcdev)) {
2658                 btrfs_err(fs_info,
2659                           "target device is smaller than source device!");
2660                 ret = -EINVAL;
2661                 goto error;
2662         }
2663
2664
2665         device = btrfs_alloc_device(NULL, &devid, NULL);
2666         if (IS_ERR(device)) {
2667                 ret = PTR_ERR(device);
2668                 goto error;
2669         }
2670
2671         name = rcu_string_strdup(device_path, GFP_KERNEL);
2672         if (!name) {
2673                 free_device(device);
2674                 ret = -ENOMEM;
2675                 goto error;
2676         }
2677         rcu_assign_pointer(device->name, name);
2678
2679         mutex_lock(&fs_info->fs_devices->device_list_mutex);
2680         set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
2681         device->generation = 0;
2682         device->io_width = fs_info->sectorsize;
2683         device->io_align = fs_info->sectorsize;
2684         device->sector_size = fs_info->sectorsize;
2685         device->total_bytes = btrfs_device_get_total_bytes(srcdev);
2686         device->disk_total_bytes = btrfs_device_get_disk_total_bytes(srcdev);
2687         device->bytes_used = btrfs_device_get_bytes_used(srcdev);
2688         device->commit_total_bytes = srcdev->commit_total_bytes;
2689         device->commit_bytes_used = device->bytes_used;
2690         device->fs_info = fs_info;
2691         device->bdev = bdev;
2692         set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
2693         set_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
2694         device->mode = FMODE_EXCL;
2695         device->dev_stats_valid = 1;
2696         set_blocksize(device->bdev, BTRFS_BDEV_BLOCKSIZE);
2697         device->fs_devices = fs_info->fs_devices;
2698         list_add(&device->dev_list, &fs_info->fs_devices->devices);
2699         fs_info->fs_devices->num_devices++;
2700         fs_info->fs_devices->open_devices++;
2701         mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2702
2703         *device_out = device;
2704         return ret;
2705
2706 error:
2707         blkdev_put(bdev, FMODE_EXCL);
2708         return ret;
2709 }
2710
2711 static noinline int btrfs_update_device(struct btrfs_trans_handle *trans,
2712                                         struct btrfs_device *device)
2713 {
2714         int ret;
2715         struct btrfs_path *path;
2716         struct btrfs_root *root = device->fs_info->chunk_root;
2717         struct btrfs_dev_item *dev_item;
2718         struct extent_buffer *leaf;
2719         struct btrfs_key key;
2720
2721         path = btrfs_alloc_path();
2722         if (!path)
2723                 return -ENOMEM;
2724
2725         key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2726         key.type = BTRFS_DEV_ITEM_KEY;
2727         key.offset = device->devid;
2728
2729         ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2730         if (ret < 0)
2731                 goto out;
2732
2733         if (ret > 0) {
2734                 ret = -ENOENT;
2735                 goto out;
2736         }
2737
2738         leaf = path->nodes[0];
2739         dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
2740
2741         btrfs_set_device_id(leaf, dev_item, device->devid);
2742         btrfs_set_device_type(leaf, dev_item, device->type);
2743         btrfs_set_device_io_align(leaf, dev_item, device->io_align);
2744         btrfs_set_device_io_width(leaf, dev_item, device->io_width);
2745         btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
2746         btrfs_set_device_total_bytes(leaf, dev_item,
2747                                      btrfs_device_get_disk_total_bytes(device));
2748         btrfs_set_device_bytes_used(leaf, dev_item,
2749                                     btrfs_device_get_bytes_used(device));
2750         btrfs_mark_buffer_dirty(leaf);
2751
2752 out:
2753         btrfs_free_path(path);
2754         return ret;
2755 }
2756
2757 int btrfs_grow_device(struct btrfs_trans_handle *trans,
2758                       struct btrfs_device *device, u64 new_size)
2759 {
2760         struct btrfs_fs_info *fs_info = device->fs_info;
2761         struct btrfs_super_block *super_copy = fs_info->super_copy;
2762         struct btrfs_fs_devices *fs_devices;
2763         u64 old_total;
2764         u64 diff;
2765
2766         if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
2767                 return -EACCES;
2768
2769         new_size = round_down(new_size, fs_info->sectorsize);
2770
2771         mutex_lock(&fs_info->chunk_mutex);
2772         old_total = btrfs_super_total_bytes(super_copy);
2773         diff = round_down(new_size - device->total_bytes, fs_info->sectorsize);
2774
2775         if (new_size <= device->total_bytes ||
2776             test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
2777                 mutex_unlock(&fs_info->chunk_mutex);
2778                 return -EINVAL;
2779         }
2780
2781         fs_devices = fs_info->fs_devices;
2782
2783         btrfs_set_super_total_bytes(super_copy,
2784                         round_down(old_total + diff, fs_info->sectorsize));
2785         device->fs_devices->total_rw_bytes += diff;
2786
2787         btrfs_device_set_total_bytes(device, new_size);
2788         btrfs_device_set_disk_total_bytes(device, new_size);
2789         btrfs_clear_space_info_full(device->fs_info);
2790         if (list_empty(&device->resized_list))
2791                 list_add_tail(&device->resized_list,
2792                               &fs_devices->resized_devices);
2793         mutex_unlock(&fs_info->chunk_mutex);
2794
2795         return btrfs_update_device(trans, device);
2796 }
2797
2798 static int btrfs_free_chunk(struct btrfs_trans_handle *trans,
2799                             struct btrfs_fs_info *fs_info, u64 chunk_offset)
2800 {
2801         struct btrfs_root *root = fs_info->chunk_root;
2802         int ret;
2803         struct btrfs_path *path;
2804         struct btrfs_key key;
2805
2806         path = btrfs_alloc_path();
2807         if (!path)
2808                 return -ENOMEM;
2809
2810         key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2811         key.offset = chunk_offset;
2812         key.type = BTRFS_CHUNK_ITEM_KEY;
2813
2814         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
2815         if (ret < 0)
2816                 goto out;
2817         else if (ret > 0) { /* Logic error or corruption */
2818                 btrfs_handle_fs_error(fs_info, -ENOENT,
2819                                       "Failed lookup while freeing chunk.");
2820                 ret = -ENOENT;
2821                 goto out;
2822         }
2823
2824         ret = btrfs_del_item(trans, root, path);
2825         if (ret < 0)
2826                 btrfs_handle_fs_error(fs_info, ret,
2827                                       "Failed to delete chunk item.");
2828 out:
2829         btrfs_free_path(path);
2830         return ret;
2831 }
2832
2833 static int btrfs_del_sys_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
2834 {
2835         struct btrfs_super_block *super_copy = fs_info->super_copy;
2836         struct btrfs_disk_key *disk_key;
2837         struct btrfs_chunk *chunk;
2838         u8 *ptr;
2839         int ret = 0;
2840         u32 num_stripes;
2841         u32 array_size;
2842         u32 len = 0;
2843         u32 cur;
2844         struct btrfs_key key;
2845
2846         mutex_lock(&fs_info->chunk_mutex);
2847         array_size = btrfs_super_sys_array_size(super_copy);
2848
2849         ptr = super_copy->sys_chunk_array;
2850         cur = 0;
2851
2852         while (cur < array_size) {
2853                 disk_key = (struct btrfs_disk_key *)ptr;
2854                 btrfs_disk_key_to_cpu(&key, disk_key);
2855
2856                 len = sizeof(*disk_key);
2857
2858                 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
2859                         chunk = (struct btrfs_chunk *)(ptr + len);
2860                         num_stripes = btrfs_stack_chunk_num_stripes(chunk);
2861                         len += btrfs_chunk_item_size(num_stripes);
2862                 } else {
2863                         ret = -EIO;
2864                         break;
2865                 }
2866                 if (key.objectid == BTRFS_FIRST_CHUNK_TREE_OBJECTID &&
2867                     key.offset == chunk_offset) {
2868                         memmove(ptr, ptr + len, array_size - (cur + len));
2869                         array_size -= len;
2870                         btrfs_set_super_sys_array_size(super_copy, array_size);
2871                 } else {
2872                         ptr += len;
2873                         cur += len;
2874                 }
2875         }
2876         mutex_unlock(&fs_info->chunk_mutex);
2877         return ret;
2878 }
2879
2880 static struct extent_map *get_chunk_map(struct btrfs_fs_info *fs_info,
2881                                         u64 logical, u64 length)
2882 {
2883         struct extent_map_tree *em_tree;
2884         struct extent_map *em;
2885
2886         em_tree = &fs_info->mapping_tree.map_tree;
2887         read_lock(&em_tree->lock);
2888         em = lookup_extent_mapping(em_tree, logical, length);
2889         read_unlock(&em_tree->lock);
2890
2891         if (!em) {
2892                 btrfs_crit(fs_info, "unable to find logical %llu length %llu",
2893                            logical, length);
2894                 return ERR_PTR(-EINVAL);
2895         }
2896
2897         if (em->start > logical || em->start + em->len < logical) {
2898                 btrfs_crit(fs_info,
2899                            "found a bad mapping, wanted %llu-%llu, found %llu-%llu",
2900                            logical, length, em->start, em->start + em->len);
2901                 free_extent_map(em);
2902                 return ERR_PTR(-EINVAL);
2903         }
2904
2905         /* callers are responsible for dropping em's ref. */
2906         return em;
2907 }
2908
2909 int btrfs_remove_chunk(struct btrfs_trans_handle *trans,
2910                        struct btrfs_fs_info *fs_info, u64 chunk_offset)
2911 {
2912         struct extent_map *em;
2913         struct map_lookup *map;
2914         u64 dev_extent_len = 0;
2915         int i, ret = 0;
2916         struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2917
2918         em = get_chunk_map(fs_info, chunk_offset, 1);
2919         if (IS_ERR(em)) {
2920                 /*
2921                  * This is a logic error, but we don't want to just rely on the
2922                  * user having built with ASSERT enabled, so if ASSERT doesn't
2923                  * do anything we still error out.
2924                  */
2925                 ASSERT(0);
2926                 return PTR_ERR(em);
2927         }
2928         map = em->map_lookup;
2929         mutex_lock(&fs_info->chunk_mutex);
2930         check_system_chunk(trans, fs_info, map->type);
2931         mutex_unlock(&fs_info->chunk_mutex);
2932
2933         /*
2934          * Take the device list mutex to prevent races with the final phase of
2935          * a device replace operation that replaces the device object associated
2936          * with map stripes (dev-replace.c:btrfs_dev_replace_finishing()).
2937          */
2938         mutex_lock(&fs_devices->device_list_mutex);
2939         for (i = 0; i < map->num_stripes; i++) {
2940                 struct btrfs_device *device = map->stripes[i].dev;
2941                 ret = btrfs_free_dev_extent(trans, device,
2942                                             map->stripes[i].physical,
2943                                             &dev_extent_len);
2944                 if (ret) {
2945                         mutex_unlock(&fs_devices->device_list_mutex);
2946                         btrfs_abort_transaction(trans, ret);
2947                         goto out;
2948                 }
2949
2950                 if (device->bytes_used > 0) {
2951                         mutex_lock(&fs_info->chunk_mutex);
2952                         btrfs_device_set_bytes_used(device,
2953                                         device->bytes_used - dev_extent_len);
2954                         atomic64_add(dev_extent_len, &fs_info->free_chunk_space);
2955                         btrfs_clear_space_info_full(fs_info);
2956                         mutex_unlock(&fs_info->chunk_mutex);
2957                 }
2958
2959                 if (map->stripes[i].dev) {
2960                         ret = btrfs_update_device(trans, map->stripes[i].dev);
2961                         if (ret) {
2962                                 mutex_unlock(&fs_devices->device_list_mutex);
2963                                 btrfs_abort_transaction(trans, ret);
2964                                 goto out;
2965                         }
2966                 }
2967         }
2968         mutex_unlock(&fs_devices->device_list_mutex);
2969
2970         ret = btrfs_free_chunk(trans, fs_info, chunk_offset);
2971         if (ret) {
2972                 btrfs_abort_transaction(trans, ret);
2973                 goto out;
2974         }
2975
2976         trace_btrfs_chunk_free(fs_info, map, chunk_offset, em->len);
2977
2978         if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
2979                 ret = btrfs_del_sys_chunk(fs_info, chunk_offset);
2980                 if (ret) {
2981                         btrfs_abort_transaction(trans, ret);
2982                         goto out;
2983                 }
2984         }
2985
2986         ret = btrfs_remove_block_group(trans, fs_info, chunk_offset, em);
2987         if (ret) {
2988                 btrfs_abort_transaction(trans, ret);
2989                 goto out;
2990         }
2991
2992 out:
2993         /* once for us */
2994         free_extent_map(em);
2995         return ret;
2996 }
2997
2998 static int btrfs_relocate_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
2999 {
3000         struct btrfs_root *root = fs_info->chunk_root;
3001         struct btrfs_trans_handle *trans;
3002         int ret;
3003
3004         /*
3005          * Prevent races with automatic removal of unused block groups.
3006          * After we relocate and before we remove the chunk with offset
3007          * chunk_offset, automatic removal of the block group can kick in,
3008          * resulting in a failure when calling btrfs_remove_chunk() below.
3009          *
3010          * Make sure to acquire this mutex before doing a tree search (dev
3011          * or chunk trees) to find chunks. Otherwise the cleaner kthread might
3012          * call btrfs_remove_chunk() (through btrfs_delete_unused_bgs()) after
3013          * we release the path used to search the chunk/dev tree and before
3014          * the current task acquires this mutex and calls us.
3015          */
3016         lockdep_assert_held(&fs_info->delete_unused_bgs_mutex);
3017
3018         ret = btrfs_can_relocate(fs_info, chunk_offset);
3019         if (ret)
3020                 return -ENOSPC;
3021
3022         /* step one, relocate all the extents inside this chunk */
3023         btrfs_scrub_pause(fs_info);
3024         ret = btrfs_relocate_block_group(fs_info, chunk_offset);
3025         btrfs_scrub_continue(fs_info);
3026         if (ret)
3027                 return ret;
3028
3029         /*
3030          * We add the kobjects here (and after forcing data chunk creation)
3031          * since relocation is the only place we'll create chunks of a new
3032          * type at runtime.  The only place where we'll remove the last
3033          * chunk of a type is the call immediately below this one.  Even
3034          * so, we're protected against races with the cleaner thread since
3035          * we're covered by the delete_unused_bgs_mutex.
3036          */
3037         btrfs_add_raid_kobjects(fs_info);
3038
3039         trans = btrfs_start_trans_remove_block_group(root->fs_info,
3040                                                      chunk_offset);
3041         if (IS_ERR(trans)) {
3042                 ret = PTR_ERR(trans);
3043                 btrfs_handle_fs_error(root->fs_info, ret, NULL);
3044                 return ret;
3045         }
3046
3047         /*
3048          * step two, delete the device extents and the
3049          * chunk tree entries
3050          */
3051         ret = btrfs_remove_chunk(trans, fs_info, chunk_offset);
3052         btrfs_end_transaction(trans);
3053         return ret;
3054 }
3055
3056 static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info)
3057 {
3058         struct btrfs_root *chunk_root = fs_info->chunk_root;
3059         struct btrfs_path *path;
3060         struct extent_buffer *leaf;
3061         struct btrfs_chunk *chunk;
3062         struct btrfs_key key;
3063         struct btrfs_key found_key;
3064         u64 chunk_type;
3065         bool retried = false;
3066         int failed = 0;
3067         int ret;
3068
3069         path = btrfs_alloc_path();
3070         if (!path)
3071                 return -ENOMEM;
3072
3073 again:
3074         key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
3075         key.offset = (u64)-1;
3076         key.type = BTRFS_CHUNK_ITEM_KEY;
3077
3078         while (1) {
3079                 mutex_lock(&fs_info->delete_unused_bgs_mutex);
3080                 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
3081                 if (ret < 0) {
3082                         mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3083                         goto error;
3084                 }
3085                 BUG_ON(ret == 0); /* Corruption */
3086
3087                 ret = btrfs_previous_item(chunk_root, path, key.objectid,
3088                                           key.type);
3089                 if (ret)
3090                         mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3091                 if (ret < 0)
3092                         goto error;
3093                 if (ret > 0)
3094                         break;
3095
3096                 leaf = path->nodes[0];
3097                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3098
3099                 chunk = btrfs_item_ptr(leaf, path->slots[0],
3100                                        struct btrfs_chunk);
3101                 chunk_type = btrfs_chunk_type(leaf, chunk);
3102                 btrfs_release_path(path);
3103
3104                 if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) {
3105                         ret = btrfs_relocate_chunk(fs_info, found_key.offset);
3106                         if (ret == -ENOSPC)
3107                                 failed++;
3108                         else
3109                                 BUG_ON(ret);
3110                 }
3111                 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3112
3113                 if (found_key.offset == 0)
3114                         break;
3115                 key.offset = found_key.offset - 1;
3116         }
3117         ret = 0;
3118         if (failed && !retried) {
3119                 failed = 0;
3120                 retried = true;
3121                 goto again;
3122         } else if (WARN_ON(failed && retried)) {
3123                 ret = -ENOSPC;
3124         }
3125 error:
3126         btrfs_free_path(path);
3127         return ret;
3128 }
3129
3130 /*
3131  * return 1 : allocate a data chunk successfully,
3132  * return <0: errors during allocating a data chunk,
3133  * return 0 : no need to allocate a data chunk.
3134  */
3135 static int btrfs_may_alloc_data_chunk(struct btrfs_fs_info *fs_info,
3136                                       u64 chunk_offset)
3137 {
3138         struct btrfs_block_group_cache *cache;
3139         u64 bytes_used;
3140         u64 chunk_type;
3141
3142         cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3143         ASSERT(cache);
3144         chunk_type = cache->flags;
3145         btrfs_put_block_group(cache);
3146
3147         if (chunk_type & BTRFS_BLOCK_GROUP_DATA) {
3148                 spin_lock(&fs_info->data_sinfo->lock);
3149                 bytes_used = fs_info->data_sinfo->bytes_used;
3150                 spin_unlock(&fs_info->data_sinfo->lock);
3151
3152                 if (!bytes_used) {
3153                         struct btrfs_trans_handle *trans;
3154                         int ret;
3155
3156                         trans = btrfs_join_transaction(fs_info->tree_root);
3157                         if (IS_ERR(trans))
3158                                 return PTR_ERR(trans);
3159
3160                         ret = btrfs_force_chunk_alloc(trans, fs_info,
3161                                                       BTRFS_BLOCK_GROUP_DATA);
3162                         btrfs_end_transaction(trans);
3163                         if (ret < 0)
3164                                 return ret;
3165
3166                         btrfs_add_raid_kobjects(fs_info);
3167
3168                         return 1;
3169                 }
3170         }
3171         return 0;
3172 }
3173
3174 static int insert_balance_item(struct btrfs_fs_info *fs_info,
3175                                struct btrfs_balance_control *bctl)
3176 {
3177         struct btrfs_root *root = fs_info->tree_root;
3178         struct btrfs_trans_handle *trans;
3179         struct btrfs_balance_item *item;
3180         struct btrfs_disk_balance_args disk_bargs;
3181         struct btrfs_path *path;
3182         struct extent_buffer *leaf;
3183         struct btrfs_key key;
3184         int ret, err;
3185
3186         path = btrfs_alloc_path();
3187         if (!path)
3188                 return -ENOMEM;
3189
3190         trans = btrfs_start_transaction(root, 0);
3191         if (IS_ERR(trans)) {
3192                 btrfs_free_path(path);
3193                 return PTR_ERR(trans);
3194         }
3195
3196         key.objectid = BTRFS_BALANCE_OBJECTID;
3197         key.type = BTRFS_TEMPORARY_ITEM_KEY;
3198         key.offset = 0;
3199
3200         ret = btrfs_insert_empty_item(trans, root, path, &key,
3201                                       sizeof(*item));
3202         if (ret)
3203                 goto out;
3204
3205         leaf = path->nodes[0];
3206         item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
3207
3208         memzero_extent_buffer(leaf, (unsigned long)item, sizeof(*item));
3209
3210         btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->data);
3211         btrfs_set_balance_data(leaf, item, &disk_bargs);
3212         btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->meta);
3213         btrfs_set_balance_meta(leaf, item, &disk_bargs);
3214         btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->sys);
3215         btrfs_set_balance_sys(leaf, item, &disk_bargs);
3216
3217         btrfs_set_balance_flags(leaf, item, bctl->flags);
3218
3219         btrfs_mark_buffer_dirty(leaf);
3220 out:
3221         btrfs_free_path(path);
3222         err = btrfs_commit_transaction(trans);
3223         if (err && !ret)
3224                 ret = err;
3225         return ret;
3226 }
3227
3228 static int del_balance_item(struct btrfs_fs_info *fs_info)
3229 {
3230         struct btrfs_root *root = fs_info->tree_root;
3231         struct btrfs_trans_handle *trans;
3232         struct btrfs_path *path;
3233         struct btrfs_key key;
3234         int ret, err;
3235
3236         path = btrfs_alloc_path();
3237         if (!path)
3238                 return -ENOMEM;
3239
3240         trans = btrfs_start_transaction(root, 0);
3241         if (IS_ERR(trans)) {
3242                 btrfs_free_path(path);
3243                 return PTR_ERR(trans);
3244         }
3245
3246         key.objectid = BTRFS_BALANCE_OBJECTID;
3247         key.type = BTRFS_TEMPORARY_ITEM_KEY;
3248         key.offset = 0;
3249
3250         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3251         if (ret < 0)
3252                 goto out;
3253         if (ret > 0) {
3254                 ret = -ENOENT;
3255                 goto out;
3256         }
3257
3258         ret = btrfs_del_item(trans, root, path);
3259 out:
3260         btrfs_free_path(path);
3261         err = btrfs_commit_transaction(trans);
3262         if (err && !ret)
3263                 ret = err;
3264         return ret;
3265 }
3266
3267 /*
3268  * This is a heuristic used to reduce the number of chunks balanced on
3269  * resume after balance was interrupted.
3270  */
3271 static void update_balance_args(struct btrfs_balance_control *bctl)
3272 {
3273         /*
3274          * Turn on soft mode for chunk types that were being converted.
3275          */
3276         if (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)
3277                 bctl->data.flags |= BTRFS_BALANCE_ARGS_SOFT;
3278         if (bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)
3279                 bctl->sys.flags |= BTRFS_BALANCE_ARGS_SOFT;
3280         if (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)
3281                 bctl->meta.flags |= BTRFS_BALANCE_ARGS_SOFT;
3282
3283         /*
3284          * Turn on usage filter if is not already used.  The idea is
3285          * that chunks that we have already balanced should be
3286          * reasonably full.  Don't do it for chunks that are being
3287          * converted - that will keep us from relocating unconverted
3288          * (albeit full) chunks.
3289          */
3290         if (!(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3291             !(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3292             !(bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3293                 bctl->data.flags |= BTRFS_BALANCE_ARGS_USAGE;
3294                 bctl->data.usage = 90;
3295         }
3296         if (!(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3297             !(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3298             !(bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3299                 bctl->sys.flags |= BTRFS_BALANCE_ARGS_USAGE;
3300                 bctl->sys.usage = 90;
3301         }
3302         if (!(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3303             !(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3304             !(bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3305                 bctl->meta.flags |= BTRFS_BALANCE_ARGS_USAGE;
3306                 bctl->meta.usage = 90;
3307         }
3308 }
3309
3310 /*
3311  * Should be called with both balance and volume mutexes held to
3312  * serialize other volume operations (add_dev/rm_dev/resize) with
3313  * restriper.  Same goes for unset_balance_control.
3314  */
3315 static void set_balance_control(struct btrfs_balance_control *bctl)
3316 {
3317         struct btrfs_fs_info *fs_info = bctl->fs_info;
3318
3319         BUG_ON(fs_info->balance_ctl);
3320
3321         spin_lock(&fs_info->balance_lock);
3322         fs_info->balance_ctl = bctl;
3323         spin_unlock(&fs_info->balance_lock);
3324 }
3325
3326 static void unset_balance_control(struct btrfs_fs_info *fs_info)
3327 {
3328         struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3329
3330         BUG_ON(!fs_info->balance_ctl);
3331
3332         spin_lock(&fs_info->balance_lock);
3333         fs_info->balance_ctl = NULL;
3334         spin_unlock(&fs_info->balance_lock);
3335
3336         kfree(bctl);
3337 }
3338
3339 /*
3340  * Balance filters.  Return 1 if chunk should be filtered out
3341  * (should not be balanced).
3342  */
3343 static int chunk_profiles_filter(u64 chunk_type,
3344                                  struct btrfs_balance_args *bargs)
3345 {
3346         chunk_type = chunk_to_extended(chunk_type) &
3347                                 BTRFS_EXTENDED_PROFILE_MASK;
3348
3349         if (bargs->profiles & chunk_type)
3350                 return 0;
3351
3352         return 1;
3353 }
3354
3355 static int chunk_usage_range_filter(struct btrfs_fs_info *fs_info, u64 chunk_offset,
3356                               struct btrfs_balance_args *bargs)
3357 {
3358         struct btrfs_block_group_cache *cache;
3359         u64 chunk_used;
3360         u64 user_thresh_min;
3361         u64 user_thresh_max;
3362         int ret = 1;
3363
3364         cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3365         chunk_used = btrfs_block_group_used(&cache->item);
3366
3367         if (bargs->usage_min == 0)
3368                 user_thresh_min = 0;
3369         else
3370                 user_thresh_min = div_factor_fine(cache->key.offset,
3371                                         bargs->usage_min);
3372
3373         if (bargs->usage_max == 0)
3374                 user_thresh_max = 1;
3375         else if (bargs->usage_max > 100)
3376                 user_thresh_max = cache->key.offset;
3377         else
3378                 user_thresh_max = div_factor_fine(cache->key.offset,
3379                                         bargs->usage_max);
3380
3381         if (user_thresh_min <= chunk_used && chunk_used < user_thresh_max)
3382                 ret = 0;
3383
3384         btrfs_put_block_group(cache);
3385         return ret;
3386 }
3387
3388 static int chunk_usage_filter(struct btrfs_fs_info *fs_info,
3389                 u64 chunk_offset, struct btrfs_balance_args *bargs)
3390 {
3391         struct btrfs_block_group_cache *cache;
3392         u64 chunk_used, user_thresh;
3393         int ret = 1;
3394
3395         cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3396         chunk_used = btrfs_block_group_used(&cache->item);
3397
3398         if (bargs->usage_min == 0)
3399                 user_thresh = 1;
3400         else if (bargs->usage > 100)
3401                 user_thresh = cache->key.offset;
3402         else
3403                 user_thresh = div_factor_fine(cache->key.offset,
3404                                               bargs->usage);
3405
3406         if (chunk_used < user_thresh)
3407                 ret = 0;
3408
3409         btrfs_put_block_group(cache);
3410         return ret;
3411 }
3412
3413 static int chunk_devid_filter(struct extent_buffer *leaf,
3414                               struct btrfs_chunk *chunk,
3415                               struct btrfs_balance_args *bargs)
3416 {
3417         struct btrfs_stripe *stripe;
3418         int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3419         int i;
3420
3421         for (i = 0; i < num_stripes; i++) {
3422                 stripe = btrfs_stripe_nr(chunk, i);
3423                 if (btrfs_stripe_devid(leaf, stripe) == bargs->devid)
3424                         return 0;
3425         }
3426
3427         return 1;
3428 }
3429
3430 /* [pstart, pend) */
3431 static int chunk_drange_filter(struct extent_buffer *leaf,
3432                                struct btrfs_chunk *chunk,
3433                                struct btrfs_balance_args *bargs)
3434 {
3435         struct btrfs_stripe *stripe;
3436         int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3437         u64 stripe_offset;
3438         u64 stripe_length;
3439         int factor;
3440         int i;
3441
3442         if (!(bargs->flags & BTRFS_BALANCE_ARGS_DEVID))
3443                 return 0;
3444
3445         if (btrfs_chunk_type(leaf, chunk) & (BTRFS_BLOCK_GROUP_DUP |
3446              BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10)) {
3447                 factor = num_stripes / 2;
3448         } else if (btrfs_chunk_type(leaf, chunk) & BTRFS_BLOCK_GROUP_RAID5) {
3449                 factor = num_stripes - 1;
3450         } else if (btrfs_chunk_type(leaf, chunk) & BTRFS_BLOCK_GROUP_RAID6) {
3451                 factor = num_stripes - 2;
3452         } else {
3453                 factor = num_stripes;
3454         }
3455
3456         for (i = 0; i < num_stripes; i++) {
3457                 stripe = btrfs_stripe_nr(chunk, i);
3458                 if (btrfs_stripe_devid(leaf, stripe) != bargs->devid)
3459                         continue;
3460
3461                 stripe_offset = btrfs_stripe_offset(leaf, stripe);
3462                 stripe_length = btrfs_chunk_length(leaf, chunk);
3463                 stripe_length = div_u64(stripe_length, factor);
3464
3465                 if (stripe_offset < bargs->pend &&
3466                     stripe_offset + stripe_length > bargs->pstart)
3467                         return 0;
3468         }
3469
3470         return 1;
3471 }
3472
3473 /* [vstart, vend) */
3474 static int chunk_vrange_filter(struct extent_buffer *leaf,
3475                                struct btrfs_chunk *chunk,
3476                                u64 chunk_offset,
3477                                struct btrfs_balance_args *bargs)
3478 {
3479         if (chunk_offset < bargs->vend &&
3480             chunk_offset + btrfs_chunk_length(leaf, chunk) > bargs->vstart)
3481                 /* at least part of the chunk is inside this vrange */
3482                 return 0;
3483
3484         return 1;
3485 }
3486
3487 static int chunk_stripes_range_filter(struct extent_buffer *leaf,
3488                                struct btrfs_chunk *chunk,
3489                                struct btrfs_balance_args *bargs)
3490 {
3491         int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3492
3493         if (bargs->stripes_min <= num_stripes
3494                         && num_stripes <= bargs->stripes_max)
3495                 return 0;
3496
3497         return 1;
3498 }
3499
3500 static int chunk_soft_convert_filter(u64 chunk_type,
3501                                      struct btrfs_balance_args *bargs)
3502 {
3503         if (!(bargs->flags & BTRFS_BALANCE_ARGS_CONVERT))
3504                 return 0;
3505
3506         chunk_type = chunk_to_extended(chunk_type) &
3507                                 BTRFS_EXTENDED_PROFILE_MASK;
3508
3509         if (bargs->target == chunk_type)
3510                 return 1;
3511
3512         return 0;
3513 }
3514
3515 static int should_balance_chunk(struct btrfs_fs_info *fs_info,
3516                                 struct extent_buffer *leaf,
3517                                 struct btrfs_chunk *chunk, u64 chunk_offset)
3518 {
3519         struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3520         struct btrfs_balance_args *bargs = NULL;
3521         u64 chunk_type = btrfs_chunk_type(leaf, chunk);
3522
3523         /* type filter */
3524         if (!((chunk_type & BTRFS_BLOCK_GROUP_TYPE_MASK) &
3525               (bctl->flags & BTRFS_BALANCE_TYPE_MASK))) {
3526                 return 0;
3527         }
3528
3529         if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
3530                 bargs = &bctl->data;
3531         else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
3532                 bargs = &bctl->sys;
3533         else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
3534                 bargs = &bctl->meta;
3535
3536         /* profiles filter */
3537         if ((bargs->flags & BTRFS_BALANCE_ARGS_PROFILES) &&
3538             chunk_profiles_filter(chunk_type, bargs)) {
3539                 return 0;
3540         }
3541
3542         /* usage filter */
3543         if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE) &&
3544             chunk_usage_filter(fs_info, chunk_offset, bargs)) {
3545                 return 0;
3546         } else if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3547             chunk_usage_range_filter(fs_info, chunk_offset, bargs)) {
3548                 return 0;
3549         }
3550
3551         /* devid filter */
3552         if ((bargs->flags & BTRFS_BALANCE_ARGS_DEVID) &&
3553             chunk_devid_filter(leaf, chunk, bargs)) {
3554                 return 0;
3555         }
3556
3557         /* drange filter, makes sense only with devid filter */
3558         if ((bargs->flags & BTRFS_BALANCE_ARGS_DRANGE) &&
3559             chunk_drange_filter(leaf, chunk, bargs)) {
3560                 return 0;
3561         }
3562
3563         /* vrange filter */
3564         if ((bargs->flags & BTRFS_BALANCE_ARGS_VRANGE) &&
3565             chunk_vrange_filter(leaf, chunk, chunk_offset, bargs)) {
3566                 return 0;
3567         }
3568
3569         /* stripes filter */
3570         if ((bargs->flags & BTRFS_BALANCE_ARGS_STRIPES_RANGE) &&
3571             chunk_stripes_range_filter(leaf, chunk, bargs)) {
3572                 return 0;
3573         }
3574
3575         /* soft profile changing mode */
3576         if ((bargs->flags & BTRFS_BALANCE_ARGS_SOFT) &&
3577             chunk_soft_convert_filter(chunk_type, bargs)) {
3578                 return 0;
3579         }
3580
3581         /*
3582          * limited by count, must be the last filter
3583          */
3584         if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT)) {
3585                 if (bargs->limit == 0)
3586                         return 0;
3587                 else
3588                         bargs->limit--;
3589         } else if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT_RANGE)) {
3590                 /*
3591                  * Same logic as the 'limit' filter; the minimum cannot be
3592                  * determined here because we do not have the global information
3593                  * about the count of all chunks that satisfy the filters.
3594                  */
3595                 if (bargs->limit_max == 0)
3596                         return 0;
3597                 else
3598                         bargs->limit_max--;
3599         }
3600
3601         return 1;
3602 }
3603
3604 static int __btrfs_balance(struct btrfs_fs_info *fs_info)
3605 {
3606         struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3607         struct btrfs_root *chunk_root = fs_info->chunk_root;
3608         struct btrfs_root *dev_root = fs_info->dev_root;
3609         struct list_head *devices;
3610         struct btrfs_device *device;
3611         u64 old_size;
3612         u64 size_to_free;
3613         u64 chunk_type;
3614         struct btrfs_chunk *chunk;
3615         struct btrfs_path *path = NULL;
3616         struct btrfs_key key;
3617         struct btrfs_key found_key;
3618         struct btrfs_trans_handle *trans;
3619         struct extent_buffer *leaf;
3620         int slot;
3621         int ret;
3622         int enospc_errors = 0;
3623         bool counting = true;
3624         /* The single value limit and min/max limits use the same bytes in the */
3625         u64 limit_data = bctl->data.limit;
3626         u64 limit_meta = bctl->meta.limit;
3627         u64 limit_sys = bctl->sys.limit;
3628         u32 count_data = 0;
3629         u32 count_meta = 0;
3630         u32 count_sys = 0;
3631         int chunk_reserved = 0;
3632
3633         /* step one make some room on all the devices */
3634         devices = &fs_info->fs_devices->devices;
3635         list_for_each_entry(device, devices, dev_list) {
3636                 old_size = btrfs_device_get_total_bytes(device);
3637                 size_to_free = div_factor(old_size, 1);
3638                 size_to_free = min_t(u64, size_to_free, SZ_1M);
3639                 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) ||
3640                     btrfs_device_get_total_bytes(device) -
3641                     btrfs_device_get_bytes_used(device) > size_to_free ||
3642                     test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
3643                         continue;
3644
3645                 ret = btrfs_shrink_device(device, old_size - size_to_free);
3646                 if (ret == -ENOSPC)
3647                         break;
3648                 if (ret) {
3649                         /* btrfs_shrink_device never returns ret > 0 */
3650                         WARN_ON(ret > 0);
3651                         goto error;
3652                 }
3653
3654                 trans = btrfs_start_transaction(dev_root, 0);
3655                 if (IS_ERR(trans)) {
3656                         ret = PTR_ERR(trans);
3657                         btrfs_info_in_rcu(fs_info,
3658                  "resize: unable to start transaction after shrinking device %s (error %d), old size %llu, new size %llu",
3659                                           rcu_str_deref(device->name), ret,
3660                                           old_size, old_size - size_to_free);
3661                         goto error;
3662                 }
3663
3664                 ret = btrfs_grow_device(trans, device, old_size);
3665                 if (ret) {
3666                         btrfs_end_transaction(trans);
3667                         /* btrfs_grow_device never returns ret > 0 */
3668                         WARN_ON(ret > 0);
3669                         btrfs_info_in_rcu(fs_info,
3670                  "resize: unable to grow device after shrinking device %s (error %d), old size %llu, new size %llu",
3671                                           rcu_str_deref(device->name), ret,
3672                                           old_size, old_size - size_to_free);
3673                         goto error;
3674                 }
3675
3676                 btrfs_end_transaction(trans);
3677         }
3678
3679         /* step two, relocate all the chunks */
3680         path = btrfs_alloc_path();
3681         if (!path) {
3682                 ret = -ENOMEM;
3683                 goto error;
3684         }
3685
3686         /* zero out stat counters */
3687         spin_lock(&fs_info->balance_lock);
3688         memset(&bctl->stat, 0, sizeof(bctl->stat));
3689         spin_unlock(&fs_info->balance_lock);
3690 again:
3691         if (!counting) {
3692                 /*
3693                  * The single value limit and min/max limits use the same bytes
3694                  * in the
3695                  */
3696                 bctl->data.limit = limit_data;
3697                 bctl->meta.limit = limit_meta;
3698                 bctl->sys.limit = limit_sys;
3699         }
3700         key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
3701         key.offset = (u64)-1;
3702         key.type = BTRFS_CHUNK_ITEM_KEY;
3703
3704         while (1) {
3705                 if ((!counting && atomic_read(&fs_info->balance_pause_req)) ||
3706                     atomic_read(&fs_info->balance_cancel_req)) {
3707                         ret = -ECANCELED;
3708                         goto error;
3709                 }
3710
3711                 mutex_lock(&fs_info->delete_unused_bgs_mutex);
3712                 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
3713                 if (ret < 0) {
3714                         mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3715                         goto error;
3716                 }
3717
3718                 /*
3719                  * this shouldn't happen, it means the last relocate
3720                  * failed
3721                  */
3722                 if (ret == 0)
3723                         BUG(); /* FIXME break ? */
3724
3725                 ret = btrfs_previous_item(chunk_root, path, 0,
3726                                           BTRFS_CHUNK_ITEM_KEY);
3727                 if (ret) {
3728                         mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3729                         ret = 0;
3730                         break;
3731                 }
3732
3733                 leaf = path->nodes[0];
3734                 slot = path->slots[0];
3735                 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3736
3737                 if (found_key.objectid != key.objectid) {
3738                         mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3739                         break;
3740                 }
3741
3742                 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
3743                 chunk_type = btrfs_chunk_type(leaf, chunk);
3744
3745                 if (!counting) {
3746                         spin_lock(&fs_info->balance_lock);
3747                         bctl->stat.considered++;
3748                         spin_unlock(&fs_info->balance_lock);
3749                 }
3750
3751                 ret = should_balance_chunk(fs_info, leaf, chunk,
3752                                            found_key.offset);
3753
3754                 btrfs_release_path(path);
3755                 if (!ret) {
3756                         mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3757                         goto loop;
3758                 }
3759