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