bb76263c3ad4a7bdfa29e4e948e49279329ad598
[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_device)
635 {
636         struct btrfs_fs_devices *fs_devices, *tmp_fs_devices;
637         struct btrfs_device *device, *tmp_device;
638
639         list_for_each_entry_safe(fs_devices, tmp_fs_devices, &fs_uuids, fs_list) {
640                 mutex_lock(&fs_devices->device_list_mutex);
641                 if (fs_devices->opened) {
642                         mutex_unlock(&fs_devices->device_list_mutex);
643                         continue;
644                 }
645
646                 list_for_each_entry_safe(device, tmp_device,
647                                          &fs_devices->devices, dev_list) {
648                         int not_found = 0;
649
650                         if (skip_device && skip_device == device)
651                                 continue;
652                         if (path && !device->name)
653                                 continue;
654
655                         rcu_read_lock();
656                         if (path)
657                                 not_found = strcmp(rcu_str_deref(device->name),
658                                                    path);
659                         rcu_read_unlock();
660                         if (not_found)
661                                 continue;
662
663                         /* delete the stale device */
664                         fs_devices->num_devices--;
665                         list_del(&device->dev_list);
666                         btrfs_free_device(device);
667
668                         if (fs_devices->num_devices == 0)
669                                 break;
670                 }
671                 mutex_unlock(&fs_devices->device_list_mutex);
672                 if (fs_devices->num_devices == 0) {
673                         btrfs_sysfs_remove_fsid(fs_devices);
674                         list_del(&fs_devices->fs_list);
675                         free_fs_devices(fs_devices);
676                 }
677         }
678 }
679
680 static int btrfs_open_one_device(struct btrfs_fs_devices *fs_devices,
681                         struct btrfs_device *device, fmode_t flags,
682                         void *holder)
683 {
684         struct request_queue *q;
685         struct block_device *bdev;
686         struct buffer_head *bh;
687         struct btrfs_super_block *disk_super;
688         u64 devid;
689         int ret;
690
691         if (device->bdev)
692                 return -EINVAL;
693         if (!device->name)
694                 return -EINVAL;
695
696         ret = btrfs_get_bdev_and_sb(device->name->str, flags, holder, 1,
697                                     &bdev, &bh);
698         if (ret)
699                 return ret;
700
701         disk_super = (struct btrfs_super_block *)bh->b_data;
702         devid = btrfs_stack_device_id(&disk_super->dev_item);
703         if (devid != device->devid)
704                 goto error_brelse;
705
706         if (memcmp(device->uuid, disk_super->dev_item.uuid, BTRFS_UUID_SIZE))
707                 goto error_brelse;
708
709         device->generation = btrfs_super_generation(disk_super);
710
711         if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_SEEDING) {
712                 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
713                 fs_devices->seeding = 1;
714         } else {
715                 if (bdev_read_only(bdev))
716                         clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
717                 else
718                         set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
719         }
720
721         q = bdev_get_queue(bdev);
722         if (!blk_queue_nonrot(q))
723                 fs_devices->rotating = 1;
724
725         device->bdev = bdev;
726         clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
727         device->mode = flags;
728
729         fs_devices->open_devices++;
730         if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
731             device->devid != BTRFS_DEV_REPLACE_DEVID) {
732                 fs_devices->rw_devices++;
733                 list_add_tail(&device->dev_alloc_list, &fs_devices->alloc_list);
734         }
735         brelse(bh);
736
737         return 0;
738
739 error_brelse:
740         brelse(bh);
741         blkdev_put(bdev, flags);
742
743         return -EINVAL;
744 }
745
746 /*
747  * Add new device to list of registered devices
748  *
749  * Returns:
750  * device pointer which was just added or updated when successful
751  * error pointer when failed
752  */
753 static noinline struct btrfs_device *device_list_add(const char *path,
754                            struct btrfs_super_block *disk_super,
755                            bool *new_device_added)
756 {
757         struct btrfs_device *device;
758         struct btrfs_fs_devices *fs_devices;
759         struct rcu_string *name;
760         u64 found_transid = btrfs_super_generation(disk_super);
761         u64 devid = btrfs_stack_device_id(&disk_super->dev_item);
762
763         fs_devices = find_fsid(disk_super->fsid);
764         if (!fs_devices) {
765                 fs_devices = alloc_fs_devices(disk_super->fsid);
766                 if (IS_ERR(fs_devices))
767                         return ERR_CAST(fs_devices);
768
769                 mutex_lock(&fs_devices->device_list_mutex);
770                 list_add(&fs_devices->fs_list, &fs_uuids);
771
772                 device = NULL;
773         } else {
774                 mutex_lock(&fs_devices->device_list_mutex);
775                 device = find_device(fs_devices, devid,
776                                 disk_super->dev_item.uuid);
777         }
778
779         if (!device) {
780                 if (fs_devices->opened) {
781                         mutex_unlock(&fs_devices->device_list_mutex);
782                         return ERR_PTR(-EBUSY);
783                 }
784
785                 device = btrfs_alloc_device(NULL, &devid,
786                                             disk_super->dev_item.uuid);
787                 if (IS_ERR(device)) {
788                         mutex_unlock(&fs_devices->device_list_mutex);
789                         /* we can safely leave the fs_devices entry around */
790                         return device;
791                 }
792
793                 name = rcu_string_strdup(path, GFP_NOFS);
794                 if (!name) {
795                         btrfs_free_device(device);
796                         mutex_unlock(&fs_devices->device_list_mutex);
797                         return ERR_PTR(-ENOMEM);
798                 }
799                 rcu_assign_pointer(device->name, name);
800
801                 list_add_rcu(&device->dev_list, &fs_devices->devices);
802                 fs_devices->num_devices++;
803
804                 device->fs_devices = fs_devices;
805                 *new_device_added = true;
806
807                 if (disk_super->label[0])
808                         pr_info("BTRFS: device label %s devid %llu transid %llu %s\n",
809                                 disk_super->label, devid, found_transid, path);
810                 else
811                         pr_info("BTRFS: device fsid %pU devid %llu transid %llu %s\n",
812                                 disk_super->fsid, devid, found_transid, path);
813
814         } else if (!device->name || strcmp(device->name->str, path)) {
815                 /*
816                  * When FS is already mounted.
817                  * 1. If you are here and if the device->name is NULL that
818                  *    means this device was missing at time of FS mount.
819                  * 2. If you are here and if the device->name is different
820                  *    from 'path' that means either
821                  *      a. The same device disappeared and reappeared with
822                  *         different name. or
823                  *      b. The missing-disk-which-was-replaced, has
824                  *         reappeared now.
825                  *
826                  * We must allow 1 and 2a above. But 2b would be a spurious
827                  * and unintentional.
828                  *
829                  * Further in case of 1 and 2a above, the disk at 'path'
830                  * would have missed some transaction when it was away and
831                  * in case of 2a the stale bdev has to be updated as well.
832                  * 2b must not be allowed at all time.
833                  */
834
835                 /*
836                  * For now, we do allow update to btrfs_fs_device through the
837                  * btrfs dev scan cli after FS has been mounted.  We're still
838                  * tracking a problem where systems fail mount by subvolume id
839                  * when we reject replacement on a mounted FS.
840                  */
841                 if (!fs_devices->opened && found_transid < device->generation) {
842                         /*
843                          * That is if the FS is _not_ mounted and if you
844                          * are here, that means there is more than one
845                          * disk with same uuid and devid.We keep the one
846                          * with larger generation number or the last-in if
847                          * generation are equal.
848                          */
849                         mutex_unlock(&fs_devices->device_list_mutex);
850                         return ERR_PTR(-EEXIST);
851                 }
852
853                 name = rcu_string_strdup(path, GFP_NOFS);
854                 if (!name) {
855                         mutex_unlock(&fs_devices->device_list_mutex);
856                         return ERR_PTR(-ENOMEM);
857                 }
858                 rcu_string_free(device->name);
859                 rcu_assign_pointer(device->name, name);
860                 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
861                         fs_devices->missing_devices--;
862                         clear_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
863                 }
864         }
865
866         /*
867          * Unmount does not free the btrfs_device struct but would zero
868          * generation along with most of the other members. So just update
869          * it back. We need it to pick the disk with largest generation
870          * (as above).
871          */
872         if (!fs_devices->opened)
873                 device->generation = found_transid;
874
875         fs_devices->total_devices = btrfs_super_num_devices(disk_super);
876
877         mutex_unlock(&fs_devices->device_list_mutex);
878         return device;
879 }
880
881 static struct btrfs_fs_devices *clone_fs_devices(struct btrfs_fs_devices *orig)
882 {
883         struct btrfs_fs_devices *fs_devices;
884         struct btrfs_device *device;
885         struct btrfs_device *orig_dev;
886
887         fs_devices = alloc_fs_devices(orig->fsid);
888         if (IS_ERR(fs_devices))
889                 return fs_devices;
890
891         mutex_lock(&orig->device_list_mutex);
892         fs_devices->total_devices = orig->total_devices;
893
894         /* We have held the volume lock, it is safe to get the devices. */
895         list_for_each_entry(orig_dev, &orig->devices, dev_list) {
896                 struct rcu_string *name;
897
898                 device = btrfs_alloc_device(NULL, &orig_dev->devid,
899                                             orig_dev->uuid);
900                 if (IS_ERR(device))
901                         goto error;
902
903                 /*
904                  * This is ok to do without rcu read locked because we hold the
905                  * uuid mutex so nothing we touch in here is going to disappear.
906                  */
907                 if (orig_dev->name) {
908                         name = rcu_string_strdup(orig_dev->name->str,
909                                         GFP_KERNEL);
910                         if (!name) {
911                                 btrfs_free_device(device);
912                                 goto error;
913                         }
914                         rcu_assign_pointer(device->name, name);
915                 }
916
917                 list_add(&device->dev_list, &fs_devices->devices);
918                 device->fs_devices = fs_devices;
919                 fs_devices->num_devices++;
920         }
921         mutex_unlock(&orig->device_list_mutex);
922         return fs_devices;
923 error:
924         mutex_unlock(&orig->device_list_mutex);
925         free_fs_devices(fs_devices);
926         return ERR_PTR(-ENOMEM);
927 }
928
929 /*
930  * After we have read the system tree and know devids belonging to
931  * this filesystem, remove the device which does not belong there.
932  */
933 void btrfs_free_extra_devids(struct btrfs_fs_devices *fs_devices, int step)
934 {
935         struct btrfs_device *device, *next;
936         struct btrfs_device *latest_dev = NULL;
937
938         mutex_lock(&uuid_mutex);
939 again:
940         /* This is the initialized path, it is safe to release the devices. */
941         list_for_each_entry_safe(device, next, &fs_devices->devices, dev_list) {
942                 if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
943                                                         &device->dev_state)) {
944                         if (!test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
945                              &device->dev_state) &&
946                              (!latest_dev ||
947                               device->generation > latest_dev->generation)) {
948                                 latest_dev = device;
949                         }
950                         continue;
951                 }
952
953                 if (device->devid == BTRFS_DEV_REPLACE_DEVID) {
954                         /*
955                          * In the first step, keep the device which has
956                          * the correct fsid and the devid that is used
957                          * for the dev_replace procedure.
958                          * In the second step, the dev_replace state is
959                          * read from the device tree and it is known
960                          * whether the procedure is really active or
961                          * not, which means whether this device is
962                          * used or whether it should be removed.
963                          */
964                         if (step == 0 || test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
965                                                   &device->dev_state)) {
966                                 continue;
967                         }
968                 }
969                 if (device->bdev) {
970                         blkdev_put(device->bdev, device->mode);
971                         device->bdev = NULL;
972                         fs_devices->open_devices--;
973                 }
974                 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
975                         list_del_init(&device->dev_alloc_list);
976                         clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
977                         if (!test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
978                                       &device->dev_state))
979                                 fs_devices->rw_devices--;
980                 }
981                 list_del_init(&device->dev_list);
982                 fs_devices->num_devices--;
983                 btrfs_free_device(device);
984         }
985
986         if (fs_devices->seed) {
987                 fs_devices = fs_devices->seed;
988                 goto again;
989         }
990
991         fs_devices->latest_bdev = latest_dev->bdev;
992
993         mutex_unlock(&uuid_mutex);
994 }
995
996 static void free_device_rcu(struct rcu_head *head)
997 {
998         struct btrfs_device *device;
999
1000         device = container_of(head, struct btrfs_device, rcu);
1001         btrfs_free_device(device);
1002 }
1003
1004 static void btrfs_close_bdev(struct btrfs_device *device)
1005 {
1006         if (!device->bdev)
1007                 return;
1008
1009         if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
1010                 sync_blockdev(device->bdev);
1011                 invalidate_bdev(device->bdev);
1012         }
1013
1014         blkdev_put(device->bdev, device->mode);
1015 }
1016
1017 static void btrfs_close_one_device(struct btrfs_device *device)
1018 {
1019         struct btrfs_fs_devices *fs_devices = device->fs_devices;
1020         struct btrfs_device *new_device;
1021         struct rcu_string *name;
1022
1023         if (device->bdev)
1024                 fs_devices->open_devices--;
1025
1026         if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
1027             device->devid != BTRFS_DEV_REPLACE_DEVID) {
1028                 list_del_init(&device->dev_alloc_list);
1029                 fs_devices->rw_devices--;
1030         }
1031
1032         if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state))
1033                 fs_devices->missing_devices--;
1034
1035         btrfs_close_bdev(device);
1036
1037         new_device = btrfs_alloc_device(NULL, &device->devid,
1038                                         device->uuid);
1039         BUG_ON(IS_ERR(new_device)); /* -ENOMEM */
1040
1041         /* Safe because we are under uuid_mutex */
1042         if (device->name) {
1043                 name = rcu_string_strdup(device->name->str, GFP_NOFS);
1044                 BUG_ON(!name); /* -ENOMEM */
1045                 rcu_assign_pointer(new_device->name, name);
1046         }
1047
1048         list_replace_rcu(&device->dev_list, &new_device->dev_list);
1049         new_device->fs_devices = device->fs_devices;
1050
1051         call_rcu(&device->rcu, free_device_rcu);
1052 }
1053
1054 static int close_fs_devices(struct btrfs_fs_devices *fs_devices)
1055 {
1056         struct btrfs_device *device, *tmp;
1057
1058         if (--fs_devices->opened > 0)
1059                 return 0;
1060
1061         mutex_lock(&fs_devices->device_list_mutex);
1062         list_for_each_entry_safe(device, tmp, &fs_devices->devices, dev_list) {
1063                 btrfs_close_one_device(device);
1064         }
1065         mutex_unlock(&fs_devices->device_list_mutex);
1066
1067         WARN_ON(fs_devices->open_devices);
1068         WARN_ON(fs_devices->rw_devices);
1069         fs_devices->opened = 0;
1070         fs_devices->seeding = 0;
1071
1072         return 0;
1073 }
1074
1075 int btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
1076 {
1077         struct btrfs_fs_devices *seed_devices = NULL;
1078         int ret;
1079
1080         mutex_lock(&uuid_mutex);
1081         ret = close_fs_devices(fs_devices);
1082         if (!fs_devices->opened) {
1083                 seed_devices = fs_devices->seed;
1084                 fs_devices->seed = NULL;
1085         }
1086         mutex_unlock(&uuid_mutex);
1087
1088         while (seed_devices) {
1089                 fs_devices = seed_devices;
1090                 seed_devices = fs_devices->seed;
1091                 close_fs_devices(fs_devices);
1092                 free_fs_devices(fs_devices);
1093         }
1094         return ret;
1095 }
1096
1097 static int open_fs_devices(struct btrfs_fs_devices *fs_devices,
1098                                 fmode_t flags, void *holder)
1099 {
1100         struct btrfs_device *device;
1101         struct btrfs_device *latest_dev = NULL;
1102         int ret = 0;
1103
1104         flags |= FMODE_EXCL;
1105
1106         list_for_each_entry(device, &fs_devices->devices, dev_list) {
1107                 /* Just open everything we can; ignore failures here */
1108                 if (btrfs_open_one_device(fs_devices, device, flags, holder))
1109                         continue;
1110
1111                 if (!latest_dev ||
1112                     device->generation > latest_dev->generation)
1113                         latest_dev = device;
1114         }
1115         if (fs_devices->open_devices == 0) {
1116                 ret = -EINVAL;
1117                 goto out;
1118         }
1119         fs_devices->opened = 1;
1120         fs_devices->latest_bdev = latest_dev->bdev;
1121         fs_devices->total_rw_bytes = 0;
1122 out:
1123         return ret;
1124 }
1125
1126 static int devid_cmp(void *priv, struct list_head *a, struct list_head *b)
1127 {
1128         struct btrfs_device *dev1, *dev2;
1129
1130         dev1 = list_entry(a, struct btrfs_device, dev_list);
1131         dev2 = list_entry(b, struct btrfs_device, dev_list);
1132
1133         if (dev1->devid < dev2->devid)
1134                 return -1;
1135         else if (dev1->devid > dev2->devid)
1136                 return 1;
1137         return 0;
1138 }
1139
1140 int btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
1141                        fmode_t flags, void *holder)
1142 {
1143         int ret;
1144
1145         lockdep_assert_held(&uuid_mutex);
1146
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
1157         return ret;
1158 }
1159
1160 static void btrfs_release_disk_super(struct page *page)
1161 {
1162         kunmap(page);
1163         put_page(page);
1164 }
1165
1166 static int btrfs_read_disk_super(struct block_device *bdev, u64 bytenr,
1167                                  struct page **page,
1168                                  struct btrfs_super_block **disk_super)
1169 {
1170         void *p;
1171         pgoff_t index;
1172
1173         /* make sure our super fits in the device */
1174         if (bytenr + PAGE_SIZE >= i_size_read(bdev->bd_inode))
1175                 return 1;
1176
1177         /* make sure our super fits in the page */
1178         if (sizeof(**disk_super) > PAGE_SIZE)
1179                 return 1;
1180
1181         /* make sure our super doesn't straddle pages on disk */
1182         index = bytenr >> PAGE_SHIFT;
1183         if ((bytenr + sizeof(**disk_super) - 1) >> PAGE_SHIFT != index)
1184                 return 1;
1185
1186         /* pull in the page with our super */
1187         *page = read_cache_page_gfp(bdev->bd_inode->i_mapping,
1188                                    index, GFP_KERNEL);
1189
1190         if (IS_ERR_OR_NULL(*page))
1191                 return 1;
1192
1193         p = kmap(*page);
1194
1195         /* align our pointer to the offset of the super block */
1196         *disk_super = p + (bytenr & ~PAGE_MASK);
1197
1198         if (btrfs_super_bytenr(*disk_super) != bytenr ||
1199             btrfs_super_magic(*disk_super) != BTRFS_MAGIC) {
1200                 btrfs_release_disk_super(*page);
1201                 return 1;
1202         }
1203
1204         if ((*disk_super)->label[0] &&
1205                 (*disk_super)->label[BTRFS_LABEL_SIZE - 1])
1206                 (*disk_super)->label[BTRFS_LABEL_SIZE - 1] = '\0';
1207
1208         return 0;
1209 }
1210
1211 /*
1212  * Look for a btrfs signature on a device. This may be called out of the mount path
1213  * and we are not allowed to call set_blocksize during the scan. The superblock
1214  * is read via pagecache
1215  */
1216 struct btrfs_device *btrfs_scan_one_device(const char *path, fmode_t flags,
1217                                            void *holder)
1218 {
1219         struct btrfs_super_block *disk_super;
1220         bool new_device_added = false;
1221         struct btrfs_device *device = NULL;
1222         struct block_device *bdev;
1223         struct page *page;
1224         u64 bytenr;
1225
1226         lockdep_assert_held(&uuid_mutex);
1227
1228         /*
1229          * we would like to check all the supers, but that would make
1230          * a btrfs mount succeed after a mkfs from a different FS.
1231          * So, we need to add a special mount option to scan for
1232          * later supers, using BTRFS_SUPER_MIRROR_MAX instead
1233          */
1234         bytenr = btrfs_sb_offset(0);
1235         flags |= FMODE_EXCL;
1236
1237         bdev = blkdev_get_by_path(path, flags, holder);
1238         if (IS_ERR(bdev))
1239                 return ERR_CAST(bdev);
1240
1241         if (btrfs_read_disk_super(bdev, bytenr, &page, &disk_super)) {
1242                 device = ERR_PTR(-EINVAL);
1243                 goto error_bdev_put;
1244         }
1245
1246         device = device_list_add(path, disk_super, &new_device_added);
1247         if (!IS_ERR(device)) {
1248                 if (new_device_added)
1249                         btrfs_free_stale_devices(path, device);
1250         }
1251
1252         btrfs_release_disk_super(page);
1253
1254 error_bdev_put:
1255         blkdev_put(bdev, flags);
1256
1257         return device;
1258 }
1259
1260 static int contains_pending_extent(struct btrfs_transaction *transaction,
1261                                    struct btrfs_device *device,
1262                                    u64 *start, u64 len)
1263 {
1264         struct btrfs_fs_info *fs_info = device->fs_info;
1265         struct extent_map *em;
1266         struct list_head *search_list = &fs_info->pinned_chunks;
1267         int ret = 0;
1268         u64 physical_start = *start;
1269
1270         if (transaction)
1271                 search_list = &transaction->pending_chunks;
1272 again:
1273         list_for_each_entry(em, search_list, list) {
1274                 struct map_lookup *map;
1275                 int i;
1276
1277                 map = em->map_lookup;
1278                 for (i = 0; i < map->num_stripes; i++) {
1279                         u64 end;
1280
1281                         if (map->stripes[i].dev != device)
1282                                 continue;
1283                         if (map->stripes[i].physical >= physical_start + len ||
1284                             map->stripes[i].physical + em->orig_block_len <=
1285                             physical_start)
1286                                 continue;
1287                         /*
1288                          * Make sure that while processing the pinned list we do
1289                          * not override our *start with a lower value, because
1290                          * we can have pinned chunks that fall within this
1291                          * device hole and that have lower physical addresses
1292                          * than the pending chunks we processed before. If we
1293                          * do not take this special care we can end up getting
1294                          * 2 pending chunks that start at the same physical
1295                          * device offsets because the end offset of a pinned
1296                          * chunk can be equal to the start offset of some
1297                          * pending chunk.
1298                          */
1299                         end = map->stripes[i].physical + em->orig_block_len;
1300                         if (end > *start) {
1301                                 *start = end;
1302                                 ret = 1;
1303                         }
1304                 }
1305         }
1306         if (search_list != &fs_info->pinned_chunks) {
1307                 search_list = &fs_info->pinned_chunks;
1308                 goto again;
1309         }
1310
1311         return ret;
1312 }
1313
1314
1315 /*
1316  * find_free_dev_extent_start - find free space in the specified device
1317  * @device:       the device which we search the free space in
1318  * @num_bytes:    the size of the free space that we need
1319  * @search_start: the position from which to begin the search
1320  * @start:        store the start of the free space.
1321  * @len:          the size of the free space. that we find, or the size
1322  *                of the max free space if we don't find suitable free space
1323  *
1324  * this uses a pretty simple search, the expectation is that it is
1325  * called very infrequently and that a given device has a small number
1326  * of extents
1327  *
1328  * @start is used to store the start of the free space if we find. But if we
1329  * don't find suitable free space, it will be used to store the start position
1330  * of the max free space.
1331  *
1332  * @len is used to store the size of the free space that we find.
1333  * But if we don't find suitable free space, it is used to store the size of
1334  * the max free space.
1335  */
1336 int find_free_dev_extent_start(struct btrfs_transaction *transaction,
1337                                struct btrfs_device *device, u64 num_bytes,
1338                                u64 search_start, u64 *start, u64 *len)
1339 {
1340         struct btrfs_fs_info *fs_info = device->fs_info;
1341         struct btrfs_root *root = fs_info->dev_root;
1342         struct btrfs_key key;
1343         struct btrfs_dev_extent *dev_extent;
1344         struct btrfs_path *path;
1345         u64 hole_size;
1346         u64 max_hole_start;
1347         u64 max_hole_size;
1348         u64 extent_end;
1349         u64 search_end = device->total_bytes;
1350         int ret;
1351         int slot;
1352         struct extent_buffer *l;
1353
1354         /*
1355          * We don't want to overwrite the superblock on the drive nor any area
1356          * used by the boot loader (grub for example), so we make sure to start
1357          * at an offset of at least 1MB.
1358          */
1359         search_start = max_t(u64, search_start, SZ_1M);
1360
1361         path = btrfs_alloc_path();
1362         if (!path)
1363                 return -ENOMEM;
1364
1365         max_hole_start = search_start;
1366         max_hole_size = 0;
1367
1368 again:
1369         if (search_start >= search_end ||
1370                 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
1371                 ret = -ENOSPC;
1372                 goto out;
1373         }
1374
1375         path->reada = READA_FORWARD;
1376         path->search_commit_root = 1;
1377         path->skip_locking = 1;
1378
1379         key.objectid = device->devid;
1380         key.offset = search_start;
1381         key.type = BTRFS_DEV_EXTENT_KEY;
1382
1383         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1384         if (ret < 0)
1385                 goto out;
1386         if (ret > 0) {
1387                 ret = btrfs_previous_item(root, path, key.objectid, key.type);
1388                 if (ret < 0)
1389                         goto out;
1390         }
1391
1392         while (1) {
1393                 l = path->nodes[0];
1394                 slot = path->slots[0];
1395                 if (slot >= btrfs_header_nritems(l)) {
1396                         ret = btrfs_next_leaf(root, path);
1397                         if (ret == 0)
1398                                 continue;
1399                         if (ret < 0)
1400                                 goto out;
1401
1402                         break;
1403                 }
1404                 btrfs_item_key_to_cpu(l, &key, slot);
1405
1406                 if (key.objectid < device->devid)
1407                         goto next;
1408
1409                 if (key.objectid > device->devid)
1410                         break;
1411
1412                 if (key.type != BTRFS_DEV_EXTENT_KEY)
1413                         goto next;
1414
1415                 if (key.offset > search_start) {
1416                         hole_size = key.offset - search_start;
1417
1418                         /*
1419                          * Have to check before we set max_hole_start, otherwise
1420                          * we could end up sending back this offset anyway.
1421                          */
1422                         if (contains_pending_extent(transaction, device,
1423                                                     &search_start,
1424                                                     hole_size)) {
1425                                 if (key.offset >= search_start) {
1426                                         hole_size = key.offset - search_start;
1427                                 } else {
1428                                         WARN_ON_ONCE(1);
1429                                         hole_size = 0;
1430                                 }
1431                         }
1432
1433                         if (hole_size > max_hole_size) {
1434                                 max_hole_start = search_start;
1435                                 max_hole_size = hole_size;
1436                         }
1437
1438                         /*
1439                          * If this free space is greater than which we need,
1440                          * it must be the max free space that we have found
1441                          * until now, so max_hole_start must point to the start
1442                          * of this free space and the length of this free space
1443                          * is stored in max_hole_size. Thus, we return
1444                          * max_hole_start and max_hole_size and go back to the
1445                          * caller.
1446                          */
1447                         if (hole_size >= num_bytes) {
1448                                 ret = 0;
1449                                 goto out;
1450                         }
1451                 }
1452
1453                 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
1454                 extent_end = key.offset + btrfs_dev_extent_length(l,
1455                                                                   dev_extent);
1456                 if (extent_end > search_start)
1457                         search_start = extent_end;
1458 next:
1459                 path->slots[0]++;
1460                 cond_resched();
1461         }
1462
1463         /*
1464          * At this point, search_start should be the end of
1465          * allocated dev extents, and when shrinking the device,
1466          * search_end may be smaller than search_start.
1467          */
1468         if (search_end > search_start) {
1469                 hole_size = search_end - search_start;
1470
1471                 if (contains_pending_extent(transaction, device, &search_start,
1472                                             hole_size)) {
1473                         btrfs_release_path(path);
1474                         goto again;
1475                 }
1476
1477                 if (hole_size > max_hole_size) {
1478                         max_hole_start = search_start;
1479                         max_hole_size = hole_size;
1480                 }
1481         }
1482
1483         /* See above. */
1484         if (max_hole_size < num_bytes)
1485                 ret = -ENOSPC;
1486         else
1487                 ret = 0;
1488
1489 out:
1490         btrfs_free_path(path);
1491         *start = max_hole_start;
1492         if (len)
1493                 *len = max_hole_size;
1494         return ret;
1495 }
1496
1497 int find_free_dev_extent(struct btrfs_trans_handle *trans,
1498                          struct btrfs_device *device, u64 num_bytes,
1499                          u64 *start, u64 *len)
1500 {
1501         /* FIXME use last free of some kind */
1502         return find_free_dev_extent_start(trans->transaction, device,
1503                                           num_bytes, 0, start, len);
1504 }
1505
1506 static int btrfs_free_dev_extent(struct btrfs_trans_handle *trans,
1507                           struct btrfs_device *device,
1508                           u64 start, u64 *dev_extent_len)
1509 {
1510         struct btrfs_fs_info *fs_info = device->fs_info;
1511         struct btrfs_root *root = fs_info->dev_root;
1512         int ret;
1513         struct btrfs_path *path;
1514         struct btrfs_key key;
1515         struct btrfs_key found_key;
1516         struct extent_buffer *leaf = NULL;
1517         struct btrfs_dev_extent *extent = NULL;
1518
1519         path = btrfs_alloc_path();
1520         if (!path)
1521                 return -ENOMEM;
1522
1523         key.objectid = device->devid;
1524         key.offset = start;
1525         key.type = BTRFS_DEV_EXTENT_KEY;
1526 again:
1527         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1528         if (ret > 0) {
1529                 ret = btrfs_previous_item(root, path, key.objectid,
1530                                           BTRFS_DEV_EXTENT_KEY);
1531                 if (ret)
1532                         goto out;
1533                 leaf = path->nodes[0];
1534                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1535                 extent = btrfs_item_ptr(leaf, path->slots[0],
1536                                         struct btrfs_dev_extent);
1537                 BUG_ON(found_key.offset > start || found_key.offset +
1538                        btrfs_dev_extent_length(leaf, extent) < start);
1539                 key = found_key;
1540                 btrfs_release_path(path);
1541                 goto again;
1542         } else if (ret == 0) {
1543                 leaf = path->nodes[0];
1544                 extent = btrfs_item_ptr(leaf, path->slots[0],
1545                                         struct btrfs_dev_extent);
1546         } else {
1547                 btrfs_handle_fs_error(fs_info, ret, "Slot search failed");
1548                 goto out;
1549         }
1550
1551         *dev_extent_len = btrfs_dev_extent_length(leaf, extent);
1552
1553         ret = btrfs_del_item(trans, root, path);
1554         if (ret) {
1555                 btrfs_handle_fs_error(fs_info, ret,
1556                                       "Failed to remove dev extent item");
1557         } else {
1558                 set_bit(BTRFS_TRANS_HAVE_FREE_BGS, &trans->transaction->flags);
1559         }
1560 out:
1561         btrfs_free_path(path);
1562         return ret;
1563 }
1564
1565 static int btrfs_alloc_dev_extent(struct btrfs_trans_handle *trans,
1566                                   struct btrfs_device *device,
1567                                   u64 chunk_offset, u64 start, u64 num_bytes)
1568 {
1569         int ret;
1570         struct btrfs_path *path;
1571         struct btrfs_fs_info *fs_info = device->fs_info;
1572         struct btrfs_root *root = fs_info->dev_root;
1573         struct btrfs_dev_extent *extent;
1574         struct extent_buffer *leaf;
1575         struct btrfs_key key;
1576
1577         WARN_ON(!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state));
1578         WARN_ON(test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state));
1579         path = btrfs_alloc_path();
1580         if (!path)
1581                 return -ENOMEM;
1582
1583         key.objectid = device->devid;
1584         key.offset = start;
1585         key.type = BTRFS_DEV_EXTENT_KEY;
1586         ret = btrfs_insert_empty_item(trans, root, path, &key,
1587                                       sizeof(*extent));
1588         if (ret)
1589                 goto out;
1590
1591         leaf = path->nodes[0];
1592         extent = btrfs_item_ptr(leaf, path->slots[0],
1593                                 struct btrfs_dev_extent);
1594         btrfs_set_dev_extent_chunk_tree(leaf, extent,
1595                                         BTRFS_CHUNK_TREE_OBJECTID);
1596         btrfs_set_dev_extent_chunk_objectid(leaf, extent,
1597                                             BTRFS_FIRST_CHUNK_TREE_OBJECTID);
1598         btrfs_set_dev_extent_chunk_offset(leaf, extent, chunk_offset);
1599
1600         btrfs_set_dev_extent_length(leaf, extent, num_bytes);
1601         btrfs_mark_buffer_dirty(leaf);
1602 out:
1603         btrfs_free_path(path);
1604         return ret;
1605 }
1606
1607 static u64 find_next_chunk(struct btrfs_fs_info *fs_info)
1608 {
1609         struct extent_map_tree *em_tree;
1610         struct extent_map *em;
1611         struct rb_node *n;
1612         u64 ret = 0;
1613
1614         em_tree = &fs_info->mapping_tree.map_tree;
1615         read_lock(&em_tree->lock);
1616         n = rb_last(&em_tree->map.rb_root);
1617         if (n) {
1618                 em = rb_entry(n, struct extent_map, rb_node);
1619                 ret = em->start + em->len;
1620         }
1621         read_unlock(&em_tree->lock);
1622
1623         return ret;
1624 }
1625
1626 static noinline int find_next_devid(struct btrfs_fs_info *fs_info,
1627                                     u64 *devid_ret)
1628 {
1629         int ret;
1630         struct btrfs_key key;
1631         struct btrfs_key found_key;
1632         struct btrfs_path *path;
1633
1634         path = btrfs_alloc_path();
1635         if (!path)
1636                 return -ENOMEM;
1637
1638         key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1639         key.type = BTRFS_DEV_ITEM_KEY;
1640         key.offset = (u64)-1;
1641
1642         ret = btrfs_search_slot(NULL, fs_info->chunk_root, &key, path, 0, 0);
1643         if (ret < 0)
1644                 goto error;
1645
1646         BUG_ON(ret == 0); /* Corruption */
1647
1648         ret = btrfs_previous_item(fs_info->chunk_root, path,
1649                                   BTRFS_DEV_ITEMS_OBJECTID,
1650                                   BTRFS_DEV_ITEM_KEY);
1651         if (ret) {
1652                 *devid_ret = 1;
1653         } else {
1654                 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
1655                                       path->slots[0]);
1656                 *devid_ret = found_key.offset + 1;
1657         }
1658         ret = 0;
1659 error:
1660         btrfs_free_path(path);
1661         return ret;
1662 }
1663
1664 /*
1665  * the device information is stored in the chunk root
1666  * the btrfs_device struct should be fully filled in
1667  */
1668 static int btrfs_add_dev_item(struct btrfs_trans_handle *trans,
1669                             struct btrfs_device *device)
1670 {
1671         int ret;
1672         struct btrfs_path *path;
1673         struct btrfs_dev_item *dev_item;
1674         struct extent_buffer *leaf;
1675         struct btrfs_key key;
1676         unsigned long ptr;
1677
1678         path = btrfs_alloc_path();
1679         if (!path)
1680                 return -ENOMEM;
1681
1682         key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1683         key.type = BTRFS_DEV_ITEM_KEY;
1684         key.offset = device->devid;
1685
1686         ret = btrfs_insert_empty_item(trans, trans->fs_info->chunk_root, path,
1687                                       &key, sizeof(*dev_item));
1688         if (ret)
1689                 goto out;
1690
1691         leaf = path->nodes[0];
1692         dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
1693
1694         btrfs_set_device_id(leaf, dev_item, device->devid);
1695         btrfs_set_device_generation(leaf, dev_item, 0);
1696         btrfs_set_device_type(leaf, dev_item, device->type);
1697         btrfs_set_device_io_align(leaf, dev_item, device->io_align);
1698         btrfs_set_device_io_width(leaf, dev_item, device->io_width);
1699         btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
1700         btrfs_set_device_total_bytes(leaf, dev_item,
1701                                      btrfs_device_get_disk_total_bytes(device));
1702         btrfs_set_device_bytes_used(leaf, dev_item,
1703                                     btrfs_device_get_bytes_used(device));
1704         btrfs_set_device_group(leaf, dev_item, 0);
1705         btrfs_set_device_seek_speed(leaf, dev_item, 0);
1706         btrfs_set_device_bandwidth(leaf, dev_item, 0);
1707         btrfs_set_device_start_offset(leaf, dev_item, 0);
1708
1709         ptr = btrfs_device_uuid(dev_item);
1710         write_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
1711         ptr = btrfs_device_fsid(dev_item);
1712         write_extent_buffer(leaf, trans->fs_info->fsid, ptr, BTRFS_FSID_SIZE);
1713         btrfs_mark_buffer_dirty(leaf);
1714
1715         ret = 0;
1716 out:
1717         btrfs_free_path(path);
1718         return ret;
1719 }
1720
1721 /*
1722  * Function to update ctime/mtime for a given device path.
1723  * Mainly used for ctime/mtime based probe like libblkid.
1724  */
1725 static void update_dev_time(const char *path_name)
1726 {
1727         struct file *filp;
1728
1729         filp = filp_open(path_name, O_RDWR, 0);
1730         if (IS_ERR(filp))
1731                 return;
1732         file_update_time(filp);
1733         filp_close(filp, NULL);
1734 }
1735
1736 static int btrfs_rm_dev_item(struct btrfs_fs_info *fs_info,
1737                              struct btrfs_device *device)
1738 {
1739         struct btrfs_root *root = fs_info->chunk_root;
1740         int ret;
1741         struct btrfs_path *path;
1742         struct btrfs_key key;
1743         struct btrfs_trans_handle *trans;
1744
1745         path = btrfs_alloc_path();
1746         if (!path)
1747                 return -ENOMEM;
1748
1749         trans = btrfs_start_transaction(root, 0);
1750         if (IS_ERR(trans)) {
1751                 btrfs_free_path(path);
1752                 return PTR_ERR(trans);
1753         }
1754         key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1755         key.type = BTRFS_DEV_ITEM_KEY;
1756         key.offset = device->devid;
1757
1758         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1759         if (ret) {
1760                 if (ret > 0)
1761                         ret = -ENOENT;
1762                 btrfs_abort_transaction(trans, ret);
1763                 btrfs_end_transaction(trans);
1764                 goto out;
1765         }
1766
1767         ret = btrfs_del_item(trans, root, path);
1768         if (ret) {
1769                 btrfs_abort_transaction(trans, ret);
1770                 btrfs_end_transaction(trans);
1771         }
1772
1773 out:
1774         btrfs_free_path(path);
1775         if (!ret)
1776                 ret = btrfs_commit_transaction(trans);
1777         return ret;
1778 }
1779
1780 /*
1781  * Verify that @num_devices satisfies the RAID profile constraints in the whole
1782  * filesystem. It's up to the caller to adjust that number regarding eg. device
1783  * replace.
1784  */
1785 static int btrfs_check_raid_min_devices(struct btrfs_fs_info *fs_info,
1786                 u64 num_devices)
1787 {
1788         u64 all_avail;
1789         unsigned seq;
1790         int i;
1791
1792         do {
1793                 seq = read_seqbegin(&fs_info->profiles_lock);
1794
1795                 all_avail = fs_info->avail_data_alloc_bits |
1796                             fs_info->avail_system_alloc_bits |
1797                             fs_info->avail_metadata_alloc_bits;
1798         } while (read_seqretry(&fs_info->profiles_lock, seq));
1799
1800         for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
1801                 if (!(all_avail & btrfs_raid_array[i].bg_flag))
1802                         continue;
1803
1804                 if (num_devices < btrfs_raid_array[i].devs_min) {
1805                         int ret = btrfs_raid_array[i].mindev_error;
1806
1807                         if (ret)
1808                                 return ret;
1809                 }
1810         }
1811
1812         return 0;
1813 }
1814
1815 static struct btrfs_device * btrfs_find_next_active_device(
1816                 struct btrfs_fs_devices *fs_devs, struct btrfs_device *device)
1817 {
1818         struct btrfs_device *next_device;
1819
1820         list_for_each_entry(next_device, &fs_devs->devices, dev_list) {
1821                 if (next_device != device &&
1822                     !test_bit(BTRFS_DEV_STATE_MISSING, &next_device->dev_state)
1823                     && next_device->bdev)
1824                         return next_device;
1825         }
1826
1827         return NULL;
1828 }
1829
1830 /*
1831  * Helper function to check if the given device is part of s_bdev / latest_bdev
1832  * and replace it with the provided or the next active device, in the context
1833  * where this function called, there should be always be another device (or
1834  * this_dev) which is active.
1835  */
1836 void btrfs_assign_next_active_device(struct btrfs_device *device,
1837                                      struct btrfs_device *this_dev)
1838 {
1839         struct btrfs_fs_info *fs_info = device->fs_info;
1840         struct btrfs_device *next_device;
1841
1842         if (this_dev)
1843                 next_device = this_dev;
1844         else
1845                 next_device = btrfs_find_next_active_device(fs_info->fs_devices,
1846                                                                 device);
1847         ASSERT(next_device);
1848
1849         if (fs_info->sb->s_bdev &&
1850                         (fs_info->sb->s_bdev == device->bdev))
1851                 fs_info->sb->s_bdev = next_device->bdev;
1852
1853         if (fs_info->fs_devices->latest_bdev == device->bdev)
1854                 fs_info->fs_devices->latest_bdev = next_device->bdev;
1855 }
1856
1857 /*
1858  * Return btrfs_fs_devices::num_devices excluding the device that's being
1859  * currently replaced.
1860  */
1861 static u64 btrfs_num_devices(struct btrfs_fs_info *fs_info)
1862 {
1863         u64 num_devices = fs_info->fs_devices->num_devices;
1864
1865         btrfs_dev_replace_read_lock(&fs_info->dev_replace);
1866         if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace)) {
1867                 ASSERT(num_devices > 1);
1868                 num_devices--;
1869         }
1870         btrfs_dev_replace_read_unlock(&fs_info->dev_replace);
1871
1872         return num_devices;
1873 }
1874
1875 int btrfs_rm_device(struct btrfs_fs_info *fs_info, const char *device_path,
1876                 u64 devid)
1877 {
1878         struct btrfs_device *device;
1879         struct btrfs_fs_devices *cur_devices;
1880         struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
1881         u64 num_devices;
1882         int ret = 0;
1883
1884         mutex_lock(&uuid_mutex);
1885
1886         num_devices = btrfs_num_devices(fs_info);
1887
1888         ret = btrfs_check_raid_min_devices(fs_info, num_devices - 1);
1889         if (ret)
1890                 goto out;
1891
1892         device = btrfs_find_device_by_devspec(fs_info, devid, device_path);
1893
1894         if (IS_ERR(device)) {
1895                 if (PTR_ERR(device) == -ENOENT &&
1896                     strcmp(device_path, "missing") == 0)
1897                         ret = BTRFS_ERROR_DEV_MISSING_NOT_FOUND;
1898                 else
1899                         ret = PTR_ERR(device);
1900                 goto out;
1901         }
1902
1903         if (btrfs_pinned_by_swapfile(fs_info, device)) {
1904                 btrfs_warn_in_rcu(fs_info,
1905                   "cannot remove device %s (devid %llu) due to active swapfile",
1906                                   rcu_str_deref(device->name), device->devid);
1907                 ret = -ETXTBSY;
1908                 goto out;
1909         }
1910
1911         if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
1912                 ret = BTRFS_ERROR_DEV_TGT_REPLACE;
1913                 goto out;
1914         }
1915
1916         if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
1917             fs_info->fs_devices->rw_devices == 1) {
1918                 ret = BTRFS_ERROR_DEV_ONLY_WRITABLE;
1919                 goto out;
1920         }
1921
1922         if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
1923                 mutex_lock(&fs_info->chunk_mutex);
1924                 list_del_init(&device->dev_alloc_list);
1925                 device->fs_devices->rw_devices--;
1926                 mutex_unlock(&fs_info->chunk_mutex);
1927         }
1928
1929         mutex_unlock(&uuid_mutex);
1930         ret = btrfs_shrink_device(device, 0);
1931         mutex_lock(&uuid_mutex);
1932         if (ret)
1933                 goto error_undo;
1934
1935         /*
1936          * TODO: the superblock still includes this device in its num_devices
1937          * counter although write_all_supers() is not locked out. This
1938          * could give a filesystem state which requires a degraded mount.
1939          */
1940         ret = btrfs_rm_dev_item(fs_info, device);
1941         if (ret)
1942                 goto error_undo;
1943
1944         clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
1945         btrfs_scrub_cancel_dev(fs_info, device);
1946
1947         /*
1948          * the device list mutex makes sure that we don't change
1949          * the device list while someone else is writing out all
1950          * the device supers. Whoever is writing all supers, should
1951          * lock the device list mutex before getting the number of
1952          * devices in the super block (super_copy). Conversely,
1953          * whoever updates the number of devices in the super block
1954          * (super_copy) should hold the device list mutex.
1955          */
1956
1957         /*
1958          * In normal cases the cur_devices == fs_devices. But in case
1959          * of deleting a seed device, the cur_devices should point to
1960          * its own fs_devices listed under the fs_devices->seed.
1961          */
1962         cur_devices = device->fs_devices;
1963         mutex_lock(&fs_devices->device_list_mutex);
1964         list_del_rcu(&device->dev_list);
1965
1966         cur_devices->num_devices--;
1967         cur_devices->total_devices--;
1968         /* Update total_devices of the parent fs_devices if it's seed */
1969         if (cur_devices != fs_devices)
1970                 fs_devices->total_devices--;
1971
1972         if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state))
1973                 cur_devices->missing_devices--;
1974
1975         btrfs_assign_next_active_device(device, NULL);
1976
1977         if (device->bdev) {
1978                 cur_devices->open_devices--;
1979                 /* remove sysfs entry */
1980                 btrfs_sysfs_rm_device_link(fs_devices, device);
1981         }
1982
1983         num_devices = btrfs_super_num_devices(fs_info->super_copy) - 1;
1984         btrfs_set_super_num_devices(fs_info->super_copy, num_devices);
1985         mutex_unlock(&fs_devices->device_list_mutex);
1986
1987         /*
1988          * at this point, the device is zero sized and detached from
1989          * the devices list.  All that's left is to zero out the old
1990          * supers and free the device.
1991          */
1992         if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
1993                 btrfs_scratch_superblocks(device->bdev, device->name->str);
1994
1995         btrfs_close_bdev(device);
1996         call_rcu(&device->rcu, free_device_rcu);
1997
1998         if (cur_devices->open_devices == 0) {
1999                 while (fs_devices) {
2000                         if (fs_devices->seed == cur_devices) {
2001                                 fs_devices->seed = cur_devices->seed;
2002                                 break;
2003                         }
2004                         fs_devices = fs_devices->seed;
2005                 }
2006                 cur_devices->seed = NULL;
2007                 close_fs_devices(cur_devices);
2008                 free_fs_devices(cur_devices);
2009         }
2010
2011 out:
2012         mutex_unlock(&uuid_mutex);
2013         return ret;
2014
2015 error_undo:
2016         if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
2017                 mutex_lock(&fs_info->chunk_mutex);
2018                 list_add(&device->dev_alloc_list,
2019                          &fs_devices->alloc_list);
2020                 device->fs_devices->rw_devices++;
2021                 mutex_unlock(&fs_info->chunk_mutex);
2022         }
2023         goto out;
2024 }
2025
2026 void btrfs_rm_dev_replace_remove_srcdev(struct btrfs_device *srcdev)
2027 {
2028         struct btrfs_fs_devices *fs_devices;
2029
2030         lockdep_assert_held(&srcdev->fs_info->fs_devices->device_list_mutex);
2031
2032         /*
2033          * in case of fs with no seed, srcdev->fs_devices will point
2034          * to fs_devices of fs_info. However when the dev being replaced is
2035          * a seed dev it will point to the seed's local fs_devices. In short
2036          * srcdev will have its correct fs_devices in both the cases.
2037          */
2038         fs_devices = srcdev->fs_devices;
2039
2040         list_del_rcu(&srcdev->dev_list);
2041         list_del(&srcdev->dev_alloc_list);
2042         fs_devices->num_devices--;
2043         if (test_bit(BTRFS_DEV_STATE_MISSING, &srcdev->dev_state))
2044                 fs_devices->missing_devices--;
2045
2046         if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &srcdev->dev_state))
2047                 fs_devices->rw_devices--;
2048
2049         if (srcdev->bdev)
2050                 fs_devices->open_devices--;
2051 }
2052
2053 void btrfs_rm_dev_replace_free_srcdev(struct btrfs_fs_info *fs_info,
2054                                       struct btrfs_device *srcdev)
2055 {
2056         struct btrfs_fs_devices *fs_devices = srcdev->fs_devices;
2057
2058         if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &srcdev->dev_state)) {
2059                 /* zero out the old super if it is writable */
2060                 btrfs_scratch_superblocks(srcdev->bdev, srcdev->name->str);
2061         }
2062
2063         btrfs_close_bdev(srcdev);
2064         call_rcu(&srcdev->rcu, free_device_rcu);
2065
2066         /* if this is no devs we rather delete the fs_devices */
2067         if (!fs_devices->num_devices) {
2068                 struct btrfs_fs_devices *tmp_fs_devices;
2069
2070                 /*
2071                  * On a mounted FS, num_devices can't be zero unless it's a
2072                  * seed. In case of a seed device being replaced, the replace
2073                  * target added to the sprout FS, so there will be no more
2074                  * device left under the seed FS.
2075                  */
2076                 ASSERT(fs_devices->seeding);
2077
2078                 tmp_fs_devices = fs_info->fs_devices;
2079                 while (tmp_fs_devices) {
2080                         if (tmp_fs_devices->seed == fs_devices) {
2081                                 tmp_fs_devices->seed = fs_devices->seed;
2082                                 break;
2083                         }
2084                         tmp_fs_devices = tmp_fs_devices->seed;
2085                 }
2086                 fs_devices->seed = NULL;
2087                 close_fs_devices(fs_devices);
2088                 free_fs_devices(fs_devices);
2089         }
2090 }
2091
2092 void btrfs_destroy_dev_replace_tgtdev(struct btrfs_device *tgtdev)
2093 {
2094         struct btrfs_fs_devices *fs_devices = tgtdev->fs_info->fs_devices;
2095
2096         WARN_ON(!tgtdev);
2097         mutex_lock(&fs_devices->device_list_mutex);
2098
2099         btrfs_sysfs_rm_device_link(fs_devices, tgtdev);
2100
2101         if (tgtdev->bdev)
2102                 fs_devices->open_devices--;
2103
2104         fs_devices->num_devices--;
2105
2106         btrfs_assign_next_active_device(tgtdev, NULL);
2107
2108         list_del_rcu(&tgtdev->dev_list);
2109
2110         mutex_unlock(&fs_devices->device_list_mutex);
2111
2112         /*
2113          * The update_dev_time() with in btrfs_scratch_superblocks()
2114          * may lead to a call to btrfs_show_devname() which will try
2115          * to hold device_list_mutex. And here this device
2116          * is already out of device list, so we don't have to hold
2117          * the device_list_mutex lock.
2118          */
2119         btrfs_scratch_superblocks(tgtdev->bdev, tgtdev->name->str);
2120
2121         btrfs_close_bdev(tgtdev);
2122         call_rcu(&tgtdev->rcu, free_device_rcu);
2123 }
2124
2125 static struct btrfs_device *btrfs_find_device_by_path(
2126                 struct btrfs_fs_info *fs_info, const char *device_path)
2127 {
2128         int ret = 0;
2129         struct btrfs_super_block *disk_super;
2130         u64 devid;
2131         u8 *dev_uuid;
2132         struct block_device *bdev;
2133         struct buffer_head *bh;
2134         struct btrfs_device *device;
2135
2136         ret = btrfs_get_bdev_and_sb(device_path, FMODE_READ,
2137                                     fs_info->bdev_holder, 0, &bdev, &bh);
2138         if (ret)
2139                 return ERR_PTR(ret);
2140         disk_super = (struct btrfs_super_block *)bh->b_data;
2141         devid = btrfs_stack_device_id(&disk_super->dev_item);
2142         dev_uuid = disk_super->dev_item.uuid;
2143         device = btrfs_find_device(fs_info, devid, dev_uuid, disk_super->fsid);
2144         brelse(bh);
2145         if (!device)
2146                 device = ERR_PTR(-ENOENT);
2147         blkdev_put(bdev, FMODE_READ);
2148         return device;
2149 }
2150
2151 static struct btrfs_device *btrfs_find_device_missing_or_by_path(
2152                 struct btrfs_fs_info *fs_info, const char *device_path)
2153 {
2154         struct btrfs_device *device = NULL;
2155         if (strcmp(device_path, "missing") == 0) {
2156                 struct list_head *devices;
2157                 struct btrfs_device *tmp;
2158
2159                 devices = &fs_info->fs_devices->devices;
2160                 list_for_each_entry(tmp, devices, dev_list) {
2161                         if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
2162                                         &tmp->dev_state) && !tmp->bdev) {
2163                                 device = tmp;
2164                                 break;
2165                         }
2166                 }
2167
2168                 if (!device)
2169                         return ERR_PTR(-ENOENT);
2170         } else {
2171                 device = btrfs_find_device_by_path(fs_info, device_path);
2172         }
2173
2174         return device;
2175 }
2176
2177 /*
2178  * Lookup a device given by device id, or the path if the id is 0.
2179  */
2180 struct btrfs_device *btrfs_find_device_by_devspec(
2181                 struct btrfs_fs_info *fs_info, u64 devid, const char *devpath)
2182 {
2183         struct btrfs_device *device;
2184
2185         if (devid) {
2186                 device = btrfs_find_device(fs_info, devid, NULL, NULL);
2187                 if (!device)
2188                         return ERR_PTR(-ENOENT);
2189         } else {
2190                 if (!devpath || !devpath[0])
2191                         return ERR_PTR(-EINVAL);
2192                 device = btrfs_find_device_missing_or_by_path(fs_info, devpath);
2193         }
2194         return device;
2195 }
2196
2197 /*
2198  * does all the dirty work required for changing file system's UUID.
2199  */
2200 static int btrfs_prepare_sprout(struct btrfs_fs_info *fs_info)
2201 {
2202         struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2203         struct btrfs_fs_devices *old_devices;
2204         struct btrfs_fs_devices *seed_devices;
2205         struct btrfs_super_block *disk_super = fs_info->super_copy;
2206         struct btrfs_device *device;
2207         u64 super_flags;
2208
2209         lockdep_assert_held(&uuid_mutex);
2210         if (!fs_devices->seeding)
2211                 return -EINVAL;
2212
2213         seed_devices = alloc_fs_devices(NULL);
2214         if (IS_ERR(seed_devices))
2215                 return PTR_ERR(seed_devices);
2216
2217         old_devices = clone_fs_devices(fs_devices);
2218         if (IS_ERR(old_devices)) {
2219                 kfree(seed_devices);
2220                 return PTR_ERR(old_devices);
2221         }
2222
2223         list_add(&old_devices->fs_list, &fs_uuids);
2224
2225         memcpy(seed_devices, fs_devices, sizeof(*seed_devices));
2226         seed_devices->opened = 1;
2227         INIT_LIST_HEAD(&seed_devices->devices);
2228         INIT_LIST_HEAD(&seed_devices->alloc_list);
2229         mutex_init(&seed_devices->device_list_mutex);
2230
2231         mutex_lock(&fs_devices->device_list_mutex);
2232         list_splice_init_rcu(&fs_devices->devices, &seed_devices->devices,
2233                               synchronize_rcu);
2234         list_for_each_entry(device, &seed_devices->devices, dev_list)
2235                 device->fs_devices = seed_devices;
2236
2237         mutex_lock(&fs_info->chunk_mutex);
2238         list_splice_init(&fs_devices->alloc_list, &seed_devices->alloc_list);
2239         mutex_unlock(&fs_info->chunk_mutex);
2240
2241         fs_devices->seeding = 0;
2242         fs_devices->num_devices = 0;
2243         fs_devices->open_devices = 0;
2244         fs_devices->missing_devices = 0;
2245         fs_devices->rotating = 0;
2246         fs_devices->seed = seed_devices;
2247
2248         generate_random_uuid(fs_devices->fsid);
2249         memcpy(fs_info->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
2250         memcpy(disk_super->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
2251         mutex_unlock(&fs_devices->device_list_mutex);
2252
2253         super_flags = btrfs_super_flags(disk_super) &
2254                       ~BTRFS_SUPER_FLAG_SEEDING;
2255         btrfs_set_super_flags(disk_super, super_flags);
2256
2257         return 0;
2258 }
2259
2260 /*
2261  * Store the expected generation for seed devices in device items.
2262  */
2263 static int btrfs_finish_sprout(struct btrfs_trans_handle *trans,
2264                                struct btrfs_fs_info *fs_info)
2265 {
2266         struct btrfs_root *root = fs_info->chunk_root;
2267         struct btrfs_path *path;
2268         struct extent_buffer *leaf;
2269         struct btrfs_dev_item *dev_item;
2270         struct btrfs_device *device;
2271         struct btrfs_key key;
2272         u8 fs_uuid[BTRFS_FSID_SIZE];
2273         u8 dev_uuid[BTRFS_UUID_SIZE];
2274         u64 devid;
2275         int ret;
2276
2277         path = btrfs_alloc_path();
2278         if (!path)
2279                 return -ENOMEM;
2280
2281         key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2282         key.offset = 0;
2283         key.type = BTRFS_DEV_ITEM_KEY;
2284
2285         while (1) {
2286                 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2287                 if (ret < 0)
2288                         goto error;
2289
2290                 leaf = path->nodes[0];
2291 next_slot:
2292                 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
2293                         ret = btrfs_next_leaf(root, path);
2294                         if (ret > 0)
2295                                 break;
2296                         if (ret < 0)
2297                                 goto error;
2298                         leaf = path->nodes[0];
2299                         btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2300                         btrfs_release_path(path);
2301                         continue;
2302                 }
2303
2304                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2305                 if (key.objectid != BTRFS_DEV_ITEMS_OBJECTID ||
2306                     key.type != BTRFS_DEV_ITEM_KEY)
2307                         break;
2308
2309                 dev_item = btrfs_item_ptr(leaf, path->slots[0],
2310                                           struct btrfs_dev_item);
2311                 devid = btrfs_device_id(leaf, dev_item);
2312                 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
2313                                    BTRFS_UUID_SIZE);
2314                 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
2315                                    BTRFS_FSID_SIZE);
2316                 device = btrfs_find_device(fs_info, devid, dev_uuid, fs_uuid);
2317                 BUG_ON(!device); /* Logic error */
2318
2319                 if (device->fs_devices->seeding) {
2320                         btrfs_set_device_generation(leaf, dev_item,
2321                                                     device->generation);
2322                         btrfs_mark_buffer_dirty(leaf);
2323                 }
2324
2325                 path->slots[0]++;
2326                 goto next_slot;
2327         }
2328         ret = 0;
2329 error:
2330         btrfs_free_path(path);
2331         return ret;
2332 }
2333
2334 int btrfs_init_new_device(struct btrfs_fs_info *fs_info, const char *device_path)
2335 {
2336         struct btrfs_root *root = fs_info->dev_root;
2337         struct request_queue *q;
2338         struct btrfs_trans_handle *trans;
2339         struct btrfs_device *device;
2340         struct block_device *bdev;
2341         struct super_block *sb = fs_info->sb;
2342         struct rcu_string *name;
2343         struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2344         u64 orig_super_total_bytes;
2345         u64 orig_super_num_devices;
2346         int seeding_dev = 0;
2347         int ret = 0;
2348         bool unlocked = false;
2349
2350         if (sb_rdonly(sb) && !fs_devices->seeding)
2351                 return -EROFS;
2352
2353         bdev = blkdev_get_by_path(device_path, FMODE_WRITE | FMODE_EXCL,
2354                                   fs_info->bdev_holder);
2355         if (IS_ERR(bdev))
2356                 return PTR_ERR(bdev);
2357
2358         if (fs_devices->seeding) {
2359                 seeding_dev = 1;
2360                 down_write(&sb->s_umount);
2361                 mutex_lock(&uuid_mutex);
2362         }
2363
2364         filemap_write_and_wait(bdev->bd_inode->i_mapping);
2365
2366         mutex_lock(&fs_devices->device_list_mutex);
2367         list_for_each_entry(device, &fs_devices->devices, dev_list) {
2368                 if (device->bdev == bdev) {
2369                         ret = -EEXIST;
2370                         mutex_unlock(
2371                                 &fs_devices->device_list_mutex);
2372                         goto error;
2373                 }
2374         }
2375         mutex_unlock(&fs_devices->device_list_mutex);
2376
2377         device = btrfs_alloc_device(fs_info, NULL, NULL);
2378         if (IS_ERR(device)) {
2379                 /* we can safely leave the fs_devices entry around */
2380                 ret = PTR_ERR(device);
2381                 goto error;
2382         }
2383
2384         name = rcu_string_strdup(device_path, GFP_KERNEL);
2385         if (!name) {
2386                 ret = -ENOMEM;
2387                 goto error_free_device;
2388         }
2389         rcu_assign_pointer(device->name, name);
2390
2391         trans = btrfs_start_transaction(root, 0);
2392         if (IS_ERR(trans)) {
2393                 ret = PTR_ERR(trans);
2394                 goto error_free_device;
2395         }
2396
2397         q = bdev_get_queue(bdev);
2398         set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
2399         device->generation = trans->transid;
2400         device->io_width = fs_info->sectorsize;
2401         device->io_align = fs_info->sectorsize;
2402         device->sector_size = fs_info->sectorsize;
2403         device->total_bytes = round_down(i_size_read(bdev->bd_inode),
2404                                          fs_info->sectorsize);
2405         device->disk_total_bytes = device->total_bytes;
2406         device->commit_total_bytes = device->total_bytes;
2407         device->fs_info = fs_info;
2408         device->bdev = bdev;
2409         set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
2410         clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
2411         device->mode = FMODE_EXCL;
2412         device->dev_stats_valid = 1;
2413         set_blocksize(device->bdev, BTRFS_BDEV_BLOCKSIZE);
2414
2415         if (seeding_dev) {
2416                 sb->s_flags &= ~SB_RDONLY;
2417                 ret = btrfs_prepare_sprout(fs_info);
2418                 if (ret) {
2419                         btrfs_abort_transaction(trans, ret);
2420                         goto error_trans;
2421                 }
2422         }
2423
2424         device->fs_devices = fs_devices;
2425
2426         mutex_lock(&fs_devices->device_list_mutex);
2427         mutex_lock(&fs_info->chunk_mutex);
2428         list_add_rcu(&device->dev_list, &fs_devices->devices);
2429         list_add(&device->dev_alloc_list, &fs_devices->alloc_list);
2430         fs_devices->num_devices++;
2431         fs_devices->open_devices++;
2432         fs_devices->rw_devices++;
2433         fs_devices->total_devices++;
2434         fs_devices->total_rw_bytes += device->total_bytes;
2435
2436         atomic64_add(device->total_bytes, &fs_info->free_chunk_space);
2437
2438         if (!blk_queue_nonrot(q))
2439                 fs_devices->rotating = 1;
2440
2441         orig_super_total_bytes = btrfs_super_total_bytes(fs_info->super_copy);
2442         btrfs_set_super_total_bytes(fs_info->super_copy,
2443                 round_down(orig_super_total_bytes + device->total_bytes,
2444                            fs_info->sectorsize));
2445
2446         orig_super_num_devices = btrfs_super_num_devices(fs_info->super_copy);
2447         btrfs_set_super_num_devices(fs_info->super_copy,
2448                                     orig_super_num_devices + 1);
2449
2450         /* add sysfs device entry */
2451         btrfs_sysfs_add_device_link(fs_devices, device);
2452
2453         /*
2454          * we've got more storage, clear any full flags on the space
2455          * infos
2456          */
2457         btrfs_clear_space_info_full(fs_info);
2458
2459         mutex_unlock(&fs_info->chunk_mutex);
2460         mutex_unlock(&fs_devices->device_list_mutex);
2461
2462         if (seeding_dev) {
2463                 mutex_lock(&fs_info->chunk_mutex);
2464                 ret = init_first_rw_device(trans, fs_info);
2465                 mutex_unlock(&fs_info->chunk_mutex);
2466                 if (ret) {
2467                         btrfs_abort_transaction(trans, ret);
2468                         goto error_sysfs;
2469                 }
2470         }
2471
2472         ret = btrfs_add_dev_item(trans, device);
2473         if (ret) {
2474                 btrfs_abort_transaction(trans, ret);
2475                 goto error_sysfs;
2476         }
2477
2478         if (seeding_dev) {
2479                 char fsid_buf[BTRFS_UUID_UNPARSED_SIZE];
2480
2481                 ret = btrfs_finish_sprout(trans, fs_info);
2482                 if (ret) {
2483                         btrfs_abort_transaction(trans, ret);
2484                         goto error_sysfs;
2485                 }
2486
2487                 /* Sprouting would change fsid of the mounted root,
2488                  * so rename the fsid on the sysfs
2489                  */
2490                 snprintf(fsid_buf, BTRFS_UUID_UNPARSED_SIZE, "%pU",
2491                                                 fs_info->fsid);
2492                 if (kobject_rename(&fs_devices->fsid_kobj, fsid_buf))
2493                         btrfs_warn(fs_info,
2494                                    "sysfs: failed to create fsid for sprout");
2495         }
2496
2497         ret = btrfs_commit_transaction(trans);
2498
2499         if (seeding_dev) {
2500                 mutex_unlock(&uuid_mutex);
2501                 up_write(&sb->s_umount);
2502                 unlocked = true;
2503
2504                 if (ret) /* transaction commit */
2505                         return ret;
2506
2507                 ret = btrfs_relocate_sys_chunks(fs_info);
2508                 if (ret < 0)
2509                         btrfs_handle_fs_error(fs_info, ret,
2510                                     "Failed to relocate sys chunks after device initialization. This can be fixed using the \"btrfs balance\" command.");
2511                 trans = btrfs_attach_transaction(root);
2512                 if (IS_ERR(trans)) {
2513                         if (PTR_ERR(trans) == -ENOENT)
2514                                 return 0;
2515                         ret = PTR_ERR(trans);
2516                         trans = NULL;
2517                         goto error_sysfs;
2518                 }
2519                 ret = btrfs_commit_transaction(trans);
2520         }
2521
2522         /* Update ctime/mtime for libblkid */
2523         update_dev_time(device_path);
2524         return ret;
2525
2526 error_sysfs:
2527         btrfs_sysfs_rm_device_link(fs_devices, device);
2528         mutex_lock(&fs_info->fs_devices->device_list_mutex);
2529         mutex_lock(&fs_info->chunk_mutex);
2530         list_del_rcu(&device->dev_list);
2531         list_del(&device->dev_alloc_list);
2532         fs_info->fs_devices->num_devices--;
2533         fs_info->fs_devices->open_devices--;
2534         fs_info->fs_devices->rw_devices--;
2535         fs_info->fs_devices->total_devices--;
2536         fs_info->fs_devices->total_rw_bytes -= device->total_bytes;
2537         atomic64_sub(device->total_bytes, &fs_info->free_chunk_space);
2538         btrfs_set_super_total_bytes(fs_info->super_copy,
2539                                     orig_super_total_bytes);
2540         btrfs_set_super_num_devices(fs_info->super_copy,
2541                                     orig_super_num_devices);
2542         mutex_unlock(&fs_info->chunk_mutex);
2543         mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2544 error_trans:
2545         if (seeding_dev)
2546                 sb->s_flags |= SB_RDONLY;
2547         if (trans)
2548                 btrfs_end_transaction(trans);
2549 error_free_device:
2550         btrfs_free_device(device);
2551 error:
2552         blkdev_put(bdev, FMODE_EXCL);
2553         if (seeding_dev && !unlocked) {
2554                 mutex_unlock(&uuid_mutex);
2555                 up_write(&sb->s_umount);
2556         }
2557         return ret;
2558 }
2559
2560 static noinline int btrfs_update_device(struct btrfs_trans_handle *trans,
2561                                         struct btrfs_device *device)
2562 {
2563         int ret;
2564         struct btrfs_path *path;
2565         struct btrfs_root *root = device->fs_info->chunk_root;
2566         struct btrfs_dev_item *dev_item;
2567         struct extent_buffer *leaf;
2568         struct btrfs_key key;
2569
2570         path = btrfs_alloc_path();
2571         if (!path)
2572                 return -ENOMEM;
2573
2574         key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2575         key.type = BTRFS_DEV_ITEM_KEY;
2576         key.offset = device->devid;
2577
2578         ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2579         if (ret < 0)
2580                 goto out;
2581
2582         if (ret > 0) {
2583                 ret = -ENOENT;
2584                 goto out;
2585         }
2586
2587         leaf = path->nodes[0];
2588         dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
2589
2590         btrfs_set_device_id(leaf, dev_item, device->devid);
2591         btrfs_set_device_type(leaf, dev_item, device->type);
2592         btrfs_set_device_io_align(leaf, dev_item, device->io_align);
2593         btrfs_set_device_io_width(leaf, dev_item, device->io_width);
2594         btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
2595         btrfs_set_device_total_bytes(leaf, dev_item,
2596                                      btrfs_device_get_disk_total_bytes(device));
2597         btrfs_set_device_bytes_used(leaf, dev_item,
2598                                     btrfs_device_get_bytes_used(device));
2599         btrfs_mark_buffer_dirty(leaf);
2600
2601 out:
2602         btrfs_free_path(path);
2603         return ret;
2604 }
2605
2606 int btrfs_grow_device(struct btrfs_trans_handle *trans,
2607                       struct btrfs_device *device, u64 new_size)
2608 {
2609         struct btrfs_fs_info *fs_info = device->fs_info;
2610         struct btrfs_super_block *super_copy = fs_info->super_copy;
2611         struct btrfs_fs_devices *fs_devices;
2612         u64 old_total;
2613         u64 diff;
2614
2615         if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
2616                 return -EACCES;
2617
2618         new_size = round_down(new_size, fs_info->sectorsize);
2619
2620         mutex_lock(&fs_info->chunk_mutex);
2621         old_total = btrfs_super_total_bytes(super_copy);
2622         diff = round_down(new_size - device->total_bytes, fs_info->sectorsize);
2623
2624         if (new_size <= device->total_bytes ||
2625             test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
2626                 mutex_unlock(&fs_info->chunk_mutex);
2627                 return -EINVAL;
2628         }
2629
2630         fs_devices = fs_info->fs_devices;
2631
2632         btrfs_set_super_total_bytes(super_copy,
2633                         round_down(old_total + diff, fs_info->sectorsize));
2634         device->fs_devices->total_rw_bytes += diff;
2635
2636         btrfs_device_set_total_bytes(device, new_size);
2637         btrfs_device_set_disk_total_bytes(device, new_size);
2638         btrfs_clear_space_info_full(device->fs_info);
2639         if (list_empty(&device->resized_list))
2640                 list_add_tail(&device->resized_list,
2641                               &fs_devices->resized_devices);
2642         mutex_unlock(&fs_info->chunk_mutex);
2643
2644         return btrfs_update_device(trans, device);
2645 }
2646
2647 static int btrfs_free_chunk(struct btrfs_trans_handle *trans, u64 chunk_offset)
2648 {
2649         struct btrfs_fs_info *fs_info = trans->fs_info;
2650         struct btrfs_root *root = fs_info->chunk_root;
2651         int ret;
2652         struct btrfs_path *path;
2653         struct btrfs_key key;
2654
2655         path = btrfs_alloc_path();
2656         if (!path)
2657                 return -ENOMEM;
2658
2659         key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2660         key.offset = chunk_offset;
2661         key.type = BTRFS_CHUNK_ITEM_KEY;
2662
2663         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
2664         if (ret < 0)
2665                 goto out;
2666         else if (ret > 0) { /* Logic error or corruption */
2667                 btrfs_handle_fs_error(fs_info, -ENOENT,
2668                                       "Failed lookup while freeing chunk.");
2669                 ret = -ENOENT;
2670                 goto out;
2671         }
2672
2673         ret = btrfs_del_item(trans, root, path);
2674         if (ret < 0)
2675                 btrfs_handle_fs_error(fs_info, ret,
2676                                       "Failed to delete chunk item.");
2677 out:
2678         btrfs_free_path(path);
2679         return ret;
2680 }
2681
2682 static int btrfs_del_sys_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
2683 {
2684         struct btrfs_super_block *super_copy = fs_info->super_copy;
2685         struct btrfs_disk_key *disk_key;
2686         struct btrfs_chunk *chunk;
2687         u8 *ptr;
2688         int ret = 0;
2689         u32 num_stripes;
2690         u32 array_size;
2691         u32 len = 0;
2692         u32 cur;
2693         struct btrfs_key key;
2694
2695         mutex_lock(&fs_info->chunk_mutex);
2696         array_size = btrfs_super_sys_array_size(super_copy);
2697
2698         ptr = super_copy->sys_chunk_array;
2699         cur = 0;
2700
2701         while (cur < array_size) {
2702                 disk_key = (struct btrfs_disk_key *)ptr;
2703                 btrfs_disk_key_to_cpu(&key, disk_key);
2704
2705                 len = sizeof(*disk_key);
2706
2707                 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
2708                         chunk = (struct btrfs_chunk *)(ptr + len);
2709                         num_stripes = btrfs_stack_chunk_num_stripes(chunk);
2710                         len += btrfs_chunk_item_size(num_stripes);
2711                 } else {
2712                         ret = -EIO;
2713                         break;
2714                 }
2715                 if (key.objectid == BTRFS_FIRST_CHUNK_TREE_OBJECTID &&
2716                     key.offset == chunk_offset) {
2717                         memmove(ptr, ptr + len, array_size - (cur + len));
2718                         array_size -= len;
2719                         btrfs_set_super_sys_array_size(super_copy, array_size);
2720                 } else {
2721                         ptr += len;
2722                         cur += len;
2723                 }
2724         }
2725         mutex_unlock(&fs_info->chunk_mutex);
2726         return ret;
2727 }
2728
2729 /*
2730  * btrfs_get_chunk_map() - Find the mapping containing the given logical extent.
2731  * @logical: Logical block offset in bytes.
2732  * @length: Length of extent in bytes.
2733  *
2734  * Return: Chunk mapping or ERR_PTR.
2735  */
2736 struct extent_map *btrfs_get_chunk_map(struct btrfs_fs_info *fs_info,
2737                                        u64 logical, u64 length)
2738 {
2739         struct extent_map_tree *em_tree;
2740         struct extent_map *em;
2741
2742         em_tree = &fs_info->mapping_tree.map_tree;
2743         read_lock(&em_tree->lock);
2744         em = lookup_extent_mapping(em_tree, logical, length);
2745         read_unlock(&em_tree->lock);
2746
2747         if (!em) {
2748                 btrfs_crit(fs_info, "unable to find logical %llu length %llu",
2749                            logical, length);
2750                 return ERR_PTR(-EINVAL);
2751         }
2752
2753         if (em->start > logical || em->start + em->len < logical) {
2754                 btrfs_crit(fs_info,
2755                            "found a bad mapping, wanted %llu-%llu, found %llu-%llu",
2756                            logical, length, em->start, em->start + em->len);
2757                 free_extent_map(em);
2758                 return ERR_PTR(-EINVAL);
2759         }
2760
2761         /* callers are responsible for dropping em's ref. */
2762         return em;
2763 }
2764
2765 int btrfs_remove_chunk(struct btrfs_trans_handle *trans, u64 chunk_offset)
2766 {
2767         struct btrfs_fs_info *fs_info = trans->fs_info;
2768         struct extent_map *em;
2769         struct map_lookup *map;
2770         u64 dev_extent_len = 0;
2771         int i, ret = 0;
2772         struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2773
2774         em = btrfs_get_chunk_map(fs_info, chunk_offset, 1);
2775         if (IS_ERR(em)) {
2776                 /*
2777                  * This is a logic error, but we don't want to just rely on the
2778                  * user having built with ASSERT enabled, so if ASSERT doesn't
2779                  * do anything we still error out.
2780                  */
2781                 ASSERT(0);
2782                 return PTR_ERR(em);
2783         }
2784         map = em->map_lookup;
2785         mutex_lock(&fs_info->chunk_mutex);
2786         check_system_chunk(trans, map->type);
2787         mutex_unlock(&fs_info->chunk_mutex);
2788
2789         /*
2790          * Take the device list mutex to prevent races with the final phase of
2791          * a device replace operation that replaces the device object associated
2792          * with map stripes (dev-replace.c:btrfs_dev_replace_finishing()).
2793          */
2794         mutex_lock(&fs_devices->device_list_mutex);
2795         for (i = 0; i < map->num_stripes; i++) {
2796                 struct btrfs_device *device = map->stripes[i].dev;
2797                 ret = btrfs_free_dev_extent(trans, device,
2798                                             map->stripes[i].physical,
2799                                             &dev_extent_len);
2800                 if (ret) {
2801                         mutex_unlock(&fs_devices->device_list_mutex);
2802                         btrfs_abort_transaction(trans, ret);
2803                         goto out;
2804                 }
2805
2806                 if (device->bytes_used > 0) {
2807                         mutex_lock(&fs_info->chunk_mutex);
2808                         btrfs_device_set_bytes_used(device,
2809                                         device->bytes_used - dev_extent_len);
2810                         atomic64_add(dev_extent_len, &fs_info->free_chunk_space);
2811                         btrfs_clear_space_info_full(fs_info);
2812                         mutex_unlock(&fs_info->chunk_mutex);
2813                 }
2814
2815                 if (map->stripes[i].dev) {
2816                         ret = btrfs_update_device(trans, map->stripes[i].dev);
2817                         if (ret) {
2818                                 mutex_unlock(&fs_devices->device_list_mutex);
2819                                 btrfs_abort_transaction(trans, ret);
2820                                 goto out;
2821                         }
2822                 }
2823         }
2824         mutex_unlock(&fs_devices->device_list_mutex);
2825
2826         ret = btrfs_free_chunk(trans, chunk_offset);
2827         if (ret) {
2828                 btrfs_abort_transaction(trans, ret);
2829                 goto out;
2830         }
2831
2832         trace_btrfs_chunk_free(fs_info, map, chunk_offset, em->len);
2833
2834         if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
2835                 ret = btrfs_del_sys_chunk(fs_info, chunk_offset);
2836                 if (ret) {
2837                         btrfs_abort_transaction(trans, ret);
2838                         goto out;
2839                 }
2840         }
2841
2842         ret = btrfs_remove_block_group(trans, chunk_offset, em);
2843         if (ret) {
2844                 btrfs_abort_transaction(trans, ret);
2845                 goto out;
2846         }
2847
2848 out:
2849         /* once for us */
2850         free_extent_map(em);
2851         return ret;
2852 }
2853
2854 static int btrfs_relocate_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
2855 {
2856         struct btrfs_root *root = fs_info->chunk_root;
2857         struct btrfs_trans_handle *trans;
2858         int ret;
2859
2860         /*
2861          * Prevent races with automatic removal of unused block groups.
2862          * After we relocate and before we remove the chunk with offset
2863          * chunk_offset, automatic removal of the block group can kick in,
2864          * resulting in a failure when calling btrfs_remove_chunk() below.
2865          *
2866          * Make sure to acquire this mutex before doing a tree search (dev
2867          * or chunk trees) to find chunks. Otherwise the cleaner kthread might
2868          * call btrfs_remove_chunk() (through btrfs_delete_unused_bgs()) after
2869          * we release the path used to search the chunk/dev tree and before
2870          * the current task acquires this mutex and calls us.
2871          */
2872         lockdep_assert_held(&fs_info->delete_unused_bgs_mutex);
2873
2874         ret = btrfs_can_relocate(fs_info, chunk_offset);
2875         if (ret)
2876                 return -ENOSPC;
2877
2878         /* step one, relocate all the extents inside this chunk */
2879         btrfs_scrub_pause(fs_info);
2880         ret = btrfs_relocate_block_group(fs_info, chunk_offset);
2881         btrfs_scrub_continue(fs_info);
2882         if (ret)
2883                 return ret;
2884
2885         /*
2886          * We add the kobjects here (and after forcing data chunk creation)
2887          * since relocation is the only place we'll create chunks of a new
2888          * type at runtime.  The only place where we'll remove the last
2889          * chunk of a type is the call immediately below this one.  Even
2890          * so, we're protected against races with the cleaner thread since
2891          * we're covered by the delete_unused_bgs_mutex.
2892          */
2893         btrfs_add_raid_kobjects(fs_info);
2894
2895         trans = btrfs_start_trans_remove_block_group(root->fs_info,
2896                                                      chunk_offset);
2897         if (IS_ERR(trans)) {
2898                 ret = PTR_ERR(trans);
2899                 btrfs_handle_fs_error(root->fs_info, ret, NULL);
2900                 return ret;
2901         }
2902
2903         /*
2904          * step two, delete the device extents and the
2905          * chunk tree entries
2906          */
2907         ret = btrfs_remove_chunk(trans, chunk_offset);
2908         btrfs_end_transaction(trans);
2909         return ret;
2910 }
2911
2912 static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info)
2913 {
2914         struct btrfs_root *chunk_root = fs_info->chunk_root;
2915         struct btrfs_path *path;
2916         struct extent_buffer *leaf;
2917         struct btrfs_chunk *chunk;
2918         struct btrfs_key key;
2919         struct btrfs_key found_key;
2920         u64 chunk_type;
2921         bool retried = false;
2922         int failed = 0;
2923         int ret;
2924
2925         path = btrfs_alloc_path();
2926         if (!path)
2927                 return -ENOMEM;
2928
2929 again:
2930         key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2931         key.offset = (u64)-1;
2932         key.type = BTRFS_CHUNK_ITEM_KEY;
2933
2934         while (1) {
2935                 mutex_lock(&fs_info->delete_unused_bgs_mutex);
2936                 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
2937                 if (ret < 0) {
2938                         mutex_unlock(&fs_info->delete_unused_bgs_mutex);
2939                         goto error;
2940                 }
2941                 BUG_ON(ret == 0); /* Corruption */
2942
2943                 ret = btrfs_previous_item(chunk_root, path, key.objectid,
2944                                           key.type);
2945                 if (ret)
2946                         mutex_unlock(&fs_info->delete_unused_bgs_mutex);
2947                 if (ret < 0)
2948                         goto error;
2949                 if (ret > 0)
2950                         break;
2951
2952                 leaf = path->nodes[0];
2953                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2954
2955                 chunk = btrfs_item_ptr(leaf, path->slots[0],
2956                                        struct btrfs_chunk);
2957                 chunk_type = btrfs_chunk_type(leaf, chunk);
2958                 btrfs_release_path(path);
2959
2960                 if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) {
2961                         ret = btrfs_relocate_chunk(fs_info, found_key.offset);
2962                         if (ret == -ENOSPC)
2963                                 failed++;
2964                         else
2965                                 BUG_ON(ret);
2966                 }
2967                 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
2968
2969                 if (found_key.offset == 0)
2970                         break;
2971                 key.offset = found_key.offset - 1;
2972         }
2973         ret = 0;
2974         if (failed && !retried) {
2975                 failed = 0;
2976                 retried = true;
2977                 goto again;
2978         } else if (WARN_ON(failed && retried)) {
2979                 ret = -ENOSPC;
2980         }
2981 error:
2982         btrfs_free_path(path);
2983         return ret;
2984 }
2985
2986 /*
2987  * return 1 : allocate a data chunk successfully,
2988  * return <0: errors during allocating a data chunk,
2989  * return 0 : no need to allocate a data chunk.
2990  */
2991 static int btrfs_may_alloc_data_chunk(struct btrfs_fs_info *fs_info,
2992                                       u64 chunk_offset)
2993 {
2994         struct btrfs_block_group_cache *cache;
2995         u64 bytes_used;
2996         u64 chunk_type;
2997
2998         cache = btrfs_lookup_block_group(fs_info, chunk_offset);
2999         ASSERT(cache);
3000         chunk_type = cache->flags;
3001         btrfs_put_block_group(cache);
3002
3003         if (chunk_type & BTRFS_BLOCK_GROUP_DATA) {
3004                 spin_lock(&fs_info->data_sinfo->lock);
3005                 bytes_used = fs_info->data_sinfo->bytes_used;
3006                 spin_unlock(&fs_info->data_sinfo->lock);
3007
3008                 if (!bytes_used) {
3009                         struct btrfs_trans_handle *trans;
3010                         int ret;
3011
3012                         trans = btrfs_join_transaction(fs_info->tree_root);
3013                         if (IS_ERR(trans))
3014                                 return PTR_ERR(trans);
3015
3016                         ret = btrfs_force_chunk_alloc(trans,
3017                                                       BTRFS_BLOCK_GROUP_DATA);
3018                         btrfs_end_transaction(trans);
3019                         if (ret < 0)
3020                                 return ret;
3021
3022                         btrfs_add_raid_kobjects(fs_info);
3023
3024                         return 1;
3025                 }
3026         }
3027         return 0;
3028 }
3029
3030 static int insert_balance_item(struct btrfs_fs_info *fs_info,
3031                                struct btrfs_balance_control *bctl)
3032 {
3033         struct btrfs_root *root = fs_info->tree_root;
3034         struct btrfs_trans_handle *trans;
3035         struct btrfs_balance_item *item;
3036         struct btrfs_disk_balance_args disk_bargs;
3037         struct btrfs_path *path;
3038         struct extent_buffer *leaf;
3039         struct btrfs_key key;
3040         int ret, err;
3041
3042         path = btrfs_alloc_path();
3043         if (!path)
3044                 return -ENOMEM;
3045
3046         trans = btrfs_start_transaction(root, 0);
3047         if (IS_ERR(trans)) {
3048                 btrfs_free_path(path);
3049                 return PTR_ERR(trans);
3050         }
3051
3052         key.objectid = BTRFS_BALANCE_OBJECTID;
3053         key.type = BTRFS_TEMPORARY_ITEM_KEY;
3054         key.offset = 0;
3055
3056         ret = btrfs_insert_empty_item(trans, root, path, &key,
3057                                       sizeof(*item));
3058         if (ret)
3059                 goto out;
3060
3061         leaf = path->nodes[0];
3062         item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
3063
3064         memzero_extent_buffer(leaf, (unsigned long)item, sizeof(*item));
3065
3066         btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->data);
3067         btrfs_set_balance_data(leaf, item, &disk_bargs);
3068         btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->meta);
3069         btrfs_set_balance_meta(leaf, item, &disk_bargs);
3070         btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->sys);
3071         btrfs_set_balance_sys(leaf, item, &disk_bargs);
3072
3073         btrfs_set_balance_flags(leaf, item, bctl->flags);
3074
3075         btrfs_mark_buffer_dirty(leaf);
3076 out:
3077         btrfs_free_path(path);
3078         err = btrfs_commit_transaction(trans);
3079         if (err && !ret)
3080                 ret = err;
3081         return ret;
3082 }
3083
3084 static int del_balance_item(struct btrfs_fs_info *fs_info)
3085 {
3086         struct btrfs_root *root = fs_info->tree_root;
3087         struct btrfs_trans_handle *trans;
3088         struct btrfs_path *path;
3089         struct btrfs_key key;
3090         int ret, err;
3091
3092         path = btrfs_alloc_path();
3093         if (!path)
3094                 return -ENOMEM;
3095
3096         trans = btrfs_start_transaction(root, 0);
3097         if (IS_ERR(trans)) {
3098                 btrfs_free_path(path);
3099                 return PTR_ERR(trans);
3100         }
3101
3102         key.objectid = BTRFS_BALANCE_OBJECTID;
3103         key.type = BTRFS_TEMPORARY_ITEM_KEY;
3104         key.offset = 0;
3105
3106         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3107         if (ret < 0)
3108                 goto out;
3109         if (ret > 0) {
3110                 ret = -ENOENT;
3111                 goto out;
3112         }
3113
3114         ret = btrfs_del_item(trans, root, path);
3115 out:
3116         btrfs_free_path(path);
3117         err = btrfs_commit_transaction(trans);
3118         if (err && !ret)
3119                 ret = err;
3120         return ret;
3121 }
3122
3123 /*
3124  * This is a heuristic used to reduce the number of chunks balanced on
3125  * resume after balance was interrupted.
3126  */
3127 static void update_balance_args(struct btrfs_balance_control *bctl)
3128 {
3129         /*
3130          * Turn on soft mode for chunk types that were being converted.
3131          */
3132         if (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)
3133                 bctl->data.flags |= BTRFS_BALANCE_ARGS_SOFT;
3134         if (bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)
3135                 bctl->sys.flags |= BTRFS_BALANCE_ARGS_SOFT;
3136         if (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)
3137                 bctl->meta.flags |= BTRFS_BALANCE_ARGS_SOFT;
3138
3139         /*
3140          * Turn on usage filter if is not already used.  The idea is
3141          * that chunks that we have already balanced should be
3142          * reasonably full.  Don't do it for chunks that are being
3143          * converted - that will keep us from relocating unconverted
3144          * (albeit full) chunks.
3145          */
3146         if (!(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3147             !(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3148             !(bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3149                 bctl->data.flags |= BTRFS_BALANCE_ARGS_USAGE;
3150                 bctl->data.usage = 90;
3151         }
3152         if (!(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3153             !(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3154             !(bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3155                 bctl->sys.flags |= BTRFS_BALANCE_ARGS_USAGE;
3156                 bctl->sys.usage = 90;
3157         }
3158         if (!(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3159             !(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3160             !(bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3161                 bctl->meta.flags |= BTRFS_BALANCE_ARGS_USAGE;
3162                 bctl->meta.usage = 90;
3163         }
3164 }
3165
3166 /*
3167  * Clear the balance status in fs_info and delete the balance item from disk.
3168  */
3169 static void reset_balance_state(struct btrfs_fs_info *fs_info)
3170 {
3171         struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3172         int ret;
3173
3174         BUG_ON(!fs_info->balance_ctl);
3175
3176         spin_lock(&fs_info->balance_lock);
3177         fs_info->balance_ctl = NULL;
3178         spin_unlock(&fs_info->balance_lock);
3179
3180         kfree(bctl);
3181         ret = del_balance_item(fs_info);
3182         if (ret)
3183                 btrfs_handle_fs_error(fs_info, ret, NULL);
3184 }
3185
3186 /*
3187  * Balance filters.  Return 1 if chunk should be filtered out
3188  * (should not be balanced).
3189  */
3190 static int chunk_profiles_filter(u64 chunk_type,
3191                                  struct btrfs_balance_args *bargs)
3192 {
3193         chunk_type = chunk_to_extended(chunk_type) &
3194                                 BTRFS_EXTENDED_PROFILE_MASK;
3195
3196         if (bargs->profiles & chunk_type)
3197                 return 0;
3198
3199         return 1;
3200 }
3201
3202 static int chunk_usage_range_filter(struct btrfs_fs_info *fs_info, u64 chunk_offset,
3203                               struct btrfs_balance_args *bargs)
3204 {
3205         struct btrfs_block_group_cache *cache;
3206         u64 chunk_used;
3207         u64 user_thresh_min;
3208         u64 user_thresh_max;
3209         int ret = 1;
3210
3211         cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3212         chunk_used = btrfs_block_group_used(&cache->item);
3213
3214         if (bargs->usage_min == 0)
3215                 user_thresh_min = 0;
3216         else
3217                 user_thresh_min = div_factor_fine(cache->key.offset,
3218                                         bargs->usage_min);
3219
3220         if (bargs->usage_max == 0)
3221                 user_thresh_max = 1;
3222         else if (bargs->usage_max > 100)
3223                 user_thresh_max = cache->key.offset;
3224         else
3225                 user_thresh_max = div_factor_fine(cache->key.offset,
3226                                         bargs->usage_max);
3227
3228         if (user_thresh_min <= chunk_used && chunk_used < user_thresh_max)
3229                 ret = 0;
3230
3231         btrfs_put_block_group(cache);
3232         return ret;
3233 }
3234
3235 static int chunk_usage_filter(struct btrfs_fs_info *fs_info,
3236                 u64 chunk_offset, struct btrfs_balance_args *bargs)
3237 {
3238         struct btrfs_block_group_cache *cache;
3239         u64 chunk_used, user_thresh;
3240         int ret = 1;
3241
3242         cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3243         chunk_used = btrfs_block_group_used(&cache->item);
3244
3245         if (bargs->usage_min == 0)
3246                 user_thresh = 1;
3247         else if (bargs->usage > 100)
3248                 user_thresh = cache->key.offset;
3249         else
3250                 user_thresh = div_factor_fine(cache->key.offset,
3251                                               bargs->usage);
3252
3253         if (chunk_used < user_thresh)
3254                 ret = 0;
3255
3256         btrfs_put_block_group(cac