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