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