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