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