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