btrfs: enhance btrfs_find_device_by_user_input() to check device path
[cascardo/linux.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 const struct btrfs_raid_attr btrfs_raid_array[BTRFS_NR_RAID_TYPES] = {
46         [BTRFS_RAID_RAID10] = {
47                 .sub_stripes    = 2,
48                 .dev_stripes    = 1,
49                 .devs_max       = 0,    /* 0 == as many as possible */
50                 .devs_min       = 4,
51                 .tolerated_failures = 1,
52                 .devs_increment = 2,
53                 .ncopies        = 2,
54         },
55         [BTRFS_RAID_RAID1] = {
56                 .sub_stripes    = 1,
57                 .dev_stripes    = 1,
58                 .devs_max       = 2,
59                 .devs_min       = 2,
60                 .tolerated_failures = 1,
61                 .devs_increment = 2,
62                 .ncopies        = 2,
63         },
64         [BTRFS_RAID_DUP] = {
65                 .sub_stripes    = 1,
66                 .dev_stripes    = 2,
67                 .devs_max       = 1,
68                 .devs_min       = 1,
69                 .tolerated_failures = 0,
70                 .devs_increment = 1,
71                 .ncopies        = 2,
72         },
73         [BTRFS_RAID_RAID0] = {
74                 .sub_stripes    = 1,
75                 .dev_stripes    = 1,
76                 .devs_max       = 0,
77                 .devs_min       = 2,
78                 .tolerated_failures = 0,
79                 .devs_increment = 1,
80                 .ncopies        = 1,
81         },
82         [BTRFS_RAID_SINGLE] = {
83                 .sub_stripes    = 1,
84                 .dev_stripes    = 1,
85                 .devs_max       = 1,
86                 .devs_min       = 1,
87                 .tolerated_failures = 0,
88                 .devs_increment = 1,
89                 .ncopies        = 1,
90         },
91         [BTRFS_RAID_RAID5] = {
92                 .sub_stripes    = 1,
93                 .dev_stripes    = 1,
94                 .devs_max       = 0,
95                 .devs_min       = 2,
96                 .tolerated_failures = 1,
97                 .devs_increment = 1,
98                 .ncopies        = 2,
99         },
100         [BTRFS_RAID_RAID6] = {
101                 .sub_stripes    = 1,
102                 .dev_stripes    = 1,
103                 .devs_max       = 0,
104                 .devs_min       = 3,
105                 .tolerated_failures = 2,
106                 .devs_increment = 1,
107                 .ncopies        = 3,
108         },
109 };
110
111 const u64 btrfs_raid_group[BTRFS_NR_RAID_TYPES] = {
112         [BTRFS_RAID_RAID10] = BTRFS_BLOCK_GROUP_RAID10,
113         [BTRFS_RAID_RAID1]  = BTRFS_BLOCK_GROUP_RAID1,
114         [BTRFS_RAID_DUP]    = BTRFS_BLOCK_GROUP_DUP,
115         [BTRFS_RAID_RAID0]  = BTRFS_BLOCK_GROUP_RAID0,
116         [BTRFS_RAID_SINGLE] = 0,
117         [BTRFS_RAID_RAID5]  = BTRFS_BLOCK_GROUP_RAID5,
118         [BTRFS_RAID_RAID6]  = BTRFS_BLOCK_GROUP_RAID6,
119 };
120
121 static int init_first_rw_device(struct btrfs_trans_handle *trans,
122                                 struct btrfs_root *root,
123                                 struct btrfs_device *device);
124 static int btrfs_relocate_sys_chunks(struct btrfs_root *root);
125 static void __btrfs_reset_dev_stats(struct btrfs_device *dev);
126 static void btrfs_dev_stat_print_on_error(struct btrfs_device *dev);
127 static void btrfs_dev_stat_print_on_load(struct btrfs_device *device);
128 static void btrfs_close_one_device(struct btrfs_device *device);
129
130 DEFINE_MUTEX(uuid_mutex);
131 static LIST_HEAD(fs_uuids);
132 struct list_head *btrfs_get_fs_uuids(void)
133 {
134         return &fs_uuids;
135 }
136
137 static struct btrfs_fs_devices *__alloc_fs_devices(void)
138 {
139         struct btrfs_fs_devices *fs_devs;
140
141         fs_devs = kzalloc(sizeof(*fs_devs), GFP_KERNEL);
142         if (!fs_devs)
143                 return ERR_PTR(-ENOMEM);
144
145         mutex_init(&fs_devs->device_list_mutex);
146
147         INIT_LIST_HEAD(&fs_devs->devices);
148         INIT_LIST_HEAD(&fs_devs->resized_devices);
149         INIT_LIST_HEAD(&fs_devs->alloc_list);
150         INIT_LIST_HEAD(&fs_devs->list);
151
152         return fs_devs;
153 }
154
155 /**
156  * alloc_fs_devices - allocate struct btrfs_fs_devices
157  * @fsid:       a pointer to UUID for this FS.  If NULL a new UUID is
158  *              generated.
159  *
160  * Return: a pointer to a new &struct btrfs_fs_devices on success;
161  * ERR_PTR() on error.  Returned struct is not linked onto any lists and
162  * can be destroyed with kfree() right away.
163  */
164 static struct btrfs_fs_devices *alloc_fs_devices(const u8 *fsid)
165 {
166         struct btrfs_fs_devices *fs_devs;
167
168         fs_devs = __alloc_fs_devices();
169         if (IS_ERR(fs_devs))
170                 return fs_devs;
171
172         if (fsid)
173                 memcpy(fs_devs->fsid, fsid, BTRFS_FSID_SIZE);
174         else
175                 generate_random_uuid(fs_devs->fsid);
176
177         return fs_devs;
178 }
179
180 static void free_fs_devices(struct btrfs_fs_devices *fs_devices)
181 {
182         struct btrfs_device *device;
183         WARN_ON(fs_devices->opened);
184         while (!list_empty(&fs_devices->devices)) {
185                 device = list_entry(fs_devices->devices.next,
186                                     struct btrfs_device, dev_list);
187                 list_del(&device->dev_list);
188                 rcu_string_free(device->name);
189                 kfree(device);
190         }
191         kfree(fs_devices);
192 }
193
194 static void btrfs_kobject_uevent(struct block_device *bdev,
195                                  enum kobject_action action)
196 {
197         int ret;
198
199         ret = kobject_uevent(&disk_to_dev(bdev->bd_disk)->kobj, action);
200         if (ret)
201                 pr_warn("BTRFS: Sending event '%d' to kobject: '%s' (%p): failed\n",
202                         action,
203                         kobject_name(&disk_to_dev(bdev->bd_disk)->kobj),
204                         &disk_to_dev(bdev->bd_disk)->kobj);
205 }
206
207 void btrfs_cleanup_fs_uuids(void)
208 {
209         struct btrfs_fs_devices *fs_devices;
210
211         while (!list_empty(&fs_uuids)) {
212                 fs_devices = list_entry(fs_uuids.next,
213                                         struct btrfs_fs_devices, list);
214                 list_del(&fs_devices->list);
215                 free_fs_devices(fs_devices);
216         }
217 }
218
219 static struct btrfs_device *__alloc_device(void)
220 {
221         struct btrfs_device *dev;
222
223         dev = kzalloc(sizeof(*dev), GFP_KERNEL);
224         if (!dev)
225                 return ERR_PTR(-ENOMEM);
226
227         INIT_LIST_HEAD(&dev->dev_list);
228         INIT_LIST_HEAD(&dev->dev_alloc_list);
229         INIT_LIST_HEAD(&dev->resized_list);
230
231         spin_lock_init(&dev->io_lock);
232
233         spin_lock_init(&dev->reada_lock);
234         atomic_set(&dev->reada_in_flight, 0);
235         atomic_set(&dev->dev_stats_ccnt, 0);
236         btrfs_device_data_ordered_init(dev);
237         INIT_RADIX_TREE(&dev->reada_zones, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
238         INIT_RADIX_TREE(&dev->reada_extents, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
239
240         return dev;
241 }
242
243 static noinline struct btrfs_device *__find_device(struct list_head *head,
244                                                    u64 devid, u8 *uuid)
245 {
246         struct btrfs_device *dev;
247
248         list_for_each_entry(dev, head, dev_list) {
249                 if (dev->devid == devid &&
250                     (!uuid || !memcmp(dev->uuid, uuid, BTRFS_UUID_SIZE))) {
251                         return dev;
252                 }
253         }
254         return NULL;
255 }
256
257 static noinline struct btrfs_fs_devices *find_fsid(u8 *fsid)
258 {
259         struct btrfs_fs_devices *fs_devices;
260
261         list_for_each_entry(fs_devices, &fs_uuids, list) {
262                 if (memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE) == 0)
263                         return fs_devices;
264         }
265         return NULL;
266 }
267
268 static int
269 btrfs_get_bdev_and_sb(const char *device_path, fmode_t flags, void *holder,
270                       int flush, struct block_device **bdev,
271                       struct buffer_head **bh)
272 {
273         int ret;
274
275         *bdev = blkdev_get_by_path(device_path, flags, holder);
276
277         if (IS_ERR(*bdev)) {
278                 ret = PTR_ERR(*bdev);
279                 goto error;
280         }
281
282         if (flush)
283                 filemap_write_and_wait((*bdev)->bd_inode->i_mapping);
284         ret = set_blocksize(*bdev, 4096);
285         if (ret) {
286                 blkdev_put(*bdev, flags);
287                 goto error;
288         }
289         invalidate_bdev(*bdev);
290         *bh = btrfs_read_dev_super(*bdev);
291         if (IS_ERR(*bh)) {
292                 ret = PTR_ERR(*bh);
293                 blkdev_put(*bdev, flags);
294                 goto error;
295         }
296
297         return 0;
298
299 error:
300         *bdev = NULL;
301         *bh = NULL;
302         return ret;
303 }
304
305 static void requeue_list(struct btrfs_pending_bios *pending_bios,
306                         struct bio *head, struct bio *tail)
307 {
308
309         struct bio *old_head;
310
311         old_head = pending_bios->head;
312         pending_bios->head = head;
313         if (pending_bios->tail)
314                 tail->bi_next = old_head;
315         else
316                 pending_bios->tail = tail;
317 }
318
319 /*
320  * we try to collect pending bios for a device so we don't get a large
321  * number of procs sending bios down to the same device.  This greatly
322  * improves the schedulers ability to collect and merge the bios.
323  *
324  * But, it also turns into a long list of bios to process and that is sure
325  * to eventually make the worker thread block.  The solution here is to
326  * make some progress and then put this work struct back at the end of
327  * the list if the block device is congested.  This way, multiple devices
328  * can make progress from a single worker thread.
329  */
330 static noinline void run_scheduled_bios(struct btrfs_device *device)
331 {
332         struct bio *pending;
333         struct backing_dev_info *bdi;
334         struct btrfs_fs_info *fs_info;
335         struct btrfs_pending_bios *pending_bios;
336         struct bio *tail;
337         struct bio *cur;
338         int again = 0;
339         unsigned long num_run;
340         unsigned long batch_run = 0;
341         unsigned long limit;
342         unsigned long last_waited = 0;
343         int force_reg = 0;
344         int sync_pending = 0;
345         struct blk_plug plug;
346
347         /*
348          * this function runs all the bios we've collected for
349          * a particular device.  We don't want to wander off to
350          * another device without first sending all of these down.
351          * So, setup a plug here and finish it off before we return
352          */
353         blk_start_plug(&plug);
354
355         bdi = blk_get_backing_dev_info(device->bdev);
356         fs_info = device->dev_root->fs_info;
357         limit = btrfs_async_submit_limit(fs_info);
358         limit = limit * 2 / 3;
359
360 loop:
361         spin_lock(&device->io_lock);
362
363 loop_lock:
364         num_run = 0;
365
366         /* take all the bios off the list at once and process them
367          * later on (without the lock held).  But, remember the
368          * tail and other pointers so the bios can be properly reinserted
369          * into the list if we hit congestion
370          */
371         if (!force_reg && device->pending_sync_bios.head) {
372                 pending_bios = &device->pending_sync_bios;
373                 force_reg = 1;
374         } else {
375                 pending_bios = &device->pending_bios;
376                 force_reg = 0;
377         }
378
379         pending = pending_bios->head;
380         tail = pending_bios->tail;
381         WARN_ON(pending && !tail);
382
383         /*
384          * if pending was null this time around, no bios need processing
385          * at all and we can stop.  Otherwise it'll loop back up again
386          * and do an additional check so no bios are missed.
387          *
388          * device->running_pending is used to synchronize with the
389          * schedule_bio code.
390          */
391         if (device->pending_sync_bios.head == NULL &&
392             device->pending_bios.head == NULL) {
393                 again = 0;
394                 device->running_pending = 0;
395         } else {
396                 again = 1;
397                 device->running_pending = 1;
398         }
399
400         pending_bios->head = NULL;
401         pending_bios->tail = NULL;
402
403         spin_unlock(&device->io_lock);
404
405         while (pending) {
406
407                 rmb();
408                 /* we want to work on both lists, but do more bios on the
409                  * sync list than the regular list
410                  */
411                 if ((num_run > 32 &&
412                     pending_bios != &device->pending_sync_bios &&
413                     device->pending_sync_bios.head) ||
414                    (num_run > 64 && pending_bios == &device->pending_sync_bios &&
415                     device->pending_bios.head)) {
416                         spin_lock(&device->io_lock);
417                         requeue_list(pending_bios, pending, tail);
418                         goto loop_lock;
419                 }
420
421                 cur = pending;
422                 pending = pending->bi_next;
423                 cur->bi_next = NULL;
424
425                 /*
426                  * atomic_dec_return implies a barrier for waitqueue_active
427                  */
428                 if (atomic_dec_return(&fs_info->nr_async_bios) < limit &&
429                     waitqueue_active(&fs_info->async_submit_wait))
430                         wake_up(&fs_info->async_submit_wait);
431
432                 BUG_ON(atomic_read(&cur->__bi_cnt) == 0);
433
434                 /*
435                  * if we're doing the sync list, record that our
436                  * plug has some sync requests on it
437                  *
438                  * If we're doing the regular list and there are
439                  * sync requests sitting around, unplug before
440                  * we add more
441                  */
442                 if (pending_bios == &device->pending_sync_bios) {
443                         sync_pending = 1;
444                 } else if (sync_pending) {
445                         blk_finish_plug(&plug);
446                         blk_start_plug(&plug);
447                         sync_pending = 0;
448                 }
449
450                 btrfsic_submit_bio(cur->bi_rw, cur);
451                 num_run++;
452                 batch_run++;
453
454                 cond_resched();
455
456                 /*
457                  * we made progress, there is more work to do and the bdi
458                  * is now congested.  Back off and let other work structs
459                  * run instead
460                  */
461                 if (pending && bdi_write_congested(bdi) && batch_run > 8 &&
462                     fs_info->fs_devices->open_devices > 1) {
463                         struct io_context *ioc;
464
465                         ioc = current->io_context;
466
467                         /*
468                          * the main goal here is that we don't want to
469                          * block if we're going to be able to submit
470                          * more requests without blocking.
471                          *
472                          * This code does two great things, it pokes into
473                          * the elevator code from a filesystem _and_
474                          * it makes assumptions about how batching works.
475                          */
476                         if (ioc && ioc->nr_batch_requests > 0 &&
477                             time_before(jiffies, ioc->last_waited + HZ/50UL) &&
478                             (last_waited == 0 ||
479                              ioc->last_waited == last_waited)) {
480                                 /*
481                                  * we want to go through our batch of
482                                  * requests and stop.  So, we copy out
483                                  * the ioc->last_waited time and test
484                                  * against it before looping
485                                  */
486                                 last_waited = ioc->last_waited;
487                                 cond_resched();
488                                 continue;
489                         }
490                         spin_lock(&device->io_lock);
491                         requeue_list(pending_bios, pending, tail);
492                         device->running_pending = 1;
493
494                         spin_unlock(&device->io_lock);
495                         btrfs_queue_work(fs_info->submit_workers,
496                                          &device->work);
497                         goto done;
498                 }
499                 /* unplug every 64 requests just for good measure */
500                 if (batch_run % 64 == 0) {
501                         blk_finish_plug(&plug);
502                         blk_start_plug(&plug);
503                         sync_pending = 0;
504                 }
505         }
506
507         cond_resched();
508         if (again)
509                 goto loop;
510
511         spin_lock(&device->io_lock);
512         if (device->pending_bios.head || device->pending_sync_bios.head)
513                 goto loop_lock;
514         spin_unlock(&device->io_lock);
515
516 done:
517         blk_finish_plug(&plug);
518 }
519
520 static void pending_bios_fn(struct btrfs_work *work)
521 {
522         struct btrfs_device *device;
523
524         device = container_of(work, struct btrfs_device, work);
525         run_scheduled_bios(device);
526 }
527
528
529 void btrfs_free_stale_device(struct btrfs_device *cur_dev)
530 {
531         struct btrfs_fs_devices *fs_devs;
532         struct btrfs_device *dev;
533
534         if (!cur_dev->name)
535                 return;
536
537         list_for_each_entry(fs_devs, &fs_uuids, list) {
538                 int del = 1;
539
540                 if (fs_devs->opened)
541                         continue;
542                 if (fs_devs->seeding)
543                         continue;
544
545                 list_for_each_entry(dev, &fs_devs->devices, dev_list) {
546
547                         if (dev == cur_dev)
548                                 continue;
549                         if (!dev->name)
550                                 continue;
551
552                         /*
553                          * Todo: This won't be enough. What if the same device
554                          * comes back (with new uuid and) with its mapper path?
555                          * But for now, this does help as mostly an admin will
556                          * either use mapper or non mapper path throughout.
557                          */
558                         rcu_read_lock();
559                         del = strcmp(rcu_str_deref(dev->name),
560                                                 rcu_str_deref(cur_dev->name));
561                         rcu_read_unlock();
562                         if (!del)
563                                 break;
564                 }
565
566                 if (!del) {
567                         /* delete the stale device */
568                         if (fs_devs->num_devices == 1) {
569                                 btrfs_sysfs_remove_fsid(fs_devs);
570                                 list_del(&fs_devs->list);
571                                 free_fs_devices(fs_devs);
572                         } else {
573                                 fs_devs->num_devices--;
574                                 list_del(&dev->dev_list);
575                                 rcu_string_free(dev->name);
576                                 kfree(dev);
577                         }
578                         break;
579                 }
580         }
581 }
582
583 /*
584  * Add new device to list of registered devices
585  *
586  * Returns:
587  * 1   - first time device is seen
588  * 0   - device already known
589  * < 0 - error
590  */
591 static noinline int device_list_add(const char *path,
592                            struct btrfs_super_block *disk_super,
593                            u64 devid, struct btrfs_fs_devices **fs_devices_ret)
594 {
595         struct btrfs_device *device;
596         struct btrfs_fs_devices *fs_devices;
597         struct rcu_string *name;
598         int ret = 0;
599         u64 found_transid = btrfs_super_generation(disk_super);
600
601         fs_devices = find_fsid(disk_super->fsid);
602         if (!fs_devices) {
603                 fs_devices = alloc_fs_devices(disk_super->fsid);
604                 if (IS_ERR(fs_devices))
605                         return PTR_ERR(fs_devices);
606
607                 list_add(&fs_devices->list, &fs_uuids);
608
609                 device = NULL;
610         } else {
611                 device = __find_device(&fs_devices->devices, devid,
612                                        disk_super->dev_item.uuid);
613         }
614
615         if (!device) {
616                 if (fs_devices->opened)
617                         return -EBUSY;
618
619                 device = btrfs_alloc_device(NULL, &devid,
620                                             disk_super->dev_item.uuid);
621                 if (IS_ERR(device)) {
622                         /* we can safely leave the fs_devices entry around */
623                         return PTR_ERR(device);
624                 }
625
626                 name = rcu_string_strdup(path, GFP_NOFS);
627                 if (!name) {
628                         kfree(device);
629                         return -ENOMEM;
630                 }
631                 rcu_assign_pointer(device->name, name);
632
633                 mutex_lock(&fs_devices->device_list_mutex);
634                 list_add_rcu(&device->dev_list, &fs_devices->devices);
635                 fs_devices->num_devices++;
636                 mutex_unlock(&fs_devices->device_list_mutex);
637
638                 ret = 1;
639                 device->fs_devices = fs_devices;
640         } else if (!device->name || strcmp(device->name->str, path)) {
641                 /*
642                  * When FS is already mounted.
643                  * 1. If you are here and if the device->name is NULL that
644                  *    means this device was missing at time of FS mount.
645                  * 2. If you are here and if the device->name is different
646                  *    from 'path' that means either
647                  *      a. The same device disappeared and reappeared with
648                  *         different name. or
649                  *      b. The missing-disk-which-was-replaced, has
650                  *         reappeared now.
651                  *
652                  * We must allow 1 and 2a above. But 2b would be a spurious
653                  * and unintentional.
654                  *
655                  * Further in case of 1 and 2a above, the disk at 'path'
656                  * would have missed some transaction when it was away and
657                  * in case of 2a the stale bdev has to be updated as well.
658                  * 2b must not be allowed at all time.
659                  */
660
661                 /*
662                  * For now, we do allow update to btrfs_fs_device through the
663                  * btrfs dev scan cli after FS has been mounted.  We're still
664                  * tracking a problem where systems fail mount by subvolume id
665                  * when we reject replacement on a mounted FS.
666                  */
667                 if (!fs_devices->opened && found_transid < device->generation) {
668                         /*
669                          * That is if the FS is _not_ mounted and if you
670                          * are here, that means there is more than one
671                          * disk with same uuid and devid.We keep the one
672                          * with larger generation number or the last-in if
673                          * generation are equal.
674                          */
675                         return -EEXIST;
676                 }
677
678                 name = rcu_string_strdup(path, GFP_NOFS);
679                 if (!name)
680                         return -ENOMEM;
681                 rcu_string_free(device->name);
682                 rcu_assign_pointer(device->name, name);
683                 if (device->missing) {
684                         fs_devices->missing_devices--;
685                         device->missing = 0;
686                 }
687         }
688
689         /*
690          * Unmount does not free the btrfs_device struct but would zero
691          * generation along with most of the other members. So just update
692          * it back. We need it to pick the disk with largest generation
693          * (as above).
694          */
695         if (!fs_devices->opened)
696                 device->generation = found_transid;
697
698         /*
699          * if there is new btrfs on an already registered device,
700          * then remove the stale device entry.
701          */
702         btrfs_free_stale_device(device);
703
704         *fs_devices_ret = fs_devices;
705
706         return ret;
707 }
708
709 static struct btrfs_fs_devices *clone_fs_devices(struct btrfs_fs_devices *orig)
710 {
711         struct btrfs_fs_devices *fs_devices;
712         struct btrfs_device *device;
713         struct btrfs_device *orig_dev;
714
715         fs_devices = alloc_fs_devices(orig->fsid);
716         if (IS_ERR(fs_devices))
717                 return fs_devices;
718
719         mutex_lock(&orig->device_list_mutex);
720         fs_devices->total_devices = orig->total_devices;
721
722         /* We have held the volume lock, it is safe to get the devices. */
723         list_for_each_entry(orig_dev, &orig->devices, dev_list) {
724                 struct rcu_string *name;
725
726                 device = btrfs_alloc_device(NULL, &orig_dev->devid,
727                                             orig_dev->uuid);
728                 if (IS_ERR(device))
729                         goto error;
730
731                 /*
732                  * This is ok to do without rcu read locked because we hold the
733                  * uuid mutex so nothing we touch in here is going to disappear.
734                  */
735                 if (orig_dev->name) {
736                         name = rcu_string_strdup(orig_dev->name->str,
737                                         GFP_KERNEL);
738                         if (!name) {
739                                 kfree(device);
740                                 goto error;
741                         }
742                         rcu_assign_pointer(device->name, name);
743                 }
744
745                 list_add(&device->dev_list, &fs_devices->devices);
746                 device->fs_devices = fs_devices;
747                 fs_devices->num_devices++;
748         }
749         mutex_unlock(&orig->device_list_mutex);
750         return fs_devices;
751 error:
752         mutex_unlock(&orig->device_list_mutex);
753         free_fs_devices(fs_devices);
754         return ERR_PTR(-ENOMEM);
755 }
756
757 void btrfs_close_extra_devices(struct btrfs_fs_devices *fs_devices, int step)
758 {
759         struct btrfs_device *device, *next;
760         struct btrfs_device *latest_dev = NULL;
761
762         mutex_lock(&uuid_mutex);
763 again:
764         /* This is the initialized path, it is safe to release the devices. */
765         list_for_each_entry_safe(device, next, &fs_devices->devices, dev_list) {
766                 if (device->in_fs_metadata) {
767                         if (!device->is_tgtdev_for_dev_replace &&
768                             (!latest_dev ||
769                              device->generation > latest_dev->generation)) {
770                                 latest_dev = device;
771                         }
772                         continue;
773                 }
774
775                 if (device->devid == BTRFS_DEV_REPLACE_DEVID) {
776                         /*
777                          * In the first step, keep the device which has
778                          * the correct fsid and the devid that is used
779                          * for the dev_replace procedure.
780                          * In the second step, the dev_replace state is
781                          * read from the device tree and it is known
782                          * whether the procedure is really active or
783                          * not, which means whether this device is
784                          * used or whether it should be removed.
785                          */
786                         if (step == 0 || device->is_tgtdev_for_dev_replace) {
787                                 continue;
788                         }
789                 }
790                 if (device->bdev) {
791                         blkdev_put(device->bdev, device->mode);
792                         device->bdev = NULL;
793                         fs_devices->open_devices--;
794                 }
795                 if (device->writeable) {
796                         list_del_init(&device->dev_alloc_list);
797                         device->writeable = 0;
798                         if (!device->is_tgtdev_for_dev_replace)
799                                 fs_devices->rw_devices--;
800                 }
801                 list_del_init(&device->dev_list);
802                 fs_devices->num_devices--;
803                 rcu_string_free(device->name);
804                 kfree(device);
805         }
806
807         if (fs_devices->seed) {
808                 fs_devices = fs_devices->seed;
809                 goto again;
810         }
811
812         fs_devices->latest_bdev = latest_dev->bdev;
813
814         mutex_unlock(&uuid_mutex);
815 }
816
817 static void __free_device(struct work_struct *work)
818 {
819         struct btrfs_device *device;
820
821         device = container_of(work, struct btrfs_device, rcu_work);
822
823         if (device->bdev)
824                 blkdev_put(device->bdev, device->mode);
825
826         rcu_string_free(device->name);
827         kfree(device);
828 }
829
830 static void free_device(struct rcu_head *head)
831 {
832         struct btrfs_device *device;
833
834         device = container_of(head, struct btrfs_device, rcu);
835
836         INIT_WORK(&device->rcu_work, __free_device);
837         schedule_work(&device->rcu_work);
838 }
839
840 static int __btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
841 {
842         struct btrfs_device *device, *tmp;
843
844         if (--fs_devices->opened > 0)
845                 return 0;
846
847         mutex_lock(&fs_devices->device_list_mutex);
848         list_for_each_entry_safe(device, tmp, &fs_devices->devices, dev_list) {
849                 btrfs_close_one_device(device);
850         }
851         mutex_unlock(&fs_devices->device_list_mutex);
852
853         WARN_ON(fs_devices->open_devices);
854         WARN_ON(fs_devices->rw_devices);
855         fs_devices->opened = 0;
856         fs_devices->seeding = 0;
857
858         return 0;
859 }
860
861 int btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
862 {
863         struct btrfs_fs_devices *seed_devices = NULL;
864         int ret;
865
866         mutex_lock(&uuid_mutex);
867         ret = __btrfs_close_devices(fs_devices);
868         if (!fs_devices->opened) {
869                 seed_devices = fs_devices->seed;
870                 fs_devices->seed = NULL;
871         }
872         mutex_unlock(&uuid_mutex);
873
874         while (seed_devices) {
875                 fs_devices = seed_devices;
876                 seed_devices = fs_devices->seed;
877                 __btrfs_close_devices(fs_devices);
878                 free_fs_devices(fs_devices);
879         }
880         /*
881          * Wait for rcu kworkers under __btrfs_close_devices
882          * to finish all blkdev_puts so device is really
883          * free when umount is done.
884          */
885         rcu_barrier();
886         return ret;
887 }
888
889 static int __btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
890                                 fmode_t flags, void *holder)
891 {
892         struct request_queue *q;
893         struct block_device *bdev;
894         struct list_head *head = &fs_devices->devices;
895         struct btrfs_device *device;
896         struct btrfs_device *latest_dev = NULL;
897         struct buffer_head *bh;
898         struct btrfs_super_block *disk_super;
899         u64 devid;
900         int seeding = 1;
901         int ret = 0;
902
903         flags |= FMODE_EXCL;
904
905         list_for_each_entry(device, head, dev_list) {
906                 if (device->bdev)
907                         continue;
908                 if (!device->name)
909                         continue;
910
911                 /* Just open everything we can; ignore failures here */
912                 if (btrfs_get_bdev_and_sb(device->name->str, flags, holder, 1,
913                                             &bdev, &bh))
914                         continue;
915
916                 disk_super = (struct btrfs_super_block *)bh->b_data;
917                 devid = btrfs_stack_device_id(&disk_super->dev_item);
918                 if (devid != device->devid)
919                         goto error_brelse;
920
921                 if (memcmp(device->uuid, disk_super->dev_item.uuid,
922                            BTRFS_UUID_SIZE))
923                         goto error_brelse;
924
925                 device->generation = btrfs_super_generation(disk_super);
926                 if (!latest_dev ||
927                     device->generation > latest_dev->generation)
928                         latest_dev = device;
929
930                 if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_SEEDING) {
931                         device->writeable = 0;
932                 } else {
933                         device->writeable = !bdev_read_only(bdev);
934                         seeding = 0;
935                 }
936
937                 q = bdev_get_queue(bdev);
938                 if (blk_queue_discard(q))
939                         device->can_discard = 1;
940
941                 device->bdev = bdev;
942                 device->in_fs_metadata = 0;
943                 device->mode = flags;
944
945                 if (!blk_queue_nonrot(bdev_get_queue(bdev)))
946                         fs_devices->rotating = 1;
947
948                 fs_devices->open_devices++;
949                 if (device->writeable &&
950                     device->devid != BTRFS_DEV_REPLACE_DEVID) {
951                         fs_devices->rw_devices++;
952                         list_add(&device->dev_alloc_list,
953                                  &fs_devices->alloc_list);
954                 }
955                 brelse(bh);
956                 continue;
957
958 error_brelse:
959                 brelse(bh);
960                 blkdev_put(bdev, flags);
961                 continue;
962         }
963         if (fs_devices->open_devices == 0) {
964                 ret = -EINVAL;
965                 goto out;
966         }
967         fs_devices->seeding = seeding;
968         fs_devices->opened = 1;
969         fs_devices->latest_bdev = latest_dev->bdev;
970         fs_devices->total_rw_bytes = 0;
971 out:
972         return ret;
973 }
974
975 int btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
976                        fmode_t flags, void *holder)
977 {
978         int ret;
979
980         mutex_lock(&uuid_mutex);
981         if (fs_devices->opened) {
982                 fs_devices->opened++;
983                 ret = 0;
984         } else {
985                 ret = __btrfs_open_devices(fs_devices, flags, holder);
986         }
987         mutex_unlock(&uuid_mutex);
988         return ret;
989 }
990
991 void btrfs_release_disk_super(struct page *page)
992 {
993         kunmap(page);
994         put_page(page);
995 }
996
997 int btrfs_read_disk_super(struct block_device *bdev, u64 bytenr,
998                 struct page **page, struct btrfs_super_block **disk_super)
999 {
1000         void *p;
1001         pgoff_t index;
1002
1003         /* make sure our super fits in the device */
1004         if (bytenr + PAGE_SIZE >= i_size_read(bdev->bd_inode))
1005                 return 1;
1006
1007         /* make sure our super fits in the page */
1008         if (sizeof(**disk_super) > PAGE_SIZE)
1009                 return 1;
1010
1011         /* make sure our super doesn't straddle pages on disk */
1012         index = bytenr >> PAGE_SHIFT;
1013         if ((bytenr + sizeof(**disk_super) - 1) >> PAGE_SHIFT != index)
1014                 return 1;
1015
1016         /* pull in the page with our super */
1017         *page = read_cache_page_gfp(bdev->bd_inode->i_mapping,
1018                                    index, GFP_KERNEL);
1019
1020         if (IS_ERR_OR_NULL(*page))
1021                 return 1;
1022
1023         p = kmap(*page);
1024
1025         /* align our pointer to the offset of the super block */
1026         *disk_super = p + (bytenr & ~PAGE_MASK);
1027
1028         if (btrfs_super_bytenr(*disk_super) != bytenr ||
1029             btrfs_super_magic(*disk_super) != BTRFS_MAGIC) {
1030                 btrfs_release_disk_super(*page);
1031                 return 1;
1032         }
1033
1034         if ((*disk_super)->label[0] &&
1035                 (*disk_super)->label[BTRFS_LABEL_SIZE - 1])
1036                 (*disk_super)->label[BTRFS_LABEL_SIZE - 1] = '\0';
1037
1038         return 0;
1039 }
1040
1041 /*
1042  * Look for a btrfs signature on a device. This may be called out of the mount path
1043  * and we are not allowed to call set_blocksize during the scan. The superblock
1044  * is read via pagecache
1045  */
1046 int btrfs_scan_one_device(const char *path, fmode_t flags, void *holder,
1047                           struct btrfs_fs_devices **fs_devices_ret)
1048 {
1049         struct btrfs_super_block *disk_super;
1050         struct block_device *bdev;
1051         struct page *page;
1052         int ret = -EINVAL;
1053         u64 devid;
1054         u64 transid;
1055         u64 total_devices;
1056         u64 bytenr;
1057
1058         /*
1059          * we would like to check all the supers, but that would make
1060          * a btrfs mount succeed after a mkfs from a different FS.
1061          * So, we need to add a special mount option to scan for
1062          * later supers, using BTRFS_SUPER_MIRROR_MAX instead
1063          */
1064         bytenr = btrfs_sb_offset(0);
1065         flags |= FMODE_EXCL;
1066         mutex_lock(&uuid_mutex);
1067
1068         bdev = blkdev_get_by_path(path, flags, holder);
1069         if (IS_ERR(bdev)) {
1070                 ret = PTR_ERR(bdev);
1071                 goto error;
1072         }
1073
1074         if (btrfs_read_disk_super(bdev, bytenr, &page, &disk_super))
1075                 goto error_bdev_put;
1076
1077         devid = btrfs_stack_device_id(&disk_super->dev_item);
1078         transid = btrfs_super_generation(disk_super);
1079         total_devices = btrfs_super_num_devices(disk_super);
1080
1081         ret = device_list_add(path, disk_super, devid, fs_devices_ret);
1082         if (ret > 0) {
1083                 if (disk_super->label[0]) {
1084                         printk(KERN_INFO "BTRFS: device label %s ", disk_super->label);
1085                 } else {
1086                         printk(KERN_INFO "BTRFS: device fsid %pU ", disk_super->fsid);
1087                 }
1088
1089                 printk(KERN_CONT "devid %llu transid %llu %s\n", devid, transid, path);
1090                 ret = 0;
1091         }
1092         if (!ret && fs_devices_ret)
1093                 (*fs_devices_ret)->total_devices = total_devices;
1094
1095         btrfs_release_disk_super(page);
1096
1097 error_bdev_put:
1098         blkdev_put(bdev, flags);
1099 error:
1100         mutex_unlock(&uuid_mutex);
1101         return ret;
1102 }
1103
1104 /* helper to account the used device space in the range */
1105 int btrfs_account_dev_extents_size(struct btrfs_device *device, u64 start,
1106                                    u64 end, u64 *length)
1107 {
1108         struct btrfs_key key;
1109         struct btrfs_root *root = device->dev_root;
1110         struct btrfs_dev_extent *dev_extent;
1111         struct btrfs_path *path;
1112         u64 extent_end;
1113         int ret;
1114         int slot;
1115         struct extent_buffer *l;
1116
1117         *length = 0;
1118
1119         if (start >= device->total_bytes || device->is_tgtdev_for_dev_replace)
1120                 return 0;
1121
1122         path = btrfs_alloc_path();
1123         if (!path)
1124                 return -ENOMEM;
1125         path->reada = READA_FORWARD;
1126
1127         key.objectid = device->devid;
1128         key.offset = start;
1129         key.type = BTRFS_DEV_EXTENT_KEY;
1130
1131         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1132         if (ret < 0)
1133                 goto out;
1134         if (ret > 0) {
1135                 ret = btrfs_previous_item(root, path, key.objectid, key.type);
1136                 if (ret < 0)
1137                         goto out;
1138         }
1139
1140         while (1) {
1141                 l = path->nodes[0];
1142                 slot = path->slots[0];
1143                 if (slot >= btrfs_header_nritems(l)) {
1144                         ret = btrfs_next_leaf(root, path);
1145                         if (ret == 0)
1146                                 continue;
1147                         if (ret < 0)
1148                                 goto out;
1149
1150                         break;
1151                 }
1152                 btrfs_item_key_to_cpu(l, &key, slot);
1153
1154                 if (key.objectid < device->devid)
1155                         goto next;
1156
1157                 if (key.objectid > device->devid)
1158                         break;
1159
1160                 if (key.type != BTRFS_DEV_EXTENT_KEY)
1161                         goto next;
1162
1163                 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
1164                 extent_end = key.offset + btrfs_dev_extent_length(l,
1165                                                                   dev_extent);
1166                 if (key.offset <= start && extent_end > end) {
1167                         *length = end - start + 1;
1168                         break;
1169                 } else if (key.offset <= start && extent_end > start)
1170                         *length += extent_end - start;
1171                 else if (key.offset > start && extent_end <= end)
1172                         *length += extent_end - key.offset;
1173                 else if (key.offset > start && key.offset <= end) {
1174                         *length += end - key.offset + 1;
1175                         break;
1176                 } else if (key.offset > end)
1177                         break;
1178
1179 next:
1180                 path->slots[0]++;
1181         }
1182         ret = 0;
1183 out:
1184         btrfs_free_path(path);
1185         return ret;
1186 }
1187
1188 static int contains_pending_extent(struct btrfs_transaction *transaction,
1189                                    struct btrfs_device *device,
1190                                    u64 *start, u64 len)
1191 {
1192         struct btrfs_fs_info *fs_info = device->dev_root->fs_info;
1193         struct extent_map *em;
1194         struct list_head *search_list = &fs_info->pinned_chunks;
1195         int ret = 0;
1196         u64 physical_start = *start;
1197
1198         if (transaction)
1199                 search_list = &transaction->pending_chunks;
1200 again:
1201         list_for_each_entry(em, search_list, list) {
1202                 struct map_lookup *map;
1203                 int i;
1204
1205                 map = em->map_lookup;
1206                 for (i = 0; i < map->num_stripes; i++) {
1207                         u64 end;
1208
1209                         if (map->stripes[i].dev != device)
1210                                 continue;
1211                         if (map->stripes[i].physical >= physical_start + len ||
1212                             map->stripes[i].physical + em->orig_block_len <=
1213                             physical_start)
1214                                 continue;
1215                         /*
1216                          * Make sure that while processing the pinned list we do
1217                          * not override our *start with a lower value, because
1218                          * we can have pinned chunks that fall within this
1219                          * device hole and that have lower physical addresses
1220                          * than the pending chunks we processed before. If we
1221                          * do not take this special care we can end up getting
1222                          * 2 pending chunks that start at the same physical
1223                          * device offsets because the end offset of a pinned
1224                          * chunk can be equal to the start offset of some
1225                          * pending chunk.
1226                          */
1227                         end = map->stripes[i].physical + em->orig_block_len;
1228                         if (end > *start) {
1229                                 *start = end;
1230                                 ret = 1;
1231                         }
1232                 }
1233         }
1234         if (search_list != &fs_info->pinned_chunks) {
1235                 search_list = &fs_info->pinned_chunks;
1236                 goto again;
1237         }
1238
1239         return ret;
1240 }
1241
1242
1243 /*
1244  * find_free_dev_extent_start - find free space in the specified device
1245  * @device:       the device which we search the free space in
1246  * @num_bytes:    the size of the free space that we need
1247  * @search_start: the position from which to begin the search
1248  * @start:        store the start of the free space.
1249  * @len:          the size of the free space. that we find, or the size
1250  *                of the max free space if we don't find suitable free space
1251  *
1252  * this uses a pretty simple search, the expectation is that it is
1253  * called very infrequently and that a given device has a small number
1254  * of extents
1255  *
1256  * @start is used to store the start of the free space if we find. But if we
1257  * don't find suitable free space, it will be used to store the start position
1258  * of the max free space.
1259  *
1260  * @len is used to store the size of the free space that we find.
1261  * But if we don't find suitable free space, it is used to store the size of
1262  * the max free space.
1263  */
1264 int find_free_dev_extent_start(struct btrfs_transaction *transaction,
1265                                struct btrfs_device *device, u64 num_bytes,
1266                                u64 search_start, u64 *start, u64 *len)
1267 {
1268         struct btrfs_key key;
1269         struct btrfs_root *root = device->dev_root;
1270         struct btrfs_dev_extent *dev_extent;
1271         struct btrfs_path *path;
1272         u64 hole_size;
1273         u64 max_hole_start;
1274         u64 max_hole_size;
1275         u64 extent_end;
1276         u64 search_end = device->total_bytes;
1277         int ret;
1278         int slot;
1279         struct extent_buffer *l;
1280         u64 min_search_start;
1281
1282         /*
1283          * We don't want to overwrite the superblock on the drive nor any area
1284          * used by the boot loader (grub for example), so we make sure to start
1285          * at an offset of at least 1MB.
1286          */
1287         min_search_start = max(root->fs_info->alloc_start, 1024ull * 1024);
1288         search_start = max(search_start, min_search_start);
1289
1290         path = btrfs_alloc_path();
1291         if (!path)
1292                 return -ENOMEM;
1293
1294         max_hole_start = search_start;
1295         max_hole_size = 0;
1296
1297 again:
1298         if (search_start >= search_end || device->is_tgtdev_for_dev_replace) {
1299                 ret = -ENOSPC;
1300                 goto out;
1301         }
1302
1303         path->reada = READA_FORWARD;
1304         path->search_commit_root = 1;
1305         path->skip_locking = 1;
1306
1307         key.objectid = device->devid;
1308         key.offset = search_start;
1309         key.type = BTRFS_DEV_EXTENT_KEY;
1310
1311         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1312         if (ret < 0)
1313                 goto out;
1314         if (ret > 0) {
1315                 ret = btrfs_previous_item(root, path, key.objectid, key.type);
1316                 if (ret < 0)
1317                         goto out;
1318         }
1319
1320         while (1) {
1321                 l = path->nodes[0];
1322                 slot = path->slots[0];
1323                 if (slot >= btrfs_header_nritems(l)) {
1324                         ret = btrfs_next_leaf(root, path);
1325                         if (ret == 0)
1326                                 continue;
1327                         if (ret < 0)
1328                                 goto out;
1329
1330                         break;
1331                 }
1332                 btrfs_item_key_to_cpu(l, &key, slot);
1333
1334                 if (key.objectid < device->devid)
1335                         goto next;
1336
1337                 if (key.objectid > device->devid)
1338                         break;
1339
1340                 if (key.type != BTRFS_DEV_EXTENT_KEY)
1341                         goto next;
1342
1343                 if (key.offset > search_start) {
1344                         hole_size = key.offset - search_start;
1345
1346                         /*
1347                          * Have to check before we set max_hole_start, otherwise
1348                          * we could end up sending back this offset anyway.
1349                          */
1350                         if (contains_pending_extent(transaction, device,
1351                                                     &search_start,
1352                                                     hole_size)) {
1353                                 if (key.offset >= search_start) {
1354                                         hole_size = key.offset - search_start;
1355                                 } else {
1356                                         WARN_ON_ONCE(1);
1357                                         hole_size = 0;
1358                                 }
1359                         }
1360
1361                         if (hole_size > max_hole_size) {
1362                                 max_hole_start = search_start;
1363                                 max_hole_size = hole_size;
1364                         }
1365
1366                         /*
1367                          * If this free space is greater than which we need,
1368                          * it must be the max free space that we have found
1369                          * until now, so max_hole_start must point to the start
1370                          * of this free space and the length of this free space
1371                          * is stored in max_hole_size. Thus, we return
1372                          * max_hole_start and max_hole_size and go back to the
1373                          * caller.
1374                          */
1375                         if (hole_size >= num_bytes) {
1376                                 ret = 0;
1377                                 goto out;
1378                         }
1379                 }
1380
1381                 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
1382                 extent_end = key.offset + btrfs_dev_extent_length(l,
1383                                                                   dev_extent);
1384                 if (extent_end > search_start)
1385                         search_start = extent_end;
1386 next:
1387                 path->slots[0]++;
1388                 cond_resched();
1389         }
1390
1391         /*
1392          * At this point, search_start should be the end of
1393          * allocated dev extents, and when shrinking the device,
1394          * search_end may be smaller than search_start.
1395          */
1396         if (search_end > search_start) {
1397                 hole_size = search_end - search_start;
1398
1399                 if (contains_pending_extent(transaction, device, &search_start,
1400                                             hole_size)) {
1401                         btrfs_release_path(path);
1402                         goto again;
1403                 }
1404
1405                 if (hole_size > max_hole_size) {
1406                         max_hole_start = search_start;
1407                         max_hole_size = hole_size;
1408                 }
1409         }
1410
1411         /* See above. */
1412         if (max_hole_size < num_bytes)
1413                 ret = -ENOSPC;
1414         else
1415                 ret = 0;
1416
1417 out:
1418         btrfs_free_path(path);
1419         *start = max_hole_start;
1420         if (len)
1421                 *len = max_hole_size;
1422         return ret;
1423 }
1424
1425 int find_free_dev_extent(struct btrfs_trans_handle *trans,
1426                          struct btrfs_device *device, u64 num_bytes,
1427                          u64 *start, u64 *len)
1428 {
1429         /* FIXME use last free of some kind */
1430         return find_free_dev_extent_start(trans->transaction, device,
1431                                           num_bytes, 0, start, len);
1432 }
1433
1434 static int btrfs_free_dev_extent(struct btrfs_trans_handle *trans,
1435                           struct btrfs_device *device,
1436                           u64 start, u64 *dev_extent_len)
1437 {
1438         int ret;
1439         struct btrfs_path *path;
1440         struct btrfs_root *root = device->dev_root;
1441         struct btrfs_key key;
1442         struct btrfs_key found_key;
1443         struct extent_buffer *leaf = NULL;
1444         struct btrfs_dev_extent *extent = NULL;
1445
1446         path = btrfs_alloc_path();
1447         if (!path)
1448                 return -ENOMEM;
1449
1450         key.objectid = device->devid;
1451         key.offset = start;
1452         key.type = BTRFS_DEV_EXTENT_KEY;
1453 again:
1454         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1455         if (ret > 0) {
1456                 ret = btrfs_previous_item(root, path, key.objectid,
1457                                           BTRFS_DEV_EXTENT_KEY);
1458                 if (ret)
1459                         goto out;
1460                 leaf = path->nodes[0];
1461                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1462                 extent = btrfs_item_ptr(leaf, path->slots[0],
1463                                         struct btrfs_dev_extent);
1464                 BUG_ON(found_key.offset > start || found_key.offset +
1465                        btrfs_dev_extent_length(leaf, extent) < start);
1466                 key = found_key;
1467                 btrfs_release_path(path);
1468                 goto again;
1469         } else if (ret == 0) {
1470                 leaf = path->nodes[0];
1471                 extent = btrfs_item_ptr(leaf, path->slots[0],
1472                                         struct btrfs_dev_extent);
1473         } else {
1474                 btrfs_std_error(root->fs_info, ret, "Slot search failed");
1475                 goto out;
1476         }
1477
1478         *dev_extent_len = btrfs_dev_extent_length(leaf, extent);
1479
1480         ret = btrfs_del_item(trans, root, path);
1481         if (ret) {
1482                 btrfs_std_error(root->fs_info, ret,
1483                             "Failed to remove dev extent item");
1484         } else {
1485                 set_bit(BTRFS_TRANS_HAVE_FREE_BGS, &trans->transaction->flags);
1486         }
1487 out:
1488         btrfs_free_path(path);
1489         return ret;
1490 }
1491
1492 static int btrfs_alloc_dev_extent(struct btrfs_trans_handle *trans,
1493                                   struct btrfs_device *device,
1494                                   u64 chunk_tree, u64 chunk_objectid,
1495                                   u64 chunk_offset, u64 start, u64 num_bytes)
1496 {
1497         int ret;
1498         struct btrfs_path *path;
1499         struct btrfs_root *root = device->dev_root;
1500         struct btrfs_dev_extent *extent;
1501         struct extent_buffer *leaf;
1502         struct btrfs_key key;
1503
1504         WARN_ON(!device->in_fs_metadata);
1505         WARN_ON(device->is_tgtdev_for_dev_replace);
1506         path = btrfs_alloc_path();
1507         if (!path)
1508                 return -ENOMEM;
1509
1510         key.objectid = device->devid;
1511         key.offset = start;
1512         key.type = BTRFS_DEV_EXTENT_KEY;
1513         ret = btrfs_insert_empty_item(trans, root, path, &key,
1514                                       sizeof(*extent));
1515         if (ret)
1516                 goto out;
1517
1518         leaf = path->nodes[0];
1519         extent = btrfs_item_ptr(leaf, path->slots[0],
1520                                 struct btrfs_dev_extent);
1521         btrfs_set_dev_extent_chunk_tree(leaf, extent, chunk_tree);
1522         btrfs_set_dev_extent_chunk_objectid(leaf, extent, chunk_objectid);
1523         btrfs_set_dev_extent_chunk_offset(leaf, extent, chunk_offset);
1524
1525         write_extent_buffer(leaf, root->fs_info->chunk_tree_uuid,
1526                     btrfs_dev_extent_chunk_tree_uuid(extent), BTRFS_UUID_SIZE);
1527
1528         btrfs_set_dev_extent_length(leaf, extent, num_bytes);
1529         btrfs_mark_buffer_dirty(leaf);
1530 out:
1531         btrfs_free_path(path);
1532         return ret;
1533 }
1534
1535 static u64 find_next_chunk(struct btrfs_fs_info *fs_info)
1536 {
1537         struct extent_map_tree *em_tree;
1538         struct extent_map *em;
1539         struct rb_node *n;
1540         u64 ret = 0;
1541
1542         em_tree = &fs_info->mapping_tree.map_tree;
1543         read_lock(&em_tree->lock);
1544         n = rb_last(&em_tree->map);
1545         if (n) {
1546                 em = rb_entry(n, struct extent_map, rb_node);
1547                 ret = em->start + em->len;
1548         }
1549         read_unlock(&em_tree->lock);
1550
1551         return ret;
1552 }
1553
1554 static noinline int find_next_devid(struct btrfs_fs_info *fs_info,
1555                                     u64 *devid_ret)
1556 {
1557         int ret;
1558         struct btrfs_key key;
1559         struct btrfs_key found_key;
1560         struct btrfs_path *path;
1561
1562         path = btrfs_alloc_path();
1563         if (!path)
1564                 return -ENOMEM;
1565
1566         key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1567         key.type = BTRFS_DEV_ITEM_KEY;
1568         key.offset = (u64)-1;
1569
1570         ret = btrfs_search_slot(NULL, fs_info->chunk_root, &key, path, 0, 0);
1571         if (ret < 0)
1572                 goto error;
1573
1574         BUG_ON(ret == 0); /* Corruption */
1575
1576         ret = btrfs_previous_item(fs_info->chunk_root, path,
1577                                   BTRFS_DEV_ITEMS_OBJECTID,
1578                                   BTRFS_DEV_ITEM_KEY);
1579         if (ret) {
1580                 *devid_ret = 1;
1581         } else {
1582                 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
1583                                       path->slots[0]);
1584                 *devid_ret = found_key.offset + 1;
1585         }
1586         ret = 0;
1587 error:
1588         btrfs_free_path(path);
1589         return ret;
1590 }
1591
1592 /*
1593  * the device information is stored in the chunk root
1594  * the btrfs_device struct should be fully filled in
1595  */
1596 static int btrfs_add_device(struct btrfs_trans_handle *trans,
1597                             struct btrfs_root *root,
1598                             struct btrfs_device *device)
1599 {
1600         int ret;
1601         struct btrfs_path *path;
1602         struct btrfs_dev_item *dev_item;
1603         struct extent_buffer *leaf;
1604         struct btrfs_key key;
1605         unsigned long ptr;
1606
1607         root = root->fs_info->chunk_root;
1608
1609         path = btrfs_alloc_path();
1610         if (!path)
1611                 return -ENOMEM;
1612
1613         key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1614         key.type = BTRFS_DEV_ITEM_KEY;
1615         key.offset = device->devid;
1616
1617         ret = btrfs_insert_empty_item(trans, root, path, &key,
1618                                       sizeof(*dev_item));
1619         if (ret)
1620                 goto out;
1621
1622         leaf = path->nodes[0];
1623         dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
1624
1625         btrfs_set_device_id(leaf, dev_item, device->devid);
1626         btrfs_set_device_generation(leaf, dev_item, 0);
1627         btrfs_set_device_type(leaf, dev_item, device->type);
1628         btrfs_set_device_io_align(leaf, dev_item, device->io_align);
1629         btrfs_set_device_io_width(leaf, dev_item, device->io_width);
1630         btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
1631         btrfs_set_device_total_bytes(leaf, dev_item,
1632                                      btrfs_device_get_disk_total_bytes(device));
1633         btrfs_set_device_bytes_used(leaf, dev_item,
1634                                     btrfs_device_get_bytes_used(device));
1635         btrfs_set_device_group(leaf, dev_item, 0);
1636         btrfs_set_device_seek_speed(leaf, dev_item, 0);
1637         btrfs_set_device_bandwidth(leaf, dev_item, 0);
1638         btrfs_set_device_start_offset(leaf, dev_item, 0);
1639
1640         ptr = btrfs_device_uuid(dev_item);
1641         write_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
1642         ptr = btrfs_device_fsid(dev_item);
1643         write_extent_buffer(leaf, root->fs_info->fsid, ptr, BTRFS_UUID_SIZE);
1644         btrfs_mark_buffer_dirty(leaf);
1645
1646         ret = 0;
1647 out:
1648         btrfs_free_path(path);
1649         return ret;
1650 }
1651
1652 /*
1653  * Function to update ctime/mtime for a given device path.
1654  * Mainly used for ctime/mtime based probe like libblkid.
1655  */
1656 static void update_dev_time(char *path_name)
1657 {
1658         struct file *filp;
1659
1660         filp = filp_open(path_name, O_RDWR, 0);
1661         if (IS_ERR(filp))
1662                 return;
1663         file_update_time(filp);
1664         filp_close(filp, NULL);
1665 }
1666
1667 static int btrfs_rm_dev_item(struct btrfs_root *root,
1668                              struct btrfs_device *device)
1669 {
1670         int ret;
1671         struct btrfs_path *path;
1672         struct btrfs_key key;
1673         struct btrfs_trans_handle *trans;
1674
1675         root = root->fs_info->chunk_root;
1676
1677         path = btrfs_alloc_path();
1678         if (!path)
1679                 return -ENOMEM;
1680
1681         trans = btrfs_start_transaction(root, 0);
1682         if (IS_ERR(trans)) {
1683                 btrfs_free_path(path);
1684                 return PTR_ERR(trans);
1685         }
1686         key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1687         key.type = BTRFS_DEV_ITEM_KEY;
1688         key.offset = device->devid;
1689
1690         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1691         if (ret < 0)
1692                 goto out;
1693
1694         if (ret > 0) {
1695                 ret = -ENOENT;
1696                 goto out;
1697         }
1698
1699         ret = btrfs_del_item(trans, root, path);
1700         if (ret)
1701                 goto out;
1702 out:
1703         btrfs_free_path(path);
1704         btrfs_commit_transaction(trans, root);
1705         return ret;
1706 }
1707
1708 static int __check_raid_min_devices(struct btrfs_fs_info *fs_info)
1709 {
1710         u64 all_avail;
1711         u64 num_devices;
1712         unsigned seq;
1713
1714         num_devices = fs_info->fs_devices->num_devices;
1715         btrfs_dev_replace_lock(&fs_info->dev_replace, 0);
1716         if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace)) {
1717                 WARN_ON(num_devices < 1);
1718                 num_devices--;
1719         }
1720         btrfs_dev_replace_unlock(&fs_info->dev_replace, 0);
1721
1722         do {
1723                 seq = read_seqbegin(&fs_info->profiles_lock);
1724
1725                 all_avail = fs_info->avail_data_alloc_bits |
1726                             fs_info->avail_system_alloc_bits |
1727                             fs_info->avail_metadata_alloc_bits;
1728         } while (read_seqretry(&fs_info->profiles_lock, seq));
1729
1730         if ((all_avail & BTRFS_BLOCK_GROUP_RAID10) && num_devices <= 4) {
1731                 return BTRFS_ERROR_DEV_RAID10_MIN_NOT_MET;
1732         }
1733
1734         if ((all_avail & BTRFS_BLOCK_GROUP_RAID1) && num_devices <= 2) {
1735                 return BTRFS_ERROR_DEV_RAID1_MIN_NOT_MET;
1736         }
1737
1738         if ((all_avail & BTRFS_BLOCK_GROUP_RAID5) &&
1739             fs_info->fs_devices->rw_devices <= 2) {
1740                 return BTRFS_ERROR_DEV_RAID5_MIN_NOT_MET;
1741         }
1742
1743         if ((all_avail & BTRFS_BLOCK_GROUP_RAID6) &&
1744             fs_info->fs_devices->rw_devices <= 3) {
1745                 return BTRFS_ERROR_DEV_RAID6_MIN_NOT_MET;
1746         }
1747
1748         return 0;
1749 }
1750
1751 int btrfs_rm_device(struct btrfs_root *root, char *device_path)
1752 {
1753         struct btrfs_device *device;
1754         struct btrfs_device *next_device;
1755         struct block_device *bdev = NULL;
1756         struct buffer_head *bh = NULL;
1757         struct btrfs_super_block *disk_super = NULL;
1758         struct btrfs_fs_devices *cur_devices;
1759         u64 num_devices;
1760         int ret = 0;
1761         bool clear_super = false;
1762
1763         mutex_lock(&uuid_mutex);
1764
1765         ret = __check_raid_min_devices(root->fs_info);
1766         if (ret)
1767                 goto out;
1768
1769         ret = btrfs_find_device_by_user_input(root, 0, device_path,
1770                                 &device);
1771         if (ret)
1772                 goto out;
1773
1774         if (device->is_tgtdev_for_dev_replace) {
1775                 ret = BTRFS_ERROR_DEV_TGT_REPLACE;
1776                 goto out;
1777         }
1778
1779         if (device->writeable && root->fs_info->fs_devices->rw_devices == 1) {
1780                 ret = BTRFS_ERROR_DEV_ONLY_WRITABLE;
1781                 goto out;
1782         }
1783
1784         if (device->writeable) {
1785                 lock_chunks(root);
1786                 list_del_init(&device->dev_alloc_list);
1787                 device->fs_devices->rw_devices--;
1788                 unlock_chunks(root);
1789                 clear_super = true;
1790         }
1791
1792         mutex_unlock(&uuid_mutex);
1793         ret = btrfs_shrink_device(device, 0);
1794         mutex_lock(&uuid_mutex);
1795         if (ret)
1796                 goto error_undo;
1797
1798         /*
1799          * TODO: the superblock still includes this device in its num_devices
1800          * counter although write_all_supers() is not locked out. This
1801          * could give a filesystem state which requires a degraded mount.
1802          */
1803         ret = btrfs_rm_dev_item(root->fs_info->chunk_root, device);
1804         if (ret)
1805                 goto error_undo;
1806
1807         device->in_fs_metadata = 0;
1808         btrfs_scrub_cancel_dev(root->fs_info, device);
1809
1810         /*
1811          * the device list mutex makes sure that we don't change
1812          * the device list while someone else is writing out all
1813          * the device supers. Whoever is writing all supers, should
1814          * lock the device list mutex before getting the number of
1815          * devices in the super block (super_copy). Conversely,
1816          * whoever updates the number of devices in the super block
1817          * (super_copy) should hold the device list mutex.
1818          */
1819
1820         cur_devices = device->fs_devices;
1821         mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
1822         list_del_rcu(&device->dev_list);
1823
1824         device->fs_devices->num_devices--;
1825         device->fs_devices->total_devices--;
1826
1827         if (device->missing)
1828                 device->fs_devices->missing_devices--;
1829
1830         next_device = list_entry(root->fs_info->fs_devices->devices.next,
1831                                  struct btrfs_device, dev_list);
1832         if (device->bdev == root->fs_info->sb->s_bdev)
1833                 root->fs_info->sb->s_bdev = next_device->bdev;
1834         if (device->bdev == root->fs_info->fs_devices->latest_bdev)
1835                 root->fs_info->fs_devices->latest_bdev = next_device->bdev;
1836
1837         if (device->bdev) {
1838                 device->fs_devices->open_devices--;
1839                 /* remove sysfs entry */
1840                 btrfs_sysfs_rm_device_link(root->fs_info->fs_devices, device);
1841         }
1842
1843         call_rcu(&device->rcu, free_device);
1844
1845         num_devices = btrfs_super_num_devices(root->fs_info->super_copy) - 1;
1846         btrfs_set_super_num_devices(root->fs_info->super_copy, num_devices);
1847         mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
1848
1849         if (cur_devices->open_devices == 0) {
1850                 struct btrfs_fs_devices *fs_devices;
1851                 fs_devices = root->fs_info->fs_devices;
1852                 while (fs_devices) {
1853                         if (fs_devices->seed == cur_devices) {
1854                                 fs_devices->seed = cur_devices->seed;
1855                                 break;
1856                         }
1857                         fs_devices = fs_devices->seed;
1858                 }
1859                 cur_devices->seed = NULL;
1860                 __btrfs_close_devices(cur_devices);
1861                 free_fs_devices(cur_devices);
1862         }
1863
1864         root->fs_info->num_tolerated_disk_barrier_failures =
1865                 btrfs_calc_num_tolerated_disk_barrier_failures(root->fs_info);
1866
1867         /*
1868          * at this point, the device is zero sized.  We want to
1869          * remove it from the devices list and zero out the old super
1870          */
1871         if (clear_super) {
1872                 u64 bytenr;
1873                 int i;
1874
1875                 if (!disk_super) {
1876                         ret = btrfs_get_bdev_and_sb(device_path,
1877                                         FMODE_WRITE | FMODE_EXCL,
1878                                         root->fs_info->bdev_holder, 0,
1879                                         &bdev, &bh);
1880                         if (ret) {
1881                                 /*
1882                                  * It could be a failed device ok for clear_super
1883                                  * to fail. So return success
1884                                  */
1885                                 ret = 0;
1886                                 goto out;
1887                         }
1888
1889                         disk_super = (struct btrfs_super_block *)bh->b_data;
1890                 }
1891                 /* make sure this device isn't detected as part of
1892                  * the FS anymore
1893                  */
1894                 memset(&disk_super->magic, 0, sizeof(disk_super->magic));
1895                 set_buffer_dirty(bh);
1896                 sync_dirty_buffer(bh);
1897                 brelse(bh);
1898
1899                 /* clear the mirror copies of super block on the disk
1900                  * being removed, 0th copy is been taken care above and
1901                  * the below would take of the rest
1902                  */
1903                 for (i = 1; i < BTRFS_SUPER_MIRROR_MAX; i++) {
1904                         bytenr = btrfs_sb_offset(i);
1905                         if (bytenr + BTRFS_SUPER_INFO_SIZE >=
1906                                         i_size_read(bdev->bd_inode))
1907                                 break;
1908
1909                         bh = __bread(bdev, bytenr / 4096,
1910                                         BTRFS_SUPER_INFO_SIZE);
1911                         if (!bh)
1912                                 continue;
1913
1914                         disk_super = (struct btrfs_super_block *)bh->b_data;
1915
1916                         if (btrfs_super_bytenr(disk_super) != bytenr ||
1917                                 btrfs_super_magic(disk_super) != BTRFS_MAGIC) {
1918                                 brelse(bh);
1919                                 continue;
1920                         }
1921                         memset(&disk_super->magic, 0,
1922                                                 sizeof(disk_super->magic));
1923                         set_buffer_dirty(bh);
1924                         sync_dirty_buffer(bh);
1925                         brelse(bh);
1926                 }
1927
1928                 if (bdev) {
1929                         /* Notify udev that device has changed */
1930                         btrfs_kobject_uevent(bdev, KOBJ_CHANGE);
1931
1932                         /* Update ctime/mtime for device path for libblkid */
1933                         update_dev_time(device_path);
1934                         blkdev_put(bdev, FMODE_READ | FMODE_EXCL);
1935                 }
1936         }
1937
1938 out:
1939         mutex_unlock(&uuid_mutex);
1940         return ret;
1941
1942 error_undo:
1943         if (device->writeable) {
1944                 lock_chunks(root);
1945                 list_add(&device->dev_alloc_list,
1946                          &root->fs_info->fs_devices->alloc_list);
1947                 device->fs_devices->rw_devices++;
1948                 unlock_chunks(root);
1949         }
1950         goto out;
1951 }
1952
1953 void btrfs_rm_dev_replace_remove_srcdev(struct btrfs_fs_info *fs_info,
1954                                         struct btrfs_device *srcdev)
1955 {
1956         struct btrfs_fs_devices *fs_devices;
1957
1958         WARN_ON(!mutex_is_locked(&fs_info->fs_devices->device_list_mutex));
1959
1960         /*
1961          * in case of fs with no seed, srcdev->fs_devices will point
1962          * to fs_devices of fs_info. However when the dev being replaced is
1963          * a seed dev it will point to the seed's local fs_devices. In short
1964          * srcdev will have its correct fs_devices in both the cases.
1965          */
1966         fs_devices = srcdev->fs_devices;
1967
1968         list_del_rcu(&srcdev->dev_list);
1969         list_del_rcu(&srcdev->dev_alloc_list);
1970         fs_devices->num_devices--;
1971         if (srcdev->missing)
1972                 fs_devices->missing_devices--;
1973
1974         if (srcdev->writeable) {
1975                 fs_devices->rw_devices--;
1976                 /* zero out the old super if it is writable */
1977                 btrfs_scratch_superblocks(srcdev->bdev, srcdev->name->str);
1978         }
1979
1980         if (srcdev->bdev)
1981                 fs_devices->open_devices--;
1982 }
1983
1984 void btrfs_rm_dev_replace_free_srcdev(struct btrfs_fs_info *fs_info,
1985                                       struct btrfs_device *srcdev)
1986 {
1987         struct btrfs_fs_devices *fs_devices = srcdev->fs_devices;
1988
1989         call_rcu(&srcdev->rcu, free_device);
1990
1991         /*
1992          * unless fs_devices is seed fs, num_devices shouldn't go
1993          * zero
1994          */
1995         BUG_ON(!fs_devices->num_devices && !fs_devices->seeding);
1996
1997         /* if this is no devs we rather delete the fs_devices */
1998         if (!fs_devices->num_devices) {
1999                 struct btrfs_fs_devices *tmp_fs_devices;
2000
2001                 tmp_fs_devices = fs_info->fs_devices;
2002                 while (tmp_fs_devices) {
2003                         if (tmp_fs_devices->seed == fs_devices) {
2004                                 tmp_fs_devices->seed = fs_devices->seed;
2005                                 break;
2006                         }
2007                         tmp_fs_devices = tmp_fs_devices->seed;
2008                 }
2009                 fs_devices->seed = NULL;
2010                 __btrfs_close_devices(fs_devices);
2011                 free_fs_devices(fs_devices);
2012         }
2013 }
2014
2015 void btrfs_destroy_dev_replace_tgtdev(struct btrfs_fs_info *fs_info,
2016                                       struct btrfs_device *tgtdev)
2017 {
2018         struct btrfs_device *next_device;
2019
2020         mutex_lock(&uuid_mutex);
2021         WARN_ON(!tgtdev);
2022         mutex_lock(&fs_info->fs_devices->device_list_mutex);
2023
2024         btrfs_sysfs_rm_device_link(fs_info->fs_devices, tgtdev);
2025
2026         if (tgtdev->bdev) {
2027                 btrfs_scratch_superblocks(tgtdev->bdev, tgtdev->name->str);
2028                 fs_info->fs_devices->open_devices--;
2029         }
2030         fs_info->fs_devices->num_devices--;
2031
2032         next_device = list_entry(fs_info->fs_devices->devices.next,
2033                                  struct btrfs_device, dev_list);
2034         if (tgtdev->bdev == fs_info->sb->s_bdev)
2035                 fs_info->sb->s_bdev = next_device->bdev;
2036         if (tgtdev->bdev == fs_info->fs_devices->latest_bdev)
2037                 fs_info->fs_devices->latest_bdev = next_device->bdev;
2038         list_del_rcu(&tgtdev->dev_list);
2039
2040         call_rcu(&tgtdev->rcu, free_device);
2041
2042         mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2043         mutex_unlock(&uuid_mutex);
2044 }
2045
2046 static int btrfs_find_device_by_path(struct btrfs_root *root, char *device_path,
2047                                      struct btrfs_device **device)
2048 {
2049         int ret = 0;
2050         struct btrfs_super_block *disk_super;
2051         u64 devid;
2052         u8 *dev_uuid;
2053         struct block_device *bdev;
2054         struct buffer_head *bh;
2055
2056         *device = NULL;
2057         ret = btrfs_get_bdev_and_sb(device_path, FMODE_READ,
2058                                     root->fs_info->bdev_holder, 0, &bdev, &bh);
2059         if (ret)
2060                 return ret;
2061         disk_super = (struct btrfs_super_block *)bh->b_data;
2062         devid = btrfs_stack_device_id(&disk_super->dev_item);
2063         dev_uuid = disk_super->dev_item.uuid;
2064         *device = btrfs_find_device(root->fs_info, devid, dev_uuid,
2065                                     disk_super->fsid);
2066         brelse(bh);
2067         if (!*device)
2068                 ret = -ENOENT;
2069         blkdev_put(bdev, FMODE_READ);
2070         return ret;
2071 }
2072
2073 int btrfs_find_device_missing_or_by_path(struct btrfs_root *root,
2074                                          char *device_path,
2075                                          struct btrfs_device **device)
2076 {
2077         *device = NULL;
2078         if (strcmp(device_path, "missing") == 0) {
2079                 struct list_head *devices;
2080                 struct btrfs_device *tmp;
2081
2082                 devices = &root->fs_info->fs_devices->devices;
2083                 /*
2084                  * It is safe to read the devices since the volume_mutex
2085                  * is held by the caller.
2086                  */
2087                 list_for_each_entry(tmp, devices, dev_list) {
2088                         if (tmp->in_fs_metadata && !tmp->bdev) {
2089                                 *device = tmp;
2090                                 break;
2091                         }
2092                 }
2093
2094                 if (!*device)
2095                         return BTRFS_ERROR_DEV_MISSING_NOT_FOUND;
2096
2097                 return 0;
2098         } else {
2099                 return btrfs_find_device_by_path(root, device_path, device);
2100         }
2101 }
2102
2103 int btrfs_find_device_by_user_input(struct btrfs_root *root, u64 srcdevid,
2104                                          char *srcdev_name,
2105                                          struct btrfs_device **device)
2106 {
2107         int ret;
2108
2109         if (srcdevid) {
2110                 ret = 0;
2111                 *device = btrfs_find_device(root->fs_info, srcdevid, NULL,
2112                                             NULL);
2113                 if (!*device)
2114                         ret = -ENOENT;
2115         } else {
2116                 if (!srcdev_name || !srcdev_name[0])
2117                         return -EINVAL;
2118
2119                 ret = btrfs_find_device_missing_or_by_path(root, srcdev_name,
2120                                                            device);
2121         }
2122         return ret;
2123 }
2124
2125 /*
2126  * does all the dirty work required for changing file system's UUID.
2127  */
2128 static int btrfs_prepare_sprout(struct btrfs_root *root)
2129 {
2130         struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
2131         struct btrfs_fs_devices *old_devices;
2132         struct btrfs_fs_devices *seed_devices;
2133         struct btrfs_super_block *disk_super = root->fs_info->super_copy;
2134         struct btrfs_device *device;
2135         u64 super_flags;
2136
2137         BUG_ON(!mutex_is_locked(&uuid_mutex));
2138         if (!fs_devices->seeding)
2139                 return -EINVAL;
2140
2141         seed_devices = __alloc_fs_devices();
2142         if (IS_ERR(seed_devices))
2143                 return PTR_ERR(seed_devices);
2144
2145         old_devices = clone_fs_devices(fs_devices);
2146         if (IS_ERR(old_devices)) {
2147                 kfree(seed_devices);
2148                 return PTR_ERR(old_devices);
2149         }
2150
2151         list_add(&old_devices->list, &fs_uuids);
2152
2153         memcpy(seed_devices, fs_devices, sizeof(*seed_devices));
2154         seed_devices->opened = 1;
2155         INIT_LIST_HEAD(&seed_devices->devices);
2156         INIT_LIST_HEAD(&seed_devices->alloc_list);
2157         mutex_init(&seed_devices->device_list_mutex);
2158
2159         mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
2160         list_splice_init_rcu(&fs_devices->devices, &seed_devices->devices,
2161                               synchronize_rcu);
2162         list_for_each_entry(device, &seed_devices->devices, dev_list)
2163                 device->fs_devices = seed_devices;
2164
2165         lock_chunks(root);
2166         list_splice_init(&fs_devices->alloc_list, &seed_devices->alloc_list);
2167         unlock_chunks(root);
2168
2169         fs_devices->seeding = 0;
2170         fs_devices->num_devices = 0;
2171         fs_devices->open_devices = 0;
2172         fs_devices->missing_devices = 0;
2173         fs_devices->rotating = 0;
2174         fs_devices->seed = seed_devices;
2175
2176         generate_random_uuid(fs_devices->fsid);
2177         memcpy(root->fs_info->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
2178         memcpy(disk_super->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
2179         mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
2180
2181         super_flags = btrfs_super_flags(disk_super) &
2182                       ~BTRFS_SUPER_FLAG_SEEDING;
2183         btrfs_set_super_flags(disk_super, super_flags);
2184
2185         return 0;
2186 }
2187
2188 /*
2189  * strore the expected generation for seed devices in device items.
2190  */
2191 static int btrfs_finish_sprout(struct btrfs_trans_handle *trans,
2192                                struct btrfs_root *root)
2193 {
2194         struct btrfs_path *path;
2195         struct extent_buffer *leaf;
2196         struct btrfs_dev_item *dev_item;
2197         struct btrfs_device *device;
2198         struct btrfs_key key;
2199         u8 fs_uuid[BTRFS_UUID_SIZE];
2200         u8 dev_uuid[BTRFS_UUID_SIZE];
2201         u64 devid;
2202         int ret;
2203
2204         path = btrfs_alloc_path();
2205         if (!path)
2206                 return -ENOMEM;
2207
2208         root = root->fs_info->chunk_root;
2209         key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2210         key.offset = 0;
2211         key.type = BTRFS_DEV_ITEM_KEY;
2212
2213         while (1) {
2214                 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2215                 if (ret < 0)
2216                         goto error;
2217
2218                 leaf = path->nodes[0];
2219 next_slot:
2220                 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
2221                         ret = btrfs_next_leaf(root, path);
2222                         if (ret > 0)
2223                                 break;
2224                         if (ret < 0)
2225                                 goto error;
2226                         leaf = path->nodes[0];
2227                         btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2228                         btrfs_release_path(path);
2229                         continue;
2230                 }
2231
2232                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2233                 if (key.objectid != BTRFS_DEV_ITEMS_OBJECTID ||
2234                     key.type != BTRFS_DEV_ITEM_KEY)
2235                         break;
2236
2237                 dev_item = btrfs_item_ptr(leaf, path->slots[0],
2238                                           struct btrfs_dev_item);
2239                 devid = btrfs_device_id(leaf, dev_item);
2240                 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
2241                                    BTRFS_UUID_SIZE);
2242                 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
2243                                    BTRFS_UUID_SIZE);
2244                 device = btrfs_find_device(root->fs_info, devid, dev_uuid,
2245                                            fs_uuid);
2246                 BUG_ON(!device); /* Logic error */
2247
2248                 if (device->fs_devices->seeding) {
2249                         btrfs_set_device_generation(leaf, dev_item,
2250                                                     device->generation);
2251                         btrfs_mark_buffer_dirty(leaf);
2252                 }
2253
2254                 path->slots[0]++;
2255                 goto next_slot;
2256         }
2257         ret = 0;
2258 error:
2259         btrfs_free_path(path);
2260         return ret;
2261 }
2262
2263 int btrfs_init_new_device(struct btrfs_root *root, char *device_path)
2264 {
2265         struct request_queue *q;
2266         struct btrfs_trans_handle *trans;
2267         struct btrfs_device *device;
2268         struct block_device *bdev;
2269         struct list_head *devices;
2270         struct super_block *sb = root->fs_info->sb;
2271         struct rcu_string *name;
2272         u64 tmp;
2273         int seeding_dev = 0;
2274         int ret = 0;
2275
2276         if ((sb->s_flags & MS_RDONLY) && !root->fs_info->fs_devices->seeding)
2277                 return -EROFS;
2278
2279         bdev = blkdev_get_by_path(device_path, FMODE_WRITE | FMODE_EXCL,
2280                                   root->fs_info->bdev_holder);
2281         if (IS_ERR(bdev))
2282                 return PTR_ERR(bdev);
2283
2284         if (root->fs_info->fs_devices->seeding) {
2285                 seeding_dev = 1;
2286                 down_write(&sb->s_umount);
2287                 mutex_lock(&uuid_mutex);
2288         }
2289
2290         filemap_write_and_wait(bdev->bd_inode->i_mapping);
2291
2292         devices = &root->fs_info->fs_devices->devices;
2293
2294         mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
2295         list_for_each_entry(device, devices, dev_list) {
2296                 if (device->bdev == bdev) {
2297                         ret = -EEXIST;
2298                         mutex_unlock(
2299                                 &root->fs_info->fs_devices->device_list_mutex);
2300                         goto error;
2301                 }
2302         }
2303         mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
2304
2305         device = btrfs_alloc_device(root->fs_info, NULL, NULL);
2306         if (IS_ERR(device)) {
2307                 /* we can safely leave the fs_devices entry around */
2308                 ret = PTR_ERR(device);
2309                 goto error;
2310         }
2311
2312         name = rcu_string_strdup(device_path, GFP_KERNEL);
2313         if (!name) {
2314                 kfree(device);
2315                 ret = -ENOMEM;
2316                 goto error;
2317         }
2318         rcu_assign_pointer(device->name, name);
2319
2320         trans = btrfs_start_transaction(root, 0);
2321         if (IS_ERR(trans)) {
2322                 rcu_string_free(device->name);
2323                 kfree(device);
2324                 ret = PTR_ERR(trans);
2325                 goto error;
2326         }
2327
2328         q = bdev_get_queue(bdev);
2329         if (blk_queue_discard(q))
2330                 device->can_discard = 1;
2331         device->writeable = 1;
2332         device->generation = trans->transid;
2333         device->io_width = root->sectorsize;
2334         device->io_align = root->sectorsize;
2335         device->sector_size = root->sectorsize;
2336         device->total_bytes = i_size_read(bdev->bd_inode);
2337         device->disk_total_bytes = device->total_bytes;
2338         device->commit_total_bytes = device->total_bytes;
2339         device->dev_root = root->fs_info->dev_root;
2340         device->bdev = bdev;
2341         device->in_fs_metadata = 1;
2342         device->is_tgtdev_for_dev_replace = 0;
2343         device->mode = FMODE_EXCL;
2344         device->dev_stats_valid = 1;
2345         set_blocksize(device->bdev, 4096);
2346
2347         if (seeding_dev) {
2348                 sb->s_flags &= ~MS_RDONLY;
2349                 ret = btrfs_prepare_sprout(root);
2350                 BUG_ON(ret); /* -ENOMEM */
2351         }
2352
2353         device->fs_devices = root->fs_info->fs_devices;
2354
2355         mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
2356         lock_chunks(root);
2357         list_add_rcu(&device->dev_list, &root->fs_info->fs_devices->devices);
2358         list_add(&device->dev_alloc_list,
2359                  &root->fs_info->fs_devices->alloc_list);
2360         root->fs_info->fs_devices->num_devices++;
2361         root->fs_info->fs_devices->open_devices++;
2362         root->fs_info->fs_devices->rw_devices++;
2363         root->fs_info->fs_devices->total_devices++;
2364         root->fs_info->fs_devices->total_rw_bytes += device->total_bytes;
2365
2366         spin_lock(&root->fs_info->free_chunk_lock);
2367         root->fs_info->free_chunk_space += device->total_bytes;
2368         spin_unlock(&root->fs_info->free_chunk_lock);
2369
2370         if (!blk_queue_nonrot(bdev_get_queue(bdev)))
2371                 root->fs_info->fs_devices->rotating = 1;
2372
2373         tmp = btrfs_super_total_bytes(root->fs_info->super_copy);
2374         btrfs_set_super_total_bytes(root->fs_info->super_copy,
2375                                     tmp + device->total_bytes);
2376
2377         tmp = btrfs_super_num_devices(root->fs_info->super_copy);
2378         btrfs_set_super_num_devices(root->fs_info->super_copy,
2379                                     tmp + 1);
2380
2381         /* add sysfs device entry */
2382         btrfs_sysfs_add_device_link(root->fs_info->fs_devices, device);
2383
2384         /*
2385          * we've got more storage, clear any full flags on the space
2386          * infos
2387          */
2388         btrfs_clear_space_info_full(root->fs_info);
2389
2390         unlock_chunks(root);
2391         mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
2392
2393         if (seeding_dev) {
2394                 lock_chunks(root);
2395                 ret = init_first_rw_device(trans, root, device);
2396                 unlock_chunks(root);
2397                 if (ret) {
2398                         btrfs_abort_transaction(trans, root, ret);
2399                         goto error_trans;
2400                 }
2401         }
2402
2403         ret = btrfs_add_device(trans, root, device);
2404         if (ret) {
2405                 btrfs_abort_transaction(trans, root, ret);
2406                 goto error_trans;
2407         }
2408
2409         if (seeding_dev) {
2410                 char fsid_buf[BTRFS_UUID_UNPARSED_SIZE];
2411
2412                 ret = btrfs_finish_sprout(trans, root);
2413                 if (ret) {
2414                         btrfs_abort_transaction(trans, root, ret);
2415                         goto error_trans;
2416                 }
2417
2418                 /* Sprouting would change fsid of the mounted root,
2419                  * so rename the fsid on the sysfs
2420                  */
2421                 snprintf(fsid_buf, BTRFS_UUID_UNPARSED_SIZE, "%pU",
2422                                                 root->fs_info->fsid);
2423                 if (kobject_rename(&root->fs_info->fs_devices->fsid_kobj,
2424                                                                 fsid_buf))
2425                         btrfs_warn(root->fs_info,
2426                                 "sysfs: failed to create fsid for sprout");
2427         }
2428
2429         root->fs_info->num_tolerated_disk_barrier_failures =
2430                 btrfs_calc_num_tolerated_disk_barrier_failures(root->fs_info);
2431         ret = btrfs_commit_transaction(trans, root);
2432
2433         if (seeding_dev) {
2434                 mutex_unlock(&uuid_mutex);
2435                 up_write(&sb->s_umount);
2436
2437                 if (ret) /* transaction commit */
2438                         return ret;
2439
2440                 ret = btrfs_relocate_sys_chunks(root);
2441                 if (ret < 0)
2442                         btrfs_std_error(root->fs_info, ret,
2443                                     "Failed to relocate sys chunks after "
2444                                     "device initialization. This can be fixed "
2445                                     "using the \"btrfs balance\" command.");
2446                 trans = btrfs_attach_transaction(root);
2447                 if (IS_ERR(trans)) {
2448                         if (PTR_ERR(trans) == -ENOENT)
2449                                 return 0;
2450                         return PTR_ERR(trans);
2451                 }
2452                 ret = btrfs_commit_transaction(trans, root);
2453         }
2454
2455         /* Update ctime/mtime for libblkid */
2456         update_dev_time(device_path);
2457         return ret;
2458
2459 error_trans:
2460         btrfs_end_transaction(trans, root);
2461         rcu_string_free(device->name);
2462         btrfs_sysfs_rm_device_link(root->fs_info->fs_devices, device);
2463         kfree(device);
2464 error:
2465         blkdev_put(bdev, FMODE_EXCL);
2466         if (seeding_dev) {
2467                 mutex_unlock(&uuid_mutex);
2468                 up_write(&sb->s_umount);
2469         }
2470         return ret;
2471 }
2472
2473 int btrfs_init_dev_replace_tgtdev(struct btrfs_root *root, char *device_path,
2474                                   struct btrfs_device *srcdev,
2475                                   struct btrfs_device **device_out)
2476 {
2477         struct request_queue *q;
2478         struct btrfs_device *device;
2479         struct block_device *bdev;
2480         struct btrfs_fs_info *fs_info = root->fs_info;
2481         struct list_head *devices;
2482         struct rcu_string *name;
2483         u64 devid = BTRFS_DEV_REPLACE_DEVID;
2484         int ret = 0;
2485
2486         *device_out = NULL;
2487         if (fs_info->fs_devices->seeding) {
2488                 btrfs_err(fs_info, "the filesystem is a seed filesystem!");
2489                 return -EINVAL;
2490         }
2491
2492         bdev = blkdev_get_by_path(device_path, FMODE_WRITE | FMODE_EXCL,
2493                                   fs_info->bdev_holder);
2494         if (IS_ERR(bdev)) {
2495                 btrfs_err(fs_info, "target device %s is invalid!", device_path);
2496                 return PTR_ERR(bdev);
2497         }
2498
2499         filemap_write_and_wait(bdev->bd_inode->i_mapping);
2500
2501         devices = &fs_info->fs_devices->devices;
2502         list_for_each_entry(device, devices, dev_list) {
2503                 if (device->bdev == bdev) {
2504                         btrfs_err(fs_info, "target device is in the filesystem!");
2505                         ret = -EEXIST;
2506                         goto error;
2507                 }
2508         }
2509
2510
2511         if (i_size_read(bdev->bd_inode) <
2512             btrfs_device_get_total_bytes(srcdev)) {
2513                 btrfs_err(fs_info, "target device is smaller than source device!");
2514                 ret = -EINVAL;
2515                 goto error;
2516         }
2517
2518
2519         device = btrfs_alloc_device(NULL, &devid, NULL);
2520         if (IS_ERR(device)) {
2521                 ret = PTR_ERR(device);
2522                 goto error;
2523         }
2524
2525         name = rcu_string_strdup(device_path, GFP_NOFS);
2526         if (!name) {
2527                 kfree(device);
2528                 ret = -ENOMEM;
2529                 goto error;
2530         }
2531         rcu_assign_pointer(device->name, name);
2532
2533         q = bdev_get_queue(bdev);
2534         if (blk_queue_discard(q))
2535                 device->can_discard = 1;
2536         mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
2537         device->writeable = 1;
2538         device->generation = 0;
2539         device->io_width = root->sectorsize;
2540         device->io_align = root->sectorsize;
2541         device->sector_size = root->sectorsize;
2542         device->total_bytes = btrfs_device_get_total_bytes(srcdev);
2543         device->disk_total_bytes = btrfs_device_get_disk_total_bytes(srcdev);
2544         device->bytes_used = btrfs_device_get_bytes_used(srcdev);
2545         ASSERT(list_empty(&srcdev->resized_list));
2546         device->commit_total_bytes = srcdev->commit_total_bytes;
2547         device->commit_bytes_used = device->bytes_used;
2548         device->dev_root = fs_info->dev_root;
2549         device->bdev = bdev;
2550         device->in_fs_metadata = 1;
2551         device->is_tgtdev_for_dev_replace = 1;
2552         device->mode = FMODE_EXCL;
2553         device->dev_stats_valid = 1;
2554         set_blocksize(device->bdev, 4096);
2555         device->fs_devices = fs_info->fs_devices;
2556         list_add(&device->dev_list, &fs_info->fs_devices->devices);
2557         fs_info->fs_devices->num_devices++;
2558         fs_info->fs_devices->open_devices++;
2559         mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
2560
2561         *device_out = device;
2562         return ret;
2563
2564 error:
2565         blkdev_put(bdev, FMODE_EXCL);
2566         return ret;
2567 }
2568
2569 void btrfs_init_dev_replace_tgtdev_for_resume(struct btrfs_fs_info *fs_info,
2570                                               struct btrfs_device *tgtdev)
2571 {
2572         WARN_ON(fs_info->fs_devices->rw_devices == 0);
2573         tgtdev->io_width = fs_info->dev_root->sectorsize;
2574         tgtdev->io_align = fs_info->dev_root->sectorsize;
2575         tgtdev->sector_size = fs_info->dev_root->sectorsize;
2576         tgtdev->dev_root = fs_info->dev_root;
2577         tgtdev->in_fs_metadata = 1;
2578 }
2579
2580 static noinline int btrfs_update_device(struct btrfs_trans_handle *trans,
2581                                         struct btrfs_device *device)
2582 {
2583         int ret;
2584         struct btrfs_path *path;
2585         struct btrfs_root *root;
2586         struct btrfs_dev_item *dev_item;
2587         struct extent_buffer *leaf;
2588         struct btrfs_key key;
2589
2590         root = device->dev_root->fs_info->chunk_root;
2591
2592         path = btrfs_alloc_path();
2593         if (!path)
2594                 return -ENOMEM;
2595
2596         key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2597         key.type = BTRFS_DEV_ITEM_KEY;
2598         key.offset = device->devid;
2599
2600         ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2601         if (ret < 0)
2602                 goto out;
2603
2604         if (ret > 0) {
2605                 ret = -ENOENT;
2606                 goto out;
2607         }
2608
2609         leaf = path->nodes[0];
2610         dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
2611
2612         btrfs_set_device_id(leaf, dev_item, device->devid);
2613         btrfs_set_device_type(leaf, dev_item, device->type);
2614         btrfs_set_device_io_align(leaf, dev_item, device->io_align);
2615         btrfs_set_device_io_width(leaf, dev_item, device->io_width);
2616         btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
2617         btrfs_set_device_total_bytes(leaf, dev_item,
2618                                      btrfs_device_get_disk_total_bytes(device));
2619         btrfs_set_device_bytes_used(leaf, dev_item,
2620                                     btrfs_device_get_bytes_used(device));
2621         btrfs_mark_buffer_dirty(leaf);
2622
2623 out:
2624         btrfs_free_path(path);
2625         return ret;
2626 }
2627
2628 int btrfs_grow_device(struct btrfs_trans_handle *trans,
2629                       struct btrfs_device *device, u64 new_size)
2630 {
2631         struct btrfs_super_block *super_copy =
2632                 device->dev_root->fs_info->super_copy;
2633         struct btrfs_fs_devices *fs_devices;
2634         u64 old_total;
2635         u64 diff;
2636
2637         if (!device->writeable)
2638                 return -EACCES;
2639
2640         lock_chunks(device->dev_root);
2641         old_total = btrfs_super_total_bytes(super_copy);
2642         diff = new_size - device->total_bytes;
2643
2644         if (new_size <= device->total_bytes ||
2645             device->is_tgtdev_for_dev_replace) {
2646                 unlock_chunks(device->dev_root);
2647                 return -EINVAL;
2648         }
2649
2650         fs_devices = device->dev_root->fs_info->fs_devices;
2651
2652         btrfs_set_super_total_bytes(super_copy, old_total + diff);
2653         device->fs_devices->total_rw_bytes += diff;
2654
2655         btrfs_device_set_total_bytes(device, new_size);
2656         btrfs_device_set_disk_total_bytes(device, new_size);
2657         btrfs_clear_space_info_full(device->dev_root->fs_info);
2658         if (list_empty(&device->resized_list))
2659                 list_add_tail(&device->resized_list,
2660                               &fs_devices->resized_devices);
2661         unlock_chunks(device->dev_root);
2662
2663         return btrfs_update_device(trans, device);
2664 }
2665
2666 static int btrfs_free_chunk(struct btrfs_trans_handle *trans,
2667                             struct btrfs_root *root, u64 chunk_objectid,
2668                             u64 chunk_offset)
2669 {
2670         int ret;
2671         struct btrfs_path *path;
2672         struct btrfs_key key;
2673
2674         root = root->fs_info->chunk_root;
2675         path = btrfs_alloc_path();
2676         if (!path)
2677                 return -ENOMEM;
2678
2679         key.objectid = chunk_objectid;
2680         key.offset = chunk_offset;
2681         key.type = BTRFS_CHUNK_ITEM_KEY;
2682
2683         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
2684         if (ret < 0)
2685                 goto out;
2686         else if (ret > 0) { /* Logic error or corruption */
2687                 btrfs_std_error(root->fs_info, -ENOENT,
2688                             "Failed lookup while freeing chunk.");
2689                 ret = -ENOENT;
2690                 goto out;
2691         }
2692
2693         ret = btrfs_del_item(trans, root, path);
2694         if (ret < 0)
2695                 btrfs_std_error(root->fs_info, ret,
2696                             "Failed to delete chunk item.");
2697 out:
2698         btrfs_free_path(path);
2699         return ret;
2700 }
2701
2702 static int btrfs_del_sys_chunk(struct btrfs_root *root, u64 chunk_objectid, u64
2703                         chunk_offset)
2704 {
2705         struct btrfs_super_block *super_copy = root->fs_info->super_copy;
2706         struct btrfs_disk_key *disk_key;
2707         struct btrfs_chunk *chunk;
2708         u8 *ptr;
2709         int ret = 0;
2710         u32 num_stripes;
2711         u32 array_size;
2712         u32 len = 0;
2713         u32 cur;
2714         struct btrfs_key key;
2715
2716         lock_chunks(root);
2717         array_size = btrfs_super_sys_array_size(super_copy);
2718
2719         ptr = super_copy->sys_chunk_array;
2720         cur = 0;
2721
2722         while (cur < array_size) {
2723                 disk_key = (struct btrfs_disk_key *)ptr;
2724                 btrfs_disk_key_to_cpu(&key, disk_key);
2725
2726                 len = sizeof(*disk_key);
2727
2728                 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
2729                         chunk = (struct btrfs_chunk *)(ptr + len);
2730                         num_stripes = btrfs_stack_chunk_num_stripes(chunk);
2731                         len += btrfs_chunk_item_size(num_stripes);
2732                 } else {
2733                         ret = -EIO;
2734                         break;
2735                 }
2736                 if (key.objectid == chunk_objectid &&
2737                     key.offset == chunk_offset) {
2738                         memmove(ptr, ptr + len, array_size - (cur + len));
2739                         array_size -= len;
2740                         btrfs_set_super_sys_array_size(super_copy, array_size);
2741                 } else {
2742                         ptr += len;
2743                         cur += len;
2744                 }
2745         }
2746         unlock_chunks(root);
2747         return ret;
2748 }
2749
2750 int btrfs_remove_chunk(struct btrfs_trans_handle *trans,
2751                        struct btrfs_root *root, u64 chunk_offset)
2752 {
2753         struct extent_map_tree *em_tree;
2754         struct extent_map *em;
2755         struct btrfs_root *extent_root = root->fs_info->extent_root;
2756         struct map_lookup *map;
2757         u64 dev_extent_len = 0;
2758         u64 chunk_objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2759         int i, ret = 0;
2760
2761         /* Just in case */
2762         root = root->fs_info->chunk_root;
2763         em_tree = &root->fs_info->mapping_tree.map_tree;
2764
2765         read_lock(&em_tree->lock);
2766         em = lookup_extent_mapping(em_tree, chunk_offset, 1);
2767         read_unlock(&em_tree->lock);
2768
2769         if (!em || em->start > chunk_offset ||
2770             em->start + em->len < chunk_offset) {
2771                 /*
2772                  * This is a logic error, but we don't want to just rely on the
2773                  * user having built with ASSERT enabled, so if ASSERT doesn't
2774                  * do anything we still error out.
2775                  */
2776                 ASSERT(0);
2777                 if (em)
2778                         free_extent_map(em);
2779                 return -EINVAL;
2780         }
2781         map = em->map_lookup;
2782         lock_chunks(root->fs_info->chunk_root);
2783         check_system_chunk(trans, extent_root, map->type);
2784         unlock_chunks(root->fs_info->chunk_root);
2785
2786         for (i = 0; i < map->num_stripes; i++) {
2787                 struct btrfs_device *device = map->stripes[i].dev;
2788                 ret = btrfs_free_dev_extent(trans, device,
2789                                             map->stripes[i].physical,
2790                                             &dev_extent_len);
2791                 if (ret) {
2792                         btrfs_abort_transaction(trans, root, ret);
2793                         goto out;
2794                 }
2795
2796                 if (device->bytes_used > 0) {
2797                         lock_chunks(root);
2798                         btrfs_device_set_bytes_used(device,
2799                                         device->bytes_used - dev_extent_len);
2800                         spin_lock(&root->fs_info->free_chunk_lock);
2801                         root->fs_info->free_chunk_space += dev_extent_len;
2802                         spin_unlock(&root->fs_info->free_chunk_lock);
2803                         btrfs_clear_space_info_full(root->fs_info);
2804                         unlock_chunks(root);
2805                 }
2806
2807                 if (map->stripes[i].dev) {
2808                         ret = btrfs_update_device(trans, map->stripes[i].dev);
2809                         if (ret) {
2810                                 btrfs_abort_transaction(trans, root, ret);
2811                                 goto out;
2812                         }
2813                 }
2814         }
2815         ret = btrfs_free_chunk(trans, root, chunk_objectid, chunk_offset);
2816         if (ret) {
2817                 btrfs_abort_transaction(trans, root, ret);
2818                 goto out;
2819         }
2820
2821         trace_btrfs_chunk_free(root, map, chunk_offset, em->len);
2822
2823         if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
2824                 ret = btrfs_del_sys_chunk(root, chunk_objectid, chunk_offset);
2825                 if (ret) {
2826                         btrfs_abort_transaction(trans, root, ret);
2827                         goto out;
2828                 }
2829         }
2830
2831         ret = btrfs_remove_block_group(trans, extent_root, chunk_offset, em);
2832         if (ret) {
2833                 btrfs_abort_transaction(trans, extent_root, ret);
2834                 goto out;
2835         }
2836
2837 out:
2838         /* once for us */
2839         free_extent_map(em);
2840         return ret;
2841 }
2842
2843 static int btrfs_relocate_chunk(struct btrfs_root *root, u64 chunk_offset)
2844 {
2845         struct btrfs_root *extent_root;
2846         struct btrfs_trans_handle *trans;
2847         int ret;
2848
2849         root = root->fs_info->chunk_root;
2850         extent_root = root->fs_info->extent_root;
2851
2852         /*
2853          * Prevent races with automatic removal of unused block groups.
2854          * After we relocate and before we remove the chunk with offset
2855          * chunk_offset, automatic removal of the block group can kick in,
2856          * resulting in a failure when calling btrfs_remove_chunk() below.
2857          *
2858          * Make sure to acquire this mutex before doing a tree search (dev
2859          * or chunk trees) to find chunks. Otherwise the cleaner kthread might
2860          * call btrfs_remove_chunk() (through btrfs_delete_unused_bgs()) after
2861          * we release the path used to search the chunk/dev tree and before
2862          * the current task acquires this mutex and calls us.
2863          */
2864         ASSERT(mutex_is_locked(&root->fs_info->delete_unused_bgs_mutex));
2865
2866         ret = btrfs_can_relocate(extent_root, chunk_offset);
2867         if (ret)
2868                 return -ENOSPC;
2869
2870         /* step one, relocate all the extents inside this chunk */
2871         btrfs_scrub_pause(root);
2872         ret = btrfs_relocate_block_group(extent_root, chunk_offset);
2873         btrfs_scrub_continue(root);
2874         if (ret)
2875                 return ret;
2876
2877         trans = btrfs_start_trans_remove_block_group(root->fs_info,
2878                                                      chunk_offset);
2879         if (IS_ERR(trans)) {
2880                 ret = PTR_ERR(trans);
2881                 btrfs_std_error(root->fs_info, ret, NULL);
2882                 return ret;
2883         }
2884
2885         /*
2886          * step two, delete the device extents and the
2887          * chunk tree entries
2888          */
2889         ret = btrfs_remove_chunk(trans, root, chunk_offset);
2890         btrfs_end_transaction(trans, root);
2891         return ret;
2892 }
2893
2894 static int btrfs_relocate_sys_chunks(struct btrfs_root *root)
2895 {
2896         struct btrfs_root *chunk_root = root->fs_info->chunk_root;
2897         struct btrfs_path *path;
2898         struct extent_buffer *leaf;
2899         struct btrfs_chunk *chunk;
2900         struct btrfs_key key;
2901         struct btrfs_key found_key;
2902         u64 chunk_type;
2903         bool retried = false;
2904         int failed = 0;
2905         int ret;
2906
2907         path = btrfs_alloc_path();
2908         if (!path)
2909                 return -ENOMEM;
2910
2911 again:
2912         key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2913         key.offset = (u64)-1;
2914         key.type = BTRFS_CHUNK_ITEM_KEY;
2915
2916         while (1) {
2917                 mutex_lock(&root->fs_info->delete_unused_bgs_mutex);
2918                 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
2919                 if (ret < 0) {
2920                         mutex_unlock(&root->fs_info->delete_unused_bgs_mutex);
2921                         goto error;
2922                 }
2923                 BUG_ON(ret == 0); /* Corruption */
2924
2925                 ret = btrfs_previous_item(chunk_root, path, key.objectid,
2926                                           key.type);
2927                 if (ret)
2928                         mutex_unlock(&root->fs_info->delete_unused_bgs_mutex);
2929                 if (ret < 0)
2930                         goto error;
2931                 if (ret > 0)
2932                         break;
2933
2934                 leaf = path->nodes[0];
2935                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2936
2937                 chunk = btrfs_item_ptr(leaf, path->slots[0],
2938                                        struct btrfs_chunk);
2939                 chunk_type = btrfs_chunk_type(leaf, chunk);
2940                 btrfs_release_path(path);
2941
2942                 if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) {
2943                         ret = btrfs_relocate_chunk(chunk_root,
2944                                                    found_key.offset);
2945                         if (ret == -ENOSPC)
2946                                 failed++;
2947                         else
2948                                 BUG_ON(ret);
2949                 }
2950                 mutex_unlock(&root->fs_info->delete_unused_bgs_mutex);
2951
2952                 if (found_key.offset == 0)
2953                         break;
2954                 key.offset = found_key.offset - 1;
2955         }
2956         ret = 0;
2957         if (failed && !retried) {
2958                 failed = 0;
2959                 retried = true;
2960                 goto again;
2961         } else if (WARN_ON(failed && retried)) {
2962                 ret = -ENOSPC;
2963         }
2964 error:
2965         btrfs_free_path(path);
2966         return ret;
2967 }
2968
2969 static int insert_balance_item(struct btrfs_root *root,
2970                                struct btrfs_balance_control *bctl)
2971 {
2972         struct btrfs_trans_handle *trans;
2973         struct btrfs_balance_item *item;
2974         struct btrfs_disk_balance_args disk_bargs;
2975         struct btrfs_path *path;
2976         struct extent_buffer *leaf;
2977         struct btrfs_key key;
2978         int ret, err;
2979
2980         path = btrfs_alloc_path();
2981         if (!path)
2982                 return -ENOMEM;
2983
2984         trans = btrfs_start_transaction(root, 0);
2985         if (IS_ERR(trans)) {
2986                 btrfs_free_path(path);
2987                 return PTR_ERR(trans);
2988         }
2989
2990         key.objectid = BTRFS_BALANCE_OBJECTID;
2991         key.type = BTRFS_TEMPORARY_ITEM_KEY;
2992         key.offset = 0;
2993
2994         ret = btrfs_insert_empty_item(trans, root, path, &key,
2995                                       sizeof(*item));
2996         if (ret)
2997                 goto out;
2998
2999         leaf = path->nodes[0];
3000         item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
3001
3002         memset_extent_buffer(leaf, 0, (unsigned long)item, sizeof(*item));
3003
3004         btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->data);
3005         btrfs_set_balance_data(leaf, item, &disk_bargs);
3006         btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->meta);
3007         btrfs_set_balance_meta(leaf, item, &disk_bargs);
3008         btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->sys);
3009         btrfs_set_balance_sys(leaf, item, &disk_bargs);
3010
3011         btrfs_set_balance_flags(leaf, item, bctl->flags);
3012
3013         btrfs_mark_buffer_dirty(leaf);
3014 out:
3015         btrfs_free_path(path);
3016         err = btrfs_commit_transaction(trans, root);
3017         if (err && !ret)
3018                 ret = err;
3019         return ret;
3020 }
3021
3022 static int del_balance_item(struct btrfs_root *root)
3023 {
3024         struct btrfs_trans_handle *trans;
3025         struct btrfs_path *path;
3026         struct btrfs_key key;
3027         int ret, err;
3028
3029         path = btrfs_alloc_path();
3030         if (!path)
3031                 return -ENOMEM;
3032
3033         trans = btrfs_start_transaction(root, 0);
3034         if (IS_ERR(trans)) {
3035                 btrfs_free_path(path);
3036                 return PTR_ERR(trans);
3037         }
3038
3039         key.objectid = BTRFS_BALANCE_OBJECTID;
3040         key.type = BTRFS_TEMPORARY_ITEM_KEY;
3041         key.offset = 0;
3042
3043         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3044         if (ret < 0)
3045                 goto out;
3046         if (ret > 0) {
3047                 ret = -ENOENT;
3048                 goto out;
3049         }
3050
3051         ret = btrfs_del_item(trans, root, path);
3052 out:
3053         btrfs_free_path(path);
3054         err = btrfs_commit_transaction(trans, root);
3055         if (err && !ret)
3056                 ret = err;
3057         return ret;
3058 }
3059
3060 /*
3061  * This is a heuristic used to reduce the number of chunks balanced on
3062  * resume after balance was interrupted.
3063  */
3064 static void update_balance_args(struct btrfs_balance_control *bctl)
3065 {
3066         /*
3067          * Turn on soft mode for chunk types that were being converted.
3068          */
3069         if (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)
3070                 bctl->data.flags |= BTRFS_BALANCE_ARGS_SOFT;
3071         if (bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)
3072                 bctl->sys.flags |= BTRFS_BALANCE_ARGS_SOFT;
3073         if (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)
3074                 bctl->meta.flags |= BTRFS_BALANCE_ARGS_SOFT;
3075
3076         /*
3077          * Turn on usage filter if is not already used.  The idea is
3078          * that chunks that we have already balanced should be
3079          * reasonably full.  Don't do it for chunks that are being
3080          * converted - that will keep us from relocating unconverted
3081          * (albeit full) chunks.
3082          */
3083         if (!(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3084             !(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3085             !(bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3086                 bctl->data.flags |= BTRFS_BALANCE_ARGS_USAGE;
3087                 bctl->data.usage = 90;
3088         }
3089         if (!(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3090             !(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3091             !(bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3092                 bctl->sys.flags |= BTRFS_BALANCE_ARGS_USAGE;
3093                 bctl->sys.usage = 90;
3094         }
3095         if (!(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3096             !(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3097             !(bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3098                 bctl->meta.flags |= BTRFS_BALANCE_ARGS_USAGE;
3099                 bctl->meta.usage = 90;
3100         }
3101 }
3102
3103 /*
3104  * Should be called with both balance and volume mutexes held to
3105  * serialize other volume operations (add_dev/rm_dev/resize) with
3106  * restriper.  Same goes for unset_balance_control.
3107  */
3108 static void set_balance_control(struct btrfs_balance_control *bctl)
3109 {
3110         struct btrfs_fs_info *fs_info = bctl->fs_info;
3111
3112         BUG_ON(fs_info->balance_ctl);
3113
3114         spin_lock(&fs_info->balance_lock);
3115         fs_info->balance_ctl = bctl;
3116         spin_unlock(&fs_info->balance_lock);
3117 }
3118
3119 static void unset_balance_control(struct btrfs_fs_info *fs_info)
3120 {
3121         struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3122
3123         BUG_ON(!fs_info->balance_ctl);
3124
3125         spin_lock(&fs_info->balance_lock);
3126         fs_info->balance_ctl = NULL;
3127         spin_unlock(&fs_info->balance_lock);
3128
3129         kfree(bctl);
3130 }
3131
3132 /*
3133  * Balance filters.  Return 1 if chunk should be filtered out
3134  * (should not be balanced).
3135  */
3136 static int chunk_profiles_filter(u64 chunk_type,
3137                                  struct btrfs_balance_args *bargs)
3138 {
3139         chunk_type = chunk_to_extended(chunk_type) &
3140                                 BTRFS_EXTENDED_PROFILE_MASK;
3141
3142         if (bargs->profiles & chunk_type)
3143                 return 0;
3144
3145         return 1;
3146 }
3147
3148 static int chunk_usage_range_filter(struct btrfs_fs_info *fs_info, u64 chunk_offset,
3149                               struct btrfs_balance_args *bargs)
3150 {
3151         struct btrfs_block_group_cache *cache;
3152         u64 chunk_used;
3153         u64 user_thresh_min;
3154         u64 user_thresh_max;
3155         int ret = 1;
3156
3157         cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3158         chunk_used = btrfs_block_group_used(&cache->item);
3159
3160         if (bargs->usage_min == 0)
3161                 user_thresh_min = 0;
3162         else
3163                 user_thresh_min = div_factor_fine(cache->key.offset,
3164                                         bargs->usage_min);
3165
3166         if (bargs->usage_max == 0)
3167                 user_thresh_max = 1;
3168         else if (bargs->usage_max > 100)
3169                 user_thresh_max = cache->key.offset;
3170         else
3171                 user_thresh_max = div_factor_fine(cache->key.offset,
3172                                         bargs->usage_max);
3173
3174         if (user_thresh_min <= chunk_used && chunk_used < user_thresh_max)
3175                 ret = 0;
3176
3177         btrfs_put_block_group(cache);
3178         return ret;
3179 }
3180
3181 static int chunk_usage_filter(struct btrfs_fs_info *fs_info,
3182                 u64 chunk_offset, struct btrfs_balance_args *bargs)
3183 {
3184         struct btrfs_block_group_cache *cache;
3185         u64 chunk_used, user_thresh;
3186         int ret = 1;
3187
3188         cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3189         chunk_used = btrfs_block_group_used(&cache->item);
3190
3191         if (bargs->usage_min == 0)
3192                 user_thresh = 1;
3193         else if (bargs->usage > 100)
3194                 user_thresh = cache->key.offset;
3195         else
3196                 user_thresh = div_factor_fine(cache->key.offset,
3197                                               bargs->usage);
3198
3199         if (chunk_used < user_thresh)
3200                 ret = 0;
3201
3202         btrfs_put_block_group(cache);
3203         return ret;
3204 }
3205
3206 static int chunk_devid_filter(struct extent_buffer *leaf,
3207                               struct btrfs_chunk *chunk,
3208                               struct btrfs_balance_args *bargs)
3209 {
3210         struct btrfs_stripe *stripe;
3211         int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3212         int i;
3213
3214         for (i = 0; i < num_stripes; i++) {
3215                 stripe = btrfs_stripe_nr(chunk, i);
3216                 if (btrfs_stripe_devid(leaf, stripe) == bargs->devid)
3217                         return 0;
3218         }
3219
3220         return 1;
3221 }
3222
3223 /* [pstart, pend) */
3224 static int chunk_drange_filter(struct extent_buffer *leaf,
3225                                struct btrfs_chunk *chunk,
3226                                u64 chunk_offset,
3227                                struct btrfs_balance_args *bargs)
3228 {
3229         struct btrfs_stripe *stripe;
3230         int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3231         u64 stripe_offset;
3232         u64 stripe_length;
3233         int factor;
3234         int i;
3235
3236         if (!(bargs->flags & BTRFS_BALANCE_ARGS_DEVID))
3237                 return 0;
3238
3239         if (btrfs_chunk_type(leaf, chunk) & (BTRFS_BLOCK_GROUP_DUP |
3240              BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10)) {
3241                 factor = num_stripes / 2;
3242         } else if (btrfs_chunk_type(leaf, chunk) & BTRFS_BLOCK_GROUP_RAID5) {
3243                 factor = num_stripes - 1;
3244         } else if (btrfs_chunk_type(leaf, chunk) & BTRFS_BLOCK_GROUP_RAID6) {
3245                 factor = num_stripes - 2;
3246         } else {
3247                 factor = num_stripes;
3248         }
3249
3250         for (i = 0; i < num_stripes; i++) {
3251                 stripe = btrfs_stripe_nr(chunk, i);
3252                 if (btrfs_stripe_devid(leaf, stripe) != bargs->devid)
3253                         continue;
3254
3255                 stripe_offset = btrfs_stripe_offset(leaf, stripe);
3256                 stripe_length = btrfs_chunk_length(leaf, chunk);
3257                 stripe_length = div_u64(stripe_length, factor);
3258
3259                 if (stripe_offset < bargs->pend &&
3260                     stripe_offset + stripe_length > bargs->pstart)
3261                         return 0;
3262         }
3263
3264         return 1;
3265 }
3266
3267 /* [vstart, vend) */
3268 static int chunk_vrange_filter(struct extent_buffer *leaf,
3269                                struct btrfs_chunk *chunk,
3270                                u64 chunk_offset,
3271                                struct btrfs_balance_args *bargs)
3272 {
3273         if (chunk_offset < bargs->vend &&
3274             chunk_offset + btrfs_chunk_length(leaf, chunk) > bargs->vstart)
3275                 /* at least part of the chunk is inside this vrange */
3276                 return 0;
3277
3278         return 1;
3279 }
3280
3281 static int chunk_stripes_range_filter(struct extent_buffer *leaf,
3282                                struct btrfs_chunk *chunk,
3283                                struct btrfs_balance_args *bargs)
3284 {
3285         int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3286
3287         if (bargs->stripes_min <= num_stripes
3288                         && num_stripes <= bargs->stripes_max)
3289                 return 0;
3290
3291         return 1;
3292 }
3293
3294 static int chunk_soft_convert_filter(u64 chunk_type,
3295                                      struct btrfs_balance_args *bargs)
3296 {
3297         if (!(bargs->flags & BTRFS_BALANCE_ARGS_CONVERT))
3298                 return 0;
3299
3300         chunk_type = chunk_to_extended(chunk_type) &
3301                                 BTRFS_EXTENDED_PROFILE_MASK;
3302
3303         if (bargs->target == chunk_type)
3304                 return 1;
3305
3306         return 0;
3307 }
3308
3309 static int should_balance_chunk(struct btrfs_root *root,
3310                                 struct extent_buffer *leaf,
3311                                 struct btrfs_chunk *chunk, u64 chunk_offset)
3312 {
3313         struct btrfs_balance_control *bctl = root->fs_info->balance_ctl;
3314         struct btrfs_balance_args *bargs = NULL;
3315         u64 chunk_type = btrfs_chunk_type(leaf, chunk);
3316
3317         /* type filter */
3318         if (!((chunk_type & BTRFS_BLOCK_GROUP_TYPE_MASK) &
3319               (bctl->flags & BTRFS_BALANCE_TYPE_MASK))) {
3320                 return 0;
3321         }
3322
3323         if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
3324                 bargs = &bctl->data;
3325         else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
3326                 bargs = &bctl->sys;
3327         else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
3328                 bargs = &bctl->meta;
3329
3330         /* profiles filter */
3331         if ((bargs->flags & BTRFS_BALANCE_ARGS_PROFILES) &&
3332             chunk_profiles_filter(chunk_type, bargs)) {
3333                 return 0;
3334         }
3335
3336         /* usage filter */
3337         if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE) &&
3338             chunk_usage_filter(bctl->fs_info, chunk_offset, bargs)) {
3339                 return 0;
3340         } else if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3341             chunk_usage_range_filter(bctl->fs_info, chunk_offset, bargs)) {
3342                 return 0;
3343         }
3344
3345         /* devid filter */
3346         if ((bargs->flags & BTRFS_BALANCE_ARGS_DEVID) &&
3347             chunk_devid_filter(leaf, chunk, bargs)) {
3348                 return 0;
3349         }
3350
3351         /* drange filter, makes sense only with devid filter */
3352         if ((bargs->flags & BTRFS_BALANCE_ARGS_DRANGE) &&
3353             chunk_drange_filter(leaf, chunk, chunk_offset, bargs)) {
3354                 return 0;
3355         }
3356
3357         /* vrange filter */
3358         if ((bargs->flags & BTRFS_BALANCE_ARGS_VRANGE) &&
3359             chunk_vrange_filter(leaf, chunk, chunk_offset, bargs)) {
3360                 return 0;
3361         }
3362
3363         /* stripes filter */
3364         if ((bargs->flags & BTRFS_BALANCE_ARGS_STRIPES_RANGE) &&
3365             chunk_stripes_range_filter(leaf, chunk, bargs)) {
3366                 return 0;
3367         }
3368
3369         /* soft profile changing mode */
3370         if ((bargs->flags & BTRFS_BALANCE_ARGS_SOFT) &&
3371             chunk_soft_convert_filter(chunk_type, bargs)) {
3372                 return 0;
3373         }
3374
3375         /*
3376          * limited by count, must be the last filter
3377          */
3378         if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT)) {
3379                 if (bargs->limit == 0)
3380                         return 0;
3381                 else
3382                         bargs->limit--;
3383         } else if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT_RANGE)) {
3384                 /*
3385                  * Same logic as the 'limit' filter; the minimum cannot be
3386                  * determined here because we do not have the global informatoin
3387                  * about the count of all chunks that satisfy the filters.
3388                  */
3389                 if (bargs->limit_max == 0)
3390                         return 0;
3391                 else
3392                         bargs->limit_max--;
3393         }
3394
3395         return 1;
3396 }
3397
3398 static int __btrfs_balance(struct btrfs_fs_info *fs_info)
3399 {
3400         struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3401         struct btrfs_root *chunk_root = fs_info->chunk_root;
3402         struct btrfs_root *dev_root = fs_info->dev_root;
3403         struct list_head *devices;
3404         struct btrfs_device *device;
3405         u64 old_size;
3406         u64 size_to_free;
3407         u64 chunk_type;
3408         struct btrfs_chunk *chunk;
3409         struct btrfs_path *path;
3410         struct btrfs_key key;
3411         struct btrfs_key found_key;
3412         struct btrfs_trans_handle *trans;
3413         struct extent_buffer *leaf;
3414         int slot;
3415         int ret;
3416         int enospc_errors = 0;
3417         bool counting = true;
3418         /* The single value limit and min/max limits use the same bytes in the */
3419         u64 limit_data = bctl->data.limit;
3420         u64 limit_meta = bctl->meta.limit;
3421         u64 limit_sys = bctl->sys.limit;
3422         u32 count_data = 0;
3423         u32 count_meta = 0;
3424         u32 count_sys = 0;
3425         int chunk_reserved = 0;
3426
3427         /* step one make some room on all the devices */
3428         devices = &fs_info->fs_devices->devices;
3429         list_for_each_entry(device, devices, dev_list) {
3430                 old_size = btrfs_device_get_total_bytes(device);
3431                 size_to_free = div_factor(old_size, 1);
3432                 size_to_free = min_t(u64, size_to_free, SZ_1M);
3433                 if (!device->writeable ||
3434                     btrfs_device_get_total_bytes(device) -
3435                     btrfs_device_get_bytes_used(device) > size_to_free ||
3436                     device->is_tgtdev_for_dev_replace)
3437                         continue;
3438
3439                 ret = btrfs_shrink_device(device, old_size - size_to_free);
3440                 if (ret == -ENOSPC)
3441                         break;
3442                 BUG_ON(ret);
3443
3444                 trans = btrfs_start_transaction(dev_root, 0);
3445                 BUG_ON(IS_ERR(trans));
3446
3447                 ret = btrfs_grow_device(trans, device, old_size);
3448                 BUG_ON(ret);
3449
3450                 btrfs_end_transaction(trans, dev_root);
3451         }
3452
3453         /* step two, relocate all the chunks */
3454         path = btrfs_alloc_path();
3455         if (!path) {
3456                 ret = -ENOMEM;
3457                 goto error;
3458         }
3459
3460         /* zero out stat counters */
3461         spin_lock(&fs_info->balance_lock);
3462         memset(&bctl->stat, 0, sizeof(bctl->stat));
3463         spin_unlock(&fs_info->balance_lock);
3464 again:
3465         if (!counting) {
3466                 /*
3467                  * The single value limit and min/max limits use the same bytes
3468                  * in the
3469                  */
3470                 bctl->data.limit = limit_data;
3471                 bctl->meta.limit = limit_meta;
3472                 bctl->sys.limit = limit_sys;
3473         }
3474         key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
3475         key.offset = (u64)-1;
3476         key.type = BTRFS_CHUNK_ITEM_KEY;
3477
3478         while (1) {
3479                 if ((!counting && atomic_read(&fs_info->balance_pause_req)) ||
3480                     atomic_read(&fs_info->balance_cancel_req)) {
3481                         ret = -ECANCELED;
3482                         goto error;
3483                 }
3484
3485                 mutex_lock(&fs_info->delete_unused_bgs_mutex);
3486                 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
3487                 if (ret < 0) {
3488                         mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3489                         goto error;
3490                 }
3491
3492                 /*
3493                  * this shouldn't happen, it means the last relocate
3494                  * failed
3495                  */
3496                 if (ret == 0)
3497                         BUG(); /* FIXME break ? */
3498
3499                 ret = btrfs_previous_item(chunk_root, path, 0,
3500                                           BTRFS_CHUNK_ITEM_KEY);
3501                 if (ret) {
3502                         mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3503                         ret = 0;
3504                         break;
3505                 }
3506
3507                 leaf = path->nodes[0];
3508                 slot = path->slots[0];
3509                 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3510
3511                 if (found_key.objectid != key.objectid) {
3512                         mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3513                         break;
3514                 }
3515
3516                 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
3517                 chunk_type = btrfs_chunk_type(leaf, chunk);
3518
3519                 if (!counting) {
3520                         spin_lock(&fs_info->balance_lock);
3521                         bctl->stat.considered++;
3522                         spin_unlock(&fs_info->balance_lock);
3523                 }
3524
3525                 ret = should_balance_chunk(chunk_root, leaf, chunk,
3526                                            found_key.offset);
3527
3528                 btrfs_release_path(path);
3529                 if (!ret) {
3530                         mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3531                         goto loop;
3532                 }
3533
3534                 if (counting) {
3535                         mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3536                         spin_lock(&fs_info->balance_lock);
3537                         bctl->stat.expected++;
3538                         spin_unlock(&fs_info->balance_lock);
3539
3540                         if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
3541                                 count_data++;
3542                         else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
3543                                 count_sys++;
3544                         else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
3545                                 count_meta++;
3546
3547                         goto loop;
3548                 }
3549
3550                 /*
3551                  * Apply limit_min filter, no need to check if the LIMITS
3552                  * filter is used, limit_min is 0 by default
3553                  */
3554                 if (((chunk_type & BTRFS_BLOCK_GROUP_DATA) &&
3555                                         count_data < bctl->data.limit_min)
3556                                 || ((chunk_type & BTRFS_BLOCK_GROUP_METADATA) &&
3557                                         count_meta < bctl->meta.limit_min)
3558                                 || ((chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) &&
3559                                         count_sys < bctl->sys.limit_min)) {
3560                         mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3561                         goto loop;
3562                 }
3563
3564                 if ((chunk_type & BTRFS_BLOCK_GROUP_DATA) && !chunk_reserved) {
3565                         trans = btrfs_start_transaction(chunk_root, 0);
3566                         if (IS_ERR(trans)) {
3567                                 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3568                                 ret = PTR_ERR(trans);
3569                                 goto error;
3570                         }
3571
3572                         ret = btrfs_force_chunk_alloc(trans, chunk_root,
3573                                                       BTRFS_BLOCK_GROUP_DATA);
3574                         btrfs_end_transaction(trans, chunk_root);
3575                         if (ret < 0) {
3576                                 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3577                                 goto error;
3578                         }
3579                         chunk_reserved = 1;
3580                 }
3581
3582                 ret = btrfs_relocate_chunk(chunk_root,
3583                                            found_key.offset);
3584                 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3585                 if (ret && ret != -ENOSPC)
3586                         goto error;
3587                 if (ret == -ENOSPC) {
3588                         enospc_errors++;
3589                 } else {
3590                         spin_lock(&fs_info->balance_lock);
3591                         bctl->stat.completed++;
3592                         spin_unlock(&fs_info->balance_lock);
3593                 }
3594 loop:
3595                 if (found_key.offset == 0)
3596                         break;
3597                 key.offset = found_key.offset - 1;
3598         }
3599
3600         if (counting) {
3601                 btrfs_release_path(path);
3602                 counting = false;
3603                 goto again;
3604         }
3605 error:
3606         btrfs_free_path(path);
3607         if (enospc_errors) {
3608                 btrfs_info(fs_info, "%d enospc errors during balance",
3609                        enospc_errors);
3610                 if (!ret)
3611                         ret = -ENOSPC;
3612         }
3613
3614         return ret;
3615 }
3616
3617 /**
3618  * alloc_profile_is_valid - see if a given profile is valid and reduced
3619  * @flags: profile to validate
3620  * @extended: if true @flags is treated as an extended profile
3621  */
3622 static int alloc_profile_is_valid(u64 flags, int extended)
3623 {
3624         u64 mask = (extended ? BTRFS_EXTENDED_PROFILE_MASK :
3625                                BTRFS_BLOCK_GROUP_PROFILE_MASK);
3626
3627         flags &= ~BTRFS_BLOCK_GROUP_TYPE_MASK;
3628
3629         /* 1) check that all other bits are zeroed */
3630         if (flags & ~mask)
3631                 return 0;
3632
3633         /* 2) see if profile is reduced */
3634         if (flags == 0)
3635                 return !extended; /* "0" is valid for usual profiles */
3636
3637         /* true if exactly one bit set */
3638         return (flags & (flags - 1)) == 0;
3639 }
3640
3641 static inline int balance_need_close(struct btrfs_fs_info *fs_info)
3642 {
3643         /* cancel requested || normal exit path */
3644         return atomic_read(&fs_info->balance_cancel_req) ||
3645                 (atomic_read(&fs_info->balance_pause_req) == 0 &&
3646                  atomic_read(&fs_info->balance_cancel_req) == 0);
3647 }
3648
3649 static void __cancel_balance(struct btrfs_fs_info *fs_info)
3650 {
3651         int ret;
3652
3653         unset_balance_control(fs_info);
3654         ret = del_balance_item(fs_info->tree_root);
3655         if (ret)
3656                 btrfs_std_error(fs_info, ret, NULL);
3657
3658         atomic_set(&fs_info->mutually_exclusive_operation_running, 0);
3659 }
3660
3661 /* Non-zero return value signifies invalidity */
3662 static inline int validate_convert_profile(struct btrfs_balance_args *bctl_arg,
3663                 u64 allowed)
3664 {
3665         return ((bctl_arg->flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3666                 (!alloc_profile_is_valid(bctl_arg->target, 1) ||
3667                  (bctl_arg->target & ~allowed)));
3668 }
3669
3670 /*
3671  * Should be called with both balance and volume mutexes held
3672  */
3673 int btrfs_balance(struct btrfs_balance_control *bctl,
3674                   struct btrfs_ioctl_balance_args *bargs)
3675 {
3676         struct btrfs_fs_info *fs_info = bctl->fs_info;
3677         u64 allowed;
3678         int mixed = 0;
3679         int ret;
3680         u64 num_devices;
3681         unsigned seq;
3682
3683         if (btrfs_fs_closing(fs_info) ||
3684             atomic_read(&fs_info->balance_pause_req) ||
3685             atomic_read(&fs_info->balance_cancel_req)) {
3686                 ret = -EINVAL;
3687                 goto out;
3688         }
3689
3690         allowed = btrfs_super_incompat_flags(fs_info->super_copy);
3691         if (allowed & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
3692                 mixed = 1;
3693
3694         /*
3695          * In case of mixed groups both data and meta should be picked,
3696          * and identical options should be given for both of them.
3697          */
3698         allowed = BTRFS_BALANCE_DATA | BTRFS_BALANCE_METADATA;
3699         if (mixed && (bctl->flags & allowed)) {
3700                 if (!(bctl->flags & BTRFS_BALANCE_DATA) ||
3701                     !(bctl->flags & BTRFS_BALANCE_METADATA) ||
3702                     memcmp(&bctl->data, &bctl->meta, sizeof(bctl->data))) {
3703                         btrfs_err(fs_info, "with mixed groups data and "
3704                                    "metadata balance options must be the same");
3705                         ret = -EINVAL;
3706                         goto out;
3707                 }
3708         }
3709
3710         num_devices = fs_info->fs_devices->num_devices;
3711         btrfs_dev_replace_lock(&fs_info->dev_replace, 0);
3712         if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace)) {
3713                 BUG_ON(num_devices < 1);
3714                 num_devices--;
3715         }
3716         btrfs_dev_replace_unlock(&fs_info->dev_replace, 0);
3717         allowed = BTRFS_AVAIL_ALLOC_BIT_SINGLE;
3718         if (num_devices == 1)
3719                 allowed |= BTRFS_BLOCK_GROUP_DUP;
3720         else if (num_devices > 1)
3721                 allowed |= (BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID1);
3722         if (num_devices > 2)
3723                 allowed |= BTRFS_BLOCK_GROUP_RAID5;
3724         if (num_devices > 3)
3725                 allowed |= (BTRFS_BLOCK_GROUP_RAID10 |
3726                             BTRFS_BLOCK_GROUP_RAID6);
3727         if (validate_convert_profile(&bctl->data, allowed)) {
3728                 btrfs_err(fs_info, "unable to start balance with target "
3729                            "data profile %llu",
3730                        bctl->data.target);
3731                 ret = -EINVAL;
3732                 goto out;
3733         }
3734         if (validate_convert_profile(&bctl->meta, allowed)) {
3735                 btrfs_err(fs_info,
3736                            "unable to start balance with target metadata profile %llu",
3737                        bctl->meta.target);
3738                 ret = -EINVAL;
3739                 goto out;
3740         }
3741         if (validate_convert_profile(&bctl->sys, allowed)) {
3742                 btrfs_err(fs_info,
3743                            "unable to start balance with target system profile %llu",
3744                        bctl->sys.target);
3745                 ret = -EINVAL;
3746                 goto out;
3747         }
3748
3749         /* allow to reduce meta or sys integrity only if force set */
3750         allowed = BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1 |
3751                         BTRFS_BLOCK_GROUP_RAID10 |
3752                         BTRFS_BLOCK_GROUP_RAID5 |
3753                         BTRFS_BLOCK_GROUP_RAID6;
3754         do {
3755                 seq = read_seqbegin(&fs_info->profiles_lock);
3756
3757                 if (((bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3758                      (fs_info->avail_system_alloc_bits & allowed) &&
3759                      !(bctl->sys.target & allowed)) ||
3760                     ((bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3761                      (fs_info->avail_metadata_alloc_bits & allowed) &&
3762                      !(bctl->meta.target & allowed))) {
3763                         if (bctl->flags & BTRFS_BALANCE_FORCE) {
3764                                 btrfs_info(fs_info, "force reducing metadata integrity");
3765                         } else {
3766                                 btrfs_err(fs_info, "balance will reduce metadata "
3767                                            "integrity, use force if you want this");
3768                                 ret = -EINVAL;
3769                                 goto out;
3770                         }
3771                 }
3772         } while (read_seqretry(&fs_info->profiles_lock, seq));
3773
3774         if (btrfs_get_num_tolerated_disk_barrier_failures(bctl->meta.target) <
3775                 btrfs_get_num_tolerated_disk_barrier_failures(bctl->data.target)) {
3776                 btrfs_warn(fs_info,
3777         "metadata profile 0x%llx has lower redundancy than data profile 0x%llx",
3778                         bctl->meta.target, bctl->data.target);
3779         }
3780
3781         if (bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) {
3782                 fs_info->num_tolerated_disk_barrier_failures = min(
3783                         btrfs_calc_num_tolerated_disk_barrier_failures(fs_info),
3784                         btrfs_get_num_tolerated_disk_barrier_failures(
3785                                 bctl->sys.target));
3786         }
3787
3788         ret = insert_balance_item(fs_info->tree_root, bctl);
3789         if (ret && ret != -EEXIST)
3790                 goto out;
3791
3792         if (!(bctl->flags & BTRFS_BALANCE_RESUME)) {
3793                 BUG_ON(ret == -EEXIST);
3794                 set_balance_control(bctl);
3795         } else {
3796                 BUG_ON(ret != -EEXIST);
3797                 spin_lock(&fs_info->balance_lock);
3798                 update_balance_args(bctl);
3799                 spin_unlock(&fs_info->balance_lock);
3800         }
3801
3802         atomic_inc(&fs_info->balance_running);
3803         mutex_unlock(&fs_info->balance_mutex);
3804
3805         ret = __btrfs_balance(fs_info);
3806
3807         mutex_lock(&fs_info->balance_mutex);
3808         atomic_dec(&fs_info->balance_running);
3809
3810         if (bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) {
3811                 fs_info->num_tolerated_disk_barrier_failures =
3812                         btrfs_calc_num_tolerated_disk_barrier_failures(fs_info);
3813         }
3814
3815         if (bargs) {
3816                 memset(bargs, 0, sizeof(*bargs));
3817                 update_ioctl_balance_args(fs_info, 0, bargs);
3818         }
3819
3820         if ((ret && ret != -ECANCELED && ret != -ENOSPC) ||
3821             balance_need_close(fs_info)) {
3822                 __cancel_balance(fs_info);
3823         }
3824
3825         wake_up(&fs_info->balance_wait_q);
3826
3827         return ret;
3828 out:
3829         if (bctl->flags & BTRFS_BALANCE_RESUME)
3830                 __cancel_balance(fs_info);
3831         else {
3832                 kfree(bctl);
3833                 atomic_set(&fs_info->mutually_exclusive_operation_running, 0);
3834         }
3835         return ret;
3836 }
3837
3838 static int balance_kthread(void *data)
3839 {
3840         struct btrfs_fs_info *fs_info = data;
3841         int ret = 0;
3842
3843         mutex_lock(&fs_info->volume_mutex);
3844         mutex_lock(&fs_info->balance_mutex);
3845
3846         if (fs_info->balance_ctl) {
3847                 btrfs_info(fs_info, "continuing balance");
3848                 ret = btrfs_balance(fs_info->balance_ctl, NULL);
3849         }
3850
3851         mutex_unlock(&fs_info->balance_mutex);
3852         mutex_unlock(&fs_info->volume_mutex);
3853
3854         return ret;
3855 }
3856
3857 int btrfs_resume_balance_async(struct btrfs_fs_info *fs_info)
3858 {
3859         struct task_struct *tsk;
3860
3861         spin_lock(&fs_info->balance_lock);
3862         if (!fs_info->balance_ctl) {
3863                 spin_unlock(&fs_info->balance_lock);
3864                 return 0;
3865         }
3866         spin_unlock(&fs_info->balance_lock);
3867
3868         if (btrfs_test_opt(fs_info->tree_root, SKIP_BALANCE)) {
3869                 btrfs_info(fs_info, "force skipping balance");
3870                 return 0;
3871         }
3872
3873         tsk = kthread_run(balance_kthread, fs_info, "btrfs-balance");
3874         return PTR_ERR_OR_ZERO(tsk);
3875 }
3876
3877 int btrfs_recover_balance(struct btrfs_fs_info *fs_info)
3878 {
3879         struct btrfs_balance_control *bctl;
3880         struct btrfs_balance_item *item;
3881         struct btrfs_disk_balance_args disk_bargs;
3882         struct btrfs_path *path;
3883         struct extent_buffer *leaf;
3884         struct btrfs_key key;
3885         int ret;
3886
3887         path = btrfs_alloc_path();
3888         if (!path)
3889                 return -ENOMEM;
3890
3891         key.objectid = BTRFS_BALANCE_OBJECTID;
3892         key.type = BTRFS_TEMPORARY_ITEM_KEY;
3893         key.offset = 0;
3894
3895         ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
3896         if (ret < 0)
3897                 goto out;
3898         if (ret > 0) { /* ret = -ENOENT; */
3899                 ret = 0;
3900                 goto out;
3901         }
3902
3903         bctl = kzalloc(sizeof(*bctl), GFP_NOFS);
3904         if (!bctl) {
3905                 ret = -ENOMEM;
3906                 goto out;
3907         }
3908
3909         leaf = path->nodes[0];
3910         item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
3911
3912         bctl->fs_info = fs_info;
3913         bctl->flags = btrfs_balance_flags(leaf, item);
3914         bctl->flags |= BTRFS_BALANCE_RESUME;
3915
3916         btrfs_balance_data(leaf, item, &disk_bargs);
3917         btrfs_disk_balance_args_to_cpu(&bctl->data, &disk_bargs);
3918         btrfs_balance_meta(leaf, item, &disk_bargs);
3919         btrfs_disk_balance_args_to_cpu(&bctl->meta, &disk_bargs);
3920         btrfs_balance_sys(leaf, item, &disk_bargs);
3921         btrfs_disk_balance_args_to_cpu(&bctl->sys, &disk_bargs);
3922
3923         WARN_ON(atomic_xchg(&fs_info->mutually_exclusive_operation_running, 1));
3924
3925         mutex_lock(&fs_info->volume_mutex);
3926         mutex_lock(&fs_info->balance_mutex);
3927
3928         set_balance_control(bctl);
3929
3930         mutex_unlock(&fs_info->balance_mutex);
3931         mutex_unlock(&fs_info->volume_mutex);
3932 out:
3933         btrfs_free_path(path);
3934         return ret;
3935 }
3936
3937 int btrfs_pause_balance(struct btrfs_fs_info *fs_info)
3938 {
3939         int ret = 0;
3940
3941         mutex_lock(&fs_info->balance_mutex);
3942         if (!fs_info->balance_ctl) {
3943                 mutex_unlock(&fs_info->balance_mutex);
3944                 return -ENOTCONN;
3945         }
3946
3947         if (atomic_read(&fs_info->balance_running)) {
3948                 atomic_inc(&fs_info->balance_pause_req);
3949                 mutex_unlock(&fs_info->balance_mutex);
3950
3951                 wait_event(fs_info->balance_wait_q,
3952                            atomic_read(&fs_info->balance_running) == 0);
3953
3954                 mutex_lock(&fs_info->balance_mutex);
3955                 /* we are good with balance_ctl ripped off from under us */
3956                 BUG_ON(atomic_read(&fs_info->balance_running));
3957                 atomic_dec(&fs_info->balance_pause_req);
3958         } else {
3959                 ret = -ENOTCONN;
3960         }
3961
3962         mutex_unlock(&fs_info->balance_mutex);
3963         return ret;
3964 }
3965
3966 int btrfs_cancel_balance(struct btrfs_fs_info *fs_info)
3967 {
3968         if (fs_info->sb->s_flags & MS_RDONLY)
3969                 return -EROFS;
3970
3971         mutex_lock(&fs_info->balance_mutex);
3972         if (!fs_info->balance_ctl) {
3973                 mutex_unlock(&fs_info->balance_mutex);
3974                 return -ENOTCONN;
3975         }
3976
3977         atomic_inc(&fs_info->balance_cancel_req);
3978         /*
3979          * if we are running just wait and return, balance item is
3980          * deleted in btrfs_balance in this case
3981          */
3982         if (atomic_read(&fs_info->balance_running)) {
3983                 mutex_unlock(&fs_info->balance_mutex);
3984                 wait_event(fs_info->balance_wait_q,
3985                            atomic_read(&fs_info->balance_running) == 0);
3986                 mutex_lock(&fs_info->balance_mutex);
3987         } else {
3988                 /* __cancel_balance needs volume_mutex */
3989                 mutex_unlock(&fs_info->balance_mutex);
3990                 mutex_lock(&fs_info->volume_mutex);
3991                 mutex_lock(&fs_info->balance_mutex);
3992
3993                 if (fs_info->balance_ctl)
3994                         __cancel_balance(fs_info);
3995
3996                 mutex_unlock(&fs_info->volume_mutex);
3997         }
3998
3999         BUG_ON(fs_info->balance_ctl || atomic_read(&fs_info->balance_running));
4000         atomic_dec(&fs_info->balance_cancel_req);
4001         mutex_unlock(&fs_info->balance_mutex);
4002         return 0;
4003 }
4004
4005 static int btrfs_uuid_scan_kthread(void *data)
4006 {
4007         struct btrfs_fs_info *fs_info = data;
4008         struct btrfs_root *root = fs_info->tree_root;
4009         struct btrfs_key key;
4010         struct btrfs_key max_key;
4011         struct btrfs_path *path = NULL;
4012         int ret = 0;
4013         struct extent_buffer *eb;
4014         int slot;
4015         struct btrfs_root_item root_item;
4016         u32 item_size;
4017         struct btrfs_trans_handle *trans = NULL;
4018
4019         path = btrfs_alloc_path();
4020         if (!path) {
4021                 ret = -ENOMEM;
4022                 goto out;
4023         }
4024
4025         key.objectid = 0;
4026         key.type = BTRFS_ROOT_ITEM_KEY;
4027         key.offset = 0;
4028
4029         max_key.objectid = (u64)-1;
4030         max_key.type = BTRFS_ROOT_ITEM_KEY;
4031         max_key.offset = (u64)-1;
4032
4033         while (1) {
4034                 ret = btrfs_search_forward(root, &key, path, 0);
4035                 if (ret) {
4036                         if (ret > 0)
4037                                 ret = 0;
4038                         break;
4039                 }
4040
4041                 if (key.type != BTRFS_ROOT_ITEM_KEY ||
4042                     (key.objectid < BTRFS_FIRST_FREE_OBJECTID &&
4043                      key.objectid != BTRFS_FS_TREE_OBJECTID) ||
4044                     key.objectid > BTRFS_LAST_FREE_OBJECTID)
4045                         goto skip;
4046
4047                 eb = path->nodes[0];
4048                 slot = path->slots[0];
4049                 item_size = btrfs_item_size_nr(eb, slot);
4050                 if (item_size < sizeof(root_item))
4051                         goto skip;
4052
4053                 read_extent_buffer(eb, &root_item,
4054                                    btrfs_item_ptr_offset(eb, slot),
4055                                    (int)sizeof(root_item));
4056                 if (btrfs_root_refs(&root_item) == 0)
4057                         goto skip;
4058
4059                 if (!btrfs_is_empty_uuid(root_item.uuid) ||
4060                     !btrfs_is_empty_uuid(root_item.received_uuid)) {
4061                         if (trans)
4062                                 goto update_tree;
4063
4064                         btrfs_release_path(path);
4065                         /*
4066                          * 1 - subvol uuid item
4067                          * 1 - received_subvol uuid item
4068                          */
4069                         trans = btrfs_start_transaction(fs_info->uuid_root, 2);
4070                         if (IS_ERR(trans)) {
4071                                 ret = PTR_ERR(trans);
4072                                 break;
4073                         }
4074                         continue;
4075                 } else {
4076                         goto skip;
4077                 }
4078 update_tree:
4079                 if (!btrfs_is_empty_uuid(root_item.uuid)) {
4080                         ret = btrfs_uuid_tree_add(trans, fs_info->uuid_root,
4081                                                   root_item.uuid,
4082                                                   BTRFS_UUID_KEY_SUBVOL,
4083                                                   key.objectid);
4084                         if (ret < 0) {
4085                                 btrfs_warn(fs_info, "uuid_tree_add failed %d",
4086                                         ret);
4087                                 break;
4088                         }
4089                 }
4090
4091                 if (!btrfs_is_empty_uuid(root_item.received_uuid)) {
4092                         ret = btrfs_uuid_tree_add(trans, fs_info->uuid_root,
4093                                                   root_item.received_uuid,
4094                                                  BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4095                                                   key.objectid);
4096                         if (ret < 0) {
4097                                 btrfs_warn(fs_info, "uuid_tree_add failed %d",
4098                                         ret);
4099                                 break;
4100                         }
4101                 }
4102
4103 skip:
4104                 if (trans) {
4105                         ret = btrfs_end_transaction(trans, fs_info->uuid_root);
4106                         trans = NULL;
4107                         if (ret)
4108                                 break;
4109                 }
4110
4111                 btrfs_release_path(path);
4112                 if (key.offset < (u64)-1) {
4113                         key.offset++;
4114                 } else if (key.type < BTRFS_ROOT_ITEM_KEY) {
4115                         key.offset = 0;
4116                         key.type = BTRFS_ROOT_ITEM_KEY;
4117                 } else if (key.objectid < (u64)-1) {
4118                         key.offset = 0;
4119                         key.type = BTRFS_ROOT_ITEM_KEY;
4120                         key.objectid++;
4121                 } else {
4122                         break;
4123                 }
4124                 cond_resched();
4125         }
4126
4127 out:
4128         btrfs_free_path(path);
4129         if (trans && !IS_ERR(trans))
4130                 btrfs_end_transaction(trans, fs_info->uuid_root);
4131         if (ret)
4132                 btrfs_warn(fs_info, "btrfs_uuid_scan_kthread failed %d", ret);
4133         else
4134                 fs_info->update_uuid_tree_gen = 1;
4135         up(&fs_info->uuid_tree_rescan_sem);
4136         return 0;
4137 }
4138
4139 /*
4140  * Callback for btrfs_uuid_tree_iterate().
4141  * returns:
4142  * 0    check succeeded, the entry is not outdated.
4143  * < 0  if an error occurred.
4144  * > 0  if the check failed, which means the caller shall remove the entry.
4145  */
4146 static int btrfs_check_uuid_tree_entry(struct btrfs_fs_info *fs_info,
4147                                        u8 *uuid, u8 type, u64 subid)
4148 {
4149         struct btrfs_key key;
4150         int ret = 0;
4151         struct btrfs_root *subvol_root;
4152
4153         if (type != BTRFS_UUID_KEY_SUBVOL &&
4154             type != BTRFS_UUID_KEY_RECEIVED_SUBVOL)
4155                 goto out;
4156
4157         key.objectid = subid;
4158         key.type = BTRFS_ROOT_ITEM_KEY;
4159         key.offset = (u64)-1;
4160         subvol_root = btrfs_read_fs_root_no_name(fs_info, &key);
4161         if (IS_ERR(subvol_root)) {
4162                 ret = PTR_ERR(subvol_root);
4163                 if (ret == -ENOENT)
4164                         ret = 1;
4165                 goto out;
4166         }
4167
4168         switch (type) {
4169         case BTRFS_UUID_KEY_SUBVOL:
4170                 if (memcmp(uuid, subvol_root->root_item.uuid, BTRFS_UUID_SIZE))
4171                         ret = 1;
4172                 break;
4173         case BTRFS_UUID_KEY_RECEIVED_SUBVOL:
4174                 if (memcmp(uuid, subvol_root->root_item.received_uuid,
4175                            BTRFS_UUID_SIZE))
4176                         ret = 1;
4177                 break;
4178         }
4179
4180 out:
4181         return ret;
4182 }
4183
4184 static int btrfs_uuid_rescan_kthread(void *data)
4185 {
4186         struct btrfs_fs_info *fs_info = (struct btrfs_fs_info *)data;
4187         int ret;
4188
4189         /*
4190          * 1st step is to iterate through the existing UUID tree and
4191          * to delete all entries that contain outdated data.
4192          * 2nd step is to add all missing entries to the UUID tree.
4193          */
4194         ret = btrfs_uuid_tree_iterate(fs_info, btrfs_check_uuid_tree_entry);
4195         if (ret < 0) {
4196                 btrfs_warn(fs_info, "iterating uuid_tree failed %d", ret);
4197                 up(&fs_info->uuid_tree_rescan_sem);
4198                 return ret;
4199         }
4200         return btrfs_uuid_scan_kthread(data);
4201 }
4202
4203 int btrfs_create_uuid_tree(struct btrfs_fs_info *fs_info)
4204 {
4205         struct btrfs_trans_handle *trans;
4206         struct btrfs_root *tree_root = fs_info->tree_root;
4207         struct btrfs_root *uuid_root;
4208         struct task_struct *task;
4209         int ret;
4210
4211         /*
4212          * 1 - root node
4213          * 1 - root item
4214          */
4215         trans = btrfs_start_transaction(tree_root, 2);
4216         if (IS_ERR(trans))
4217                 return PTR_ERR(trans);
4218
4219         uuid_root = btrfs_create_tree(trans, fs_info,
4220                                       BTRFS_UUID_TREE_OBJECTID);
4221         if (IS_ERR(uuid_root)) {
4222                 ret = PTR_ERR(uuid_root);
4223                 btrfs_abort_transaction(trans, tree_root, ret);
4224                 return ret;
4225         }
4226
4227         fs_info->uuid_root = uuid_root;
4228
4229         ret = btrfs_commit_transaction(trans, tree_root);
4230         if (ret)
4231                 return ret;
4232
4233         down(&fs_info->uuid_tree_rescan_sem);
4234         task = kthread_run(btrfs_uuid_scan_kthread, fs_info, "btrfs-uuid");
4235         if (IS_ERR(task)) {
4236                 /* fs_info->update_uuid_tree_gen remains 0 in all error case */
4237                 btrfs_warn(fs_info, "failed to start uuid_scan task");
4238                 up(&fs_info->uuid_tree_rescan_sem);
4239                 return PTR_ERR(task);
4240         }
4241
4242         return 0;
4243 }
4244
4245 int btrfs_check_uuid_tree(struct btrfs_fs_info *fs_info)
4246 {
4247         struct task_struct *task;
4248
4249         down(&fs_info->uuid_tree_rescan_sem);
4250         task = kthread_run(btrfs_uuid_rescan_kthread, fs_info, "btrfs-uuid");
4251         if (IS_ERR(task)) {
4252                 /* fs_info->update_uuid_tree_gen remains 0 in all error case */
4253                 btrfs_warn(fs_info, "failed to start uuid_rescan task");
4254                 up(&fs_info->uuid_tree_rescan_sem);
4255                 return PTR_ERR(task);
4256         }
4257
4258         return 0;
4259 }
4260
4261 /*
4262  * shrinking a device means finding all of the device extents past
4263  * the new size, and then following the back refs to the chunks.
4264  * The chunk relocation code actually frees the device extent
4265  */
4266 int btrfs_shrink_device(struct btrfs_device *device, u64 new_size)
4267 {
4268         struct btrfs_trans_handle *trans;
4269         struct btrfs_root *root = device->dev_root;
4270         struct btrfs_dev_extent *dev_extent = NULL;
4271         struct btrfs_path *path;
4272         u64 length;
4273         u64 chunk_offset;
4274         int ret;
4275         int slot;
4276         int failed = 0;
4277         bool retried = false;
4278         bool checked_pending_chunks = false;
4279         struct extent_buffer *l;
4280         struct btrfs_key key;
4281         struct btrfs_super_block *super_copy = root->fs_info->super_copy;
4282         u64 old_total = btrfs_super_total_bytes(super_copy);
4283         u64 old_size = btrfs_device_get_total_bytes(device);
4284         u64 diff = old_size - new_size;
4285
4286         if (device->is_tgtdev_for_dev_replace)
4287                 return -EINVAL;
4288
4289         path = btrfs_alloc_path();
4290         if (!path)
4291                 return -ENOMEM;
4292
4293         path->reada = READA_FORWARD;
4294
4295         lock_chunks(root);
4296
4297         btrfs_device_set_total_bytes(device, new_size);
4298         if (device->writeable) {
4299                 device->fs_devices->total_rw_bytes -= diff;
4300                 spin_lock(&root->fs_info->free_chunk_lock);
4301                 root->fs_info->free_chunk_space -= diff;
4302                 spin_unlock(&root->fs_info->free_chunk_lock);
4303         }
4304         unlock_chunks(root);
4305
4306 again:
4307         key.objectid = device->devid;
4308         key.offset = (u64)-1;
4309         key.type = BTRFS_DEV_EXTENT_KEY;
4310
4311         do {
4312                 mutex_lock(&root->fs_info->delete_unused_bgs_mutex);
4313                 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4314                 if (ret < 0) {
4315                         mutex_unlock(&root->fs_info->delete_unused_bgs_mutex);
4316                         goto done;
4317                 }
4318
4319                 ret = btrfs_previous_item(root, path, 0, key.type);
4320                 if (ret)
4321                         mutex_unlock(&root->fs_info->delete_unused_bgs_mutex);
4322                 if (ret < 0)
4323                         goto done;
4324                 if (ret) {
4325                         ret = 0;
4326                         btrfs_release_path(path);
4327                         break;
4328                 }
4329
4330                 l = path->nodes[0];
4331                 slot = path->slots[0];
4332                 btrfs_item_key_to_cpu(l, &key, path->slots[0]);
4333
4334                 if (key.objectid != device->devid) {
4335                         mutex_unlock(&root->fs_info->delete_unused_bgs_mutex);
4336                         btrfs_release_path(path);
4337                         break;
4338                 }
4339
4340                 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
4341                 length = btrfs_dev_extent_length(l, dev_extent);
4342
4343                 if (key.offset + length <= new_size) {
4344                         mutex_unlock(&root->fs_info->delete_unused_bgs_mutex);
4345                         btrfs_release_path(path);
4346                         break;
4347                 }
4348
4349                 chunk_offset = btrfs_dev_extent_chunk_offset(l, dev_extent);
4350                 btrfs_release_path(path);
4351
4352                 ret = btrfs_relocate_chunk(root, chunk_offset);
4353                 mutex_unlock(&root->fs_info->delete_unused_bgs_mutex);
4354                 if (ret && ret != -ENOSPC)
4355                         goto done;
4356                 if (ret == -ENOSPC)
4357                         failed++;
4358         } while (key.offset-- > 0);
4359
4360         if (failed && !retried) {
4361                 failed = 0;
4362                 retried = true;
4363                 goto again;
4364         } else if (failed && retried) {
4365                 ret = -ENOSPC;
4366                 goto done;
4367         }
4368
4369         /* Shrinking succeeded, else we would be at "done". */
4370         trans = btrfs_start_transaction(root, 0);
4371         if (IS_ERR(trans)) {
4372                 ret = PTR_ERR(trans);
4373                 goto done;
4374         }
4375
4376         lock_chunks(root);
4377
4378         /*
4379          * We checked in the above loop all device extents that were already in
4380          * the device tree. However before we have updated the device's
4381          * total_bytes to the new size, we might have had chunk allocations that
4382          * have not complete yet (new block groups attached to transaction
4383          * handles), and therefore their device extents were not yet in the
4384          * device tree and we missed them in the loop above. So if we have any
4385          * pending chunk using a device extent that overlaps the device range
4386          * that we can not use anymore, commit the current transaction and
4387          * repeat the search on the device tree - this way we guarantee we will
4388          * not have chunks using device extents that end beyond 'new_size'.
4389          */
4390         if (!checked_pending_chunks) {
4391                 u64 start = new_size;
4392                 u64 len = old_size - new_size;
4393
4394                 if (contains_pending_extent(trans->transaction, device,
4395                                             &start, len)) {
4396                         unlock_chunks(root);
4397                         checked_pending_chunks = true;
4398                         failed = 0;
4399                         retried = false;
4400                         ret = btrfs_commit_transaction(trans, root);
4401                         if (ret)
4402                                 goto done;
4403                         goto again;
4404                 }
4405         }
4406
4407         btrfs_device_set_disk_total_bytes(device, new_size);
4408         if (list_empty(&device->resized_list))
4409                 list_add_tail(&device->resized_list,
4410                               &root->fs_info->fs_devices->resized_devices);
4411
4412         WARN_ON(diff > old_total);
4413         btrfs_set_super_total_bytes(super_copy, old_total - diff);
4414         unlock_chunks(root);
4415
4416         /* Now btrfs_update_device() will change the on-disk size. */
4417         ret = btrfs_update_device(trans, device);
4418         btrfs_end_transaction(trans, root);
4419 done:
4420         btrfs_free_path(path);
4421         if (ret) {
4422                 lock_chunks(root);
4423                 btrfs_device_set_total_bytes(device, old_size);
4424                 if (device->writeable)
4425                         device->fs_devices->total_rw_bytes += diff;
4426                 spin_lock(&root->fs_info->free_chunk_lock);
4427                 root->fs_info->free_chunk_space += diff;
4428                 spin_unlock(&root->fs_info->free_chunk_lock);
4429                 unlock_chunks(root);
4430         }
4431         return ret;
4432 }
4433
4434 static int btrfs_add_system_chunk(struct btrfs_root *root,
4435                            struct btrfs_key *key,
4436                            struct btrfs_chunk *chunk, int item_size)
4437 {
4438         struct btrfs_super_block *super_copy = root->fs_info->super_copy;
4439         struct btrfs_disk_key disk_key;
4440         u32 array_size;
4441         u8 *ptr;
4442
4443         lock_chunks(root);
4444         array_size = btrfs_super_sys_array_size(super_copy);
4445         if (array_size + item_size + sizeof(disk_key)
4446                         > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE) {
4447                 unlock_chunks(root);
4448                 return -EFBIG;
4449         }
4450
4451         ptr = super_copy->sys_chunk_array + array_size;
4452         btrfs_cpu_key_to_disk(&disk_key, key);
4453         memcpy(ptr, &disk_key, sizeof(disk_key));
4454         ptr += sizeof(disk_key);
4455         memcpy(ptr, chunk, item_size);
4456         item_size += sizeof(disk_key);
4457         btrfs_set_super_sys_array_size(super_copy, array_size + item_size);
4458         unlock_chunks(root);
4459
4460         return 0;
4461 }
4462
4463 /*
4464  * sort the devices in descending order by max_avail, total_avail
4465  */
4466 static int btrfs_cmp_device_info(const void *a, const void *b)
4467 {
4468         const struct btrfs_device_info *di_a = a;
4469         const struct btrfs_device_info *di_b = b;
4470
4471         if (di_a->max_avail > di_b->max_avail)
4472                 return -1;
4473         if (di_a->max_avail < di_b->max_avail)
4474                 return 1;
4475         if (di_a->total_avail > di_b->total_avail)
4476                 return -1;
4477         if (di_a->total_avail < di_b->total_avail)
4478                 return 1;
4479         return 0;
4480 }
4481
4482 static u32 find_raid56_stripe_len(u32 data_devices, u32 dev_stripe_target)
4483 {
4484         /* TODO allow them to set a preferred stripe size */
4485         return SZ_64K;
4486 }
4487
4488 static void check_raid56_incompat_flag(struct btrfs_fs_info *info, u64 type)
4489 {
4490         if (!(type & BTRFS_BLOCK_GROUP_RAID56_MASK))
4491                 return;
4492
4493         btrfs_set_fs_incompat(info, RAID56);
4494 }
4495
4496 #define BTRFS_MAX_DEVS(r) ((BTRFS_LEAF_DATA_SIZE(r)             \
4497                         - sizeof(struct btrfs_item)             \
4498                         - sizeof(struct btrfs_chunk))           \
4499                         / sizeof(struct btrfs_stripe) + 1)
4500
4501 #define BTRFS_MAX_DEVS_SYS_CHUNK ((BTRFS_SYSTEM_CHUNK_ARRAY_SIZE        \
4502                                 - 2 * sizeof(struct btrfs_disk_key)     \
4503                                 - 2 * sizeof(struct btrfs_chunk))       \
4504                                 / sizeof(struct btrfs_stripe) + 1)
4505
4506 static int __btrfs_alloc_chunk(struct btrfs_trans_handle *trans,
4507                                struct btrfs_root *extent_root, u64 start,
4508                                u64 type)
4509 {
4510         struct btrfs_fs_info *info = extent_root->fs_info;
4511         struct btrfs_fs_devices *fs_devices = info->fs_devices;
4512         struct list_head *cur;
4513         struct map_lookup *map = NULL;
4514         struct extent_map_tree *em_tree;
4515         struct extent_map *em;
4516         struct btrfs_device_info *devices_info = NULL;
4517         u64 total_avail;
4518         int num_stripes;        /* total number of stripes to allocate */
4519         int data_stripes;       /* number of stripes that count for
4520                                    block group size */
4521         int sub_stripes;        /* sub_stripes info for map */
4522         int dev_stripes;        /* stripes per dev */
4523         int devs_max;           /* max devs to use */
4524         int devs_min;           /* min devs needed */
4525         int devs_increment;     /* ndevs has to be a multiple of this */
4526         int ncopies;            /* how many copies to data has */
4527         int ret;
4528         u64 max_stripe_size;
4529         u64 max_chunk_size;
4530         u64 stripe_size;
4531         u64 num_bytes;
4532         u64 raid_stripe_len = BTRFS_STRIPE_LEN;
4533         int ndevs;
4534         int i;
4535         int j;
4536         int index;
4537
4538         BUG_ON(!alloc_profile_is_valid(type, 0));
4539
4540         if (list_empty(&fs_devices->alloc_list))
4541                 return -ENOSPC;
4542
4543         index = __get_raid_index(type);
4544
4545         sub_stripes = btrfs_raid_array[index].sub_stripes;
4546         dev_stripes = btrfs_raid_array[index].dev_stripes;
4547         devs_max = btrfs_raid_array[index].devs_max;
4548         devs_min = btrfs_raid_array[index].devs_min;
4549         devs_increment = btrfs_raid_array[index].devs_increment;
4550         ncopies = btrfs_raid_array[index].ncopies;
4551
4552         if (type & BTRFS_BLOCK_GROUP_DATA) {
4553                 max_stripe_size = SZ_1G;
4554                 max_chunk_size = 10 * max_stripe_size;
4555                 if (!devs_max)
4556                         devs_max = BTRFS_MAX_DEVS(info->chunk_root);
4557         } else if (type & BTRFS_BLOCK_GROUP_METADATA) {
4558                 /* for larger filesystems, use larger metadata chunks */
4559                 if (fs_devices->total_rw_bytes > 50ULL * SZ_1G)
4560                         max_stripe_size = SZ_1G;
4561                 else
4562                         max_stripe_size = SZ_256M;
4563                 max_chunk_size = max_stripe_size;
4564                 if (!devs_max)
4565                         devs_max = BTRFS_MAX_DEVS(info->chunk_root);
4566         } else if (type & BTRFS_BLOCK_GROUP_SYSTEM) {
4567                 max_stripe_size = SZ_32M;
4568                 max_chunk_size = 2 * max_stripe_size;
4569                 if (!devs_max)
4570                         devs_max = BTRFS_MAX_DEVS_SYS_CHUNK;
4571         } else {
4572                 btrfs_err(info, "invalid chunk type 0x%llx requested",
4573                        type);
4574                 BUG_ON(1);
4575         }
4576
4577         /* we don't want a chunk larger than 10% of writeable space */
4578         max_chunk_size = min(div_factor(fs_devices->total_rw_bytes, 1),
4579                              max_chunk_size);
4580
4581         devices_info = kcalloc(fs_devices->rw_devices, sizeof(*devices_info),
4582                                GFP_NOFS);
4583         if (!devices_info)
4584                 return -ENOMEM;
4585
4586         cur = fs_devices->alloc_list.next;
4587
4588         /*
4589          * in the first pass through the devices list, we gather information
4590          * about the available holes on each device.
4591          */
4592         ndevs = 0;
4593         while (cur != &fs_devices->alloc_list) {
4594                 struct btrfs_device *device;
4595                 u64 max_avail;
4596                 u64 dev_offset;
4597
4598                 device = list_entry(cur, struct btrfs_device, dev_alloc_list);
4599
4600                 cur = cur->next;
4601
4602                 if (!device->writeable) {
4603                         WARN(1, KERN_ERR
4604                                "BTRFS: read-only device in alloc_list\n");
4605                         continue;
4606                 }
4607
4608                 if (!device->in_fs_metadata ||
4609                     device->is_tgtdev_for_dev_replace)
4610                         continue;
4611
4612                 if (device->total_bytes > device->bytes_used)
4613                         total_avail = device->total_bytes - device->bytes_used;
4614                 else
4615                         total_avail = 0;
4616
4617                 /* If there is no space on this device, skip it. */
4618                 if (total_avail == 0)
4619                         continue;
4620
4621                 ret = find_free_dev_extent(trans, device,
4622                                            max_stripe_size * dev_stripes,
4623                                            &dev_offset, &max_avail);
4624                 if (ret && ret != -ENOSPC)
4625                         goto error;
4626
4627                 if (ret == 0)
4628                         max_avail = max_stripe_size * dev_stripes;
4629
4630                 if (max_avail < BTRFS_STRIPE_LEN * dev_stripes)
4631                         continue;
4632
4633                 if (ndevs == fs_devices->rw_devices) {
4634                         WARN(1, "%s: found more than %llu devices\n",
4635                              __func__, fs_devices->rw_devices);
4636                         break;
4637                 }
4638                 devices_info[ndevs].dev_offset = dev_offset;
4639                 devices_info[ndevs].max_avail = max_avail;
4640                 devices_info[ndevs].total_avail = total_avail;
4641                 devices_info[ndevs].dev = device;
4642                 ++ndevs;
4643         }
4644
4645         /*
4646          * now sort the devices by hole size / available space
4647          */
4648         sort(devices_info, ndevs, sizeof(struct btrfs_device_info),
4649              btrfs_cmp_device_info, NULL);
4650
4651         /* round down to number of usable stripes */
4652         ndevs -= ndevs % devs_increment;
4653
4654         if (ndevs < devs_increment * sub_stripes || ndevs < devs_min) {
4655                 ret = -ENOSPC;
4656                 goto error;
4657         }
4658
4659         if (devs_max && ndevs > devs_max)
4660                 ndevs = devs_max;
4661         /*
4662          * the primary goal is to maximize the number of stripes, so use as many
4663          * devices as possible, even if the stripes are not maximum sized.
4664          */
4665         stripe_size = devices_info[ndevs-1].max_avail;
4666         num_stripes = ndevs * dev_stripes;
4667
4668         /*
4669          * this will have to be fixed for RAID1 and RAID10 over
4670          * more drives
4671          */
4672         data_stripes = num_stripes / ncopies;
4673
4674         if (type & BTRFS_BLOCK_GROUP_RAID5) {
4675                 raid_stripe_len = find_raid56_stripe_len(ndevs - 1,
4676                                  btrfs_super_stripesize(info->super_copy));
4677                 data_stripes = num_stripes - 1;
4678         }
4679         if (type & BTRFS_BLOCK_GROUP_RAID6) {
4680                 raid_stripe_len = find_raid56_stripe_len(ndevs - 2,
4681                                  btrfs_super_stripesize(info->super_copy));
4682                 data_stripes = num_stripes - 2;
4683         }
4684
4685         /*
4686          * Use the number of data stripes to figure out how big this chunk
4687          * is really going to be in terms of logical address space,
4688          * and compare that answer with the max chunk size
4689          */
4690         if (stripe_size * data_stripes > max_chunk_size) {
4691                 u64 mask = (1ULL << 24) - 1;
4692
4693                 stripe_size = div_u64(max_chunk_size, data_stripes);
4694
4695                 /* bump the answer up to a 16MB boundary */
4696                 stripe_size = (stripe_size + mask) & ~mask;
4697
4698                 /* but don't go higher than the limits we found
4699                  * while searching for free extents
4700                  */
4701                 if (stripe_size > devices_info[ndevs-1].max_avail)
4702                         stripe_size = devices_info[ndevs-1].max_avail;
4703         }
4704
4705         stripe_size = div_u64(stripe_size, dev_stripes);
4706
4707         /* align to BTRFS_STRIPE_LEN */
4708         stripe_size = div_u64(stripe_size, raid_stripe_len);
4709         stripe_size *= raid_stripe_len;
4710
4711         map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
4712         if (!map) {
4713                 ret = -ENOMEM;
4714                 goto error;
4715         }
4716         map->num_stripes = num_stripes;
4717
4718         for (i = 0; i < ndevs; ++i) {
4719                 for (j = 0; j < dev_stripes; ++j) {
4720                         int s = i * dev_stripes + j;
4721                         map->stripes[s].dev = devices_info[i].dev;
4722                         map->stripes[s].physical = devices_info[i].dev_offset +
4723                                                    j * stripe_size;
4724                 }
4725         }
4726         map->sector_size = extent_root->sectorsize;
4727         map->stripe_len = raid_stripe_len;
4728         map->io_align = raid_stripe_len;
4729         map->io_width = raid_stripe_len;
4730         map->type = type;
4731         map->sub_stripes = sub_stripes;
4732
4733         num_bytes = stripe_size * data_stripes;
4734
4735         trace_btrfs_chunk_alloc(info->chunk_root, map, start, num_bytes);
4736
4737         em = alloc_extent_map();
4738         if (!em) {
4739                 kfree(map);
4740                 ret = -ENOMEM;
4741                 goto error;
4742         }
4743         set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
4744         em->map_lookup = map;
4745         em->start = start;
4746         em->len = num_bytes;
4747         em->block_start = 0;
4748         em->block_len = em->len;
4749         em->orig_block_len = stripe_size;
4750
4751         em_tree = &extent_root->fs_info->mapping_tree.map_tree;
4752         write_lock(&em_tree->lock);
4753         ret = add_extent_mapping(em_tree, em, 0);
4754         if (!ret) {
4755                 list_add_tail(&em->list, &trans->transaction->pending_chunks);
4756                 atomic_inc(&em->refs);
4757         }
4758         write_unlock(&em_tree->lock);
4759         if (ret) {
4760                 free_extent_map(em);
4761                 goto error;
4762         }
4763
4764         ret = btrfs_make_block_group(trans, extent_root, 0, type,
4765                                      BTRFS_FIRST_CHUNK_TREE_OBJECTID,
4766                                      start, num_bytes);
4767         if (ret)
4768                 goto error_del_extent;
4769
4770         for (i = 0; i < map->num_stripes; i++) {
4771                 num_bytes = map->stripes[i].dev->bytes_used + stripe_size;
4772                 btrfs_device_set_bytes_used(map->stripes[i].dev, num_bytes);
4773         }
4774
4775         spin_lock(&extent_root->fs_info->free_chunk_lock);
4776         extent_root->fs_info->free_chunk_space -= (stripe_size *
4777                                                    map->num_stripes);
4778         spin_unlock(&extent_root->fs_info->free_chunk_lock);
4779
4780         free_extent_map(em);
4781         check_raid56_incompat_flag(extent_root->fs_info, type);
4782
4783         kfree(devices_info);
4784         return 0;
4785
4786 error_del_extent:
4787         write_lock(&em_tree->lock);
4788         remove_extent_mapping(em_tree, em);
4789         write_unlock(&em_tree->lock);
4790
4791         /* One for our allocation */
4792         free_extent_map(em);
4793         /* One for the tree reference */
4794         free_extent_map(em);
4795         /* One for the pending_chunks list reference */
4796         free_extent_map(em);
4797 error:
4798         kfree(devices_info);
4799         return ret;
4800 }
4801
4802 int btrfs_finish_chunk_alloc(struct btrfs_trans_handle *trans,
4803                                 struct btrfs_root *extent_root,
4804                                 u64 chunk_offset, u64 chunk_size)
4805 {
4806         struct btrfs_key key;
4807         struct btrfs_root *chunk_root = extent_root->fs_info->chunk_root;
4808         struct btrfs_device *device;
4809         struct btrfs_chunk *chunk;
4810         struct btrfs_stripe *stripe;
4811         struct extent_map_tree *em_tree;
4812         struct extent_map *em;
4813         struct map_lookup *map;
4814         size_t item_size;
4815         u64 dev_offset;
4816         u64 stripe_size;
4817         int i = 0;
4818         int ret = 0;
4819
4820         em_tree = &extent_root->fs_info->mapping_tree.map_tree;
4821         read_lock(&em_tree->lock);
4822         em = lookup_extent_mapping(em_tree, chunk_offset, chunk_size);
4823         read_unlock(&em_tree->lock);
4824
4825         if (!em) {
4826                 btrfs_crit(extent_root->fs_info, "unable to find logical "
4827                            "%Lu len %Lu", chunk_offset, chunk_size);
4828                 return -EINVAL;
4829         }
4830
4831         if (em->start != chunk_offset || em->len != chunk_size) {
4832                 btrfs_crit(extent_root->fs_info, "found a bad mapping, wanted"
4833                           " %Lu-%Lu, found %Lu-%Lu", chunk_offset,
4834                           chunk_size, em->start, em->len);
4835                 free_extent_map(em);
4836                 return -EINVAL;
4837         }
4838
4839         map = em->map_lookup;
4840         item_size = btrfs_chunk_item_size(map->num_stripes);
4841         stripe_size = em->orig_block_len;
4842
4843         chunk = kzalloc(item_size, GFP_NOFS);
4844         if (!chunk) {
4845                 ret = -ENOMEM;
4846                 goto out;
4847         }
4848
4849         /*
4850          * Take the device list mutex to prevent races with the final phase of
4851          * a device replace operation that replaces the device object associated
4852          * with the map's stripes, because the device object's id can change
4853          * at any time during that final phase of the device replace operation
4854          * (dev-replace.c:btrfs_dev_replace_finishing()).
4855          */
4856         mutex_lock(&chunk_root->fs_info->fs_devices->device_list_mutex);
4857         for (i = 0; i < map->num_stripes; i++) {
4858                 device = map->stripes[i].dev;
4859                 dev_offset = map->stripes[i].physical;
4860
4861                 ret = btrfs_update_device(trans, device);
4862                 if (ret)
4863                         break;
4864                 ret = btrfs_alloc_dev_extent(trans, device,
4865                                              chunk_root->root_key.objectid,
4866                                              BTRFS_FIRST_CHUNK_TREE_OBJECTID,
4867                                              chunk_offset, dev_offset,
4868                                              stripe_size);
4869                 if (ret)
4870                         break;
4871         }
4872         if (ret) {
4873                 mutex_unlock(&chunk_root->fs_info->fs_devices->device_list_mutex);
4874                 goto out;
4875         }
4876
4877         stripe = &chunk->stripe;
4878         for (i = 0; i < map->num_stripes; i++) {
4879                 device = map->stripes[i].dev;
4880                 dev_offset = map->stripes[i].physical;
4881
4882                 btrfs_set_stack_stripe_devid(stripe, device->devid);
4883                 btrfs_set_stack_stripe_offset(stripe, dev_offset);
4884                 memcpy(stripe->dev_uuid, device->uuid, BTRFS_UUID_SIZE);
4885                 stripe++;
4886         }
4887         mutex_unlock(&chunk_root->fs_info->fs_devices->device_list_mutex);
4888
4889         btrfs_set_stack_chunk_length(chunk, chunk_size);
4890         btrfs_set_stack_chunk_owner(chunk, extent_root->root_key.objectid);
4891         btrfs_set_stack_chunk_stripe_len(chunk, map->stripe_len);
4892         btrfs_set_stack_chunk_type(chunk, map->type);
4893         btrfs_set_stack_chunk_num_stripes(chunk, map->num_stripes);
4894         btrfs_set_stack_chunk_io_align(chunk, map->stripe_len);
4895         btrfs_set_stack_chunk_io_width(chunk, map->stripe_len);
4896         btrfs_set_stack_chunk_sector_size(chunk, extent_root->sectorsize);
4897         btrfs_set_stack_chunk_sub_stripes(chunk, map->sub_stripes);
4898
4899         key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
4900         key.type = BTRFS_CHUNK_ITEM_KEY;
4901         key.offset = chunk_offset;
4902
4903         ret = btrfs_insert_item(trans, chunk_root, &key, chunk, item_size);
4904         if (ret == 0 && map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
4905                 /*
4906                  * TODO: Cleanup of inserted chunk root in case of
4907                  * failure.
4908                  */
4909                 ret = btrfs_add_system_chunk(chunk_root, &key, chunk,
4910                                              item_size);
4911         }
4912
4913 out:
4914         kfree(chunk);
4915         free_extent_map(em);
4916         return ret;
4917 }
4918
4919 /*
4920  * Chunk allocation falls into two parts. The first part does works
4921  * that make the new allocated chunk useable, but not do any operation
4922  * that modifies the chunk tree. The second part does the works that
4923  * require modifying the chunk tree. This division is important for the
4924  * bootstrap process of adding storage to a seed btrfs.
4925  */
4926 int btrfs_alloc_chunk(struct btrfs_trans_handle *trans,
4927                       struct btrfs_root *extent_root, u64 type)
4928 {
4929         u64 chunk_offset;
4930
4931         ASSERT(mutex_is_locked(&extent_root->fs_info->chunk_mutex));
4932         chunk_offset = find_next_chunk(extent_root->fs_info);
4933         return __btrfs_alloc_chunk(trans, extent_root, chunk_offset, type);
4934 }
4935
4936 static noinline int init_first_rw_device(struct btrfs_trans_handle *trans,
4937                                          struct btrfs_root *root,
4938                                          struct btrfs_device *device)
4939 {
4940         u64 chunk_offset;
4941         u64 sys_chunk_offset;
4942         u64 alloc_profile;
4943         struct btrfs_fs_info *fs_info = root->fs_info;
4944         struct btrfs_root *extent_root = fs_info->extent_root;
4945         int ret;
4946
4947         chunk_offset = find_next_chunk(fs_info);
4948         alloc_profile = btrfs_get_alloc_profile(extent_root, 0);
4949         ret = __btrfs_alloc_chunk(trans, extent_root, chunk_offset,
4950                                   alloc_profile);
4951         if (ret)
4952                 return ret;
4953
4954         sys_chunk_offset = find_next_chunk(root->fs_info);
4955         alloc_profile = btrfs_get_alloc_profile(fs_info->chunk_root, 0);
4956         ret = __btrfs_alloc_chunk(trans, extent_root, sys_chunk_offset,
4957                                   alloc_profile);
4958         return ret;
4959 }
4960
4961 static inline int btrfs_chunk_max_errors(struct map_lookup *map)
4962 {
4963         int max_errors;
4964
4965         if (map->type & (BTRFS_BLOCK_GROUP_RAID1 |
4966                          BTRFS_BLOCK_GROUP_RAID10 |
4967                          BTRFS_BLOCK_GROUP_RAID5 |
4968                          BTRFS_BLOCK_GROUP_DUP)) {
4969                 max_errors = 1;
4970         } else if (map->type & BTRFS_BLOCK_GROUP_RAID6) {
4971                 max_errors = 2;
4972         } else {
4973                 max_errors = 0;
4974         }
4975
4976         return max_errors;
4977 }
4978
4979 int btrfs_chunk_readonly(struct btrfs_root *root, u64 chunk_offset)
4980 {
4981         struct extent_map *em;
4982         struct map_lookup *map;
4983         struct btrfs_mapping_tree *map_tree = &root->fs_info->mapping_tree;
4984         int readonly = 0;
4985         int miss_ndevs = 0;
4986         int i;
4987
4988         read_lock(&map_tree->map_tree.lock);
4989         em = lookup_extent_mapping(&map_tree->map_tree, chunk_offset, 1);
4990         read_unlock(&map_tree->map_tree.lock);
4991         if (!em)
4992                 return 1;
4993
4994         map = em->map_lookup;
4995         for (i = 0; i < map->num_stripes; i++) {
4996                 if (map->stripes[i].dev->missing) {
4997                         miss_ndevs++;
4998                         continue;
4999                 }
5000
5001                 if (!map->stripes[i].dev->writeable) {
5002                         readonly = 1;
5003                         goto end;
5004                 }
5005         }
5006
5007         /*
5008          * If the number of missing devices is larger than max errors,
5009          * we can not write the data into that chunk successfully, so
5010          * set it readonly.
5011          */
5012         if (miss_ndevs > btrfs_chunk_max_errors(map))
5013                 readonly = 1;
5014 end:
5015         free_extent_map(em);
5016         return readonly;
5017 }
5018
5019 void btrfs_mapping_init(struct btrfs_mapping_tree *tree)
5020 {
5021         extent_map_tree_init(&tree->map_tree);
5022 }
5023
5024 void btrfs_mapping_tree_free(struct btrfs_mapping_tree *tree)
5025 {
5026         struct extent_map *em;
5027
5028         while (1) {
5029                 write_lock(&tree->map_tree.lock);
5030                 em = lookup_extent_mapping(&tree->map_tree, 0, (u64)-1);
5031                 if (em)
5032                         remove_extent_mapping(&tree->map_tree, em);
5033                 write_unlock(&tree->map_tree.lock);
5034                 if (!em)
5035                         break;
5036                 /* once for us */
5037                 free_extent_map(em);
5038                 /* once for the tree */
5039                 free_extent_map(em);
5040         }
5041 }
5042
5043 int btrfs_num_copies(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
5044 {
5045         struct btrfs_mapping_tree *map_tree = &fs_info->mapping_tree;
5046         struct extent_map *em;
5047         struct map_lookup *map;
5048         struct extent_map_tree *em_tree = &map_tree->map_tree;
5049         int ret;
5050
5051         read_lock(&em_tree->lock);
5052         em = lookup_extent_mapping(em_tree, logical, len);
5053         read_unlock(&em_tree->lock);
5054
5055         /*
5056          * We could return errors for these cases, but that could get ugly and
5057          * we'd probably do the same thing which is just not do anything else
5058          * and exit, so return 1 so the callers don't try to use other copies.
5059          */
5060         if (!em) {
5061                 btrfs_crit(fs_info, "No mapping for %Lu-%Lu", logical,
5062                             logical+len);
5063                 return 1;
5064         }
5065
5066         if (em->start > logical || em->start + em->len < logical) {
5067                 btrfs_crit(fs_info, "Invalid mapping for %Lu-%Lu, got "
5068                             "%Lu-%Lu", logical, logical+len, em->start,
5069                             em->start + em->len);
5070                 free_extent_map(em);
5071                 return 1;
5072         }
5073
5074         map = em->map_lookup;
5075         if (map->type & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1))
5076                 ret = map->num_stripes;
5077         else if (map->type & BTRFS_BLOCK_GROUP_RAID10)
5078                 ret = map->sub_stripes;
5079         else if (map->type & BTRFS_BLOCK_GROUP_RAID5)
5080                 ret = 2;
5081         else if (map->type & BTRFS_BLOCK_GROUP_RAID6)
5082                 ret = 3;
5083         else
5084                 ret = 1;
5085         free_extent_map(em);
5086
5087         btrfs_dev_replace_lock(&fs_info->dev_replace, 0);
5088         if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace))
5089                 ret++;
5090         btrfs_dev_replace_unlock(&fs_info->dev_replace, 0);
5091
5092         return ret;
5093 }
5094
5095 unsigned long btrfs_full_stripe_len(struct btrfs_root *root,
5096                                     struct btrfs_mapping_tree *map_tree,
5097                                     u64 logical)
5098 {
5099         struct extent_map *em;
5100         struct map_lookup *map;
5101         struct extent_map_tree *em_tree = &map_tree->map_tree;
5102         unsigned long len = root->sectorsize;
5103
5104         read_lock(&em_tree->lock);
5105         em = lookup_extent_mapping(em_tree, logical, len);
5106         read_unlock(&em_tree->lock);
5107         BUG_ON(!em);
5108
5109         BUG_ON(em->start > logical || em->start + em->len < logical);
5110         map = em->map_lookup;
5111         if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
5112                 len = map->stripe_len * nr_data_stripes(map);
5113         free_extent_map(em);
5114         return len;
5115 }
5116
5117 int btrfs_is_parity_mirror(struct btrfs_mapping_tree *map_tree,
5118                            u64 logical, u64 len, int mirror_num)
5119 {
5120         struct extent_map *em;
5121         struct map_lookup *map;
5122         struct extent_map_tree *em_tree = &map_tree->map_tree;
5123         int ret = 0;
5124
5125         read_lock(&em_tree->lock);
5126         em = lookup_extent_mapping(em_tree, logical, len);
5127         read_unlock(&em_tree->lock);
5128         BUG_ON(!em);
5129
5130         BUG_ON(em->start > logical || em->start + em->len < logical);
5131         map = em->map_lookup;
5132         if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
5133                 ret = 1;
5134         free_extent_map(em);
5135         return ret;
5136 }
5137
5138 static int find_live_mirror(struct btrfs_fs_info *fs_info,
5139                             struct map_lookup *map, int first, int num,
5140                             int optimal, int dev_replace_is_ongoing)
5141 {
5142         int i;
5143         int tolerance;
5144         struct btrfs_device *srcdev;
5145
5146         if (dev_replace_is_ongoing &&
5147             fs_info->dev_replace.cont_reading_from_srcdev_mode ==
5148              BTRFS_DEV_REPLACE_ITEM_CONT_READING_FROM_SRCDEV_MODE_AVOID)
5149                 srcdev = fs_info->dev_replace.srcdev;
5150         else
5151                 srcdev = NULL;
5152
5153         /*
5154          * try to avoid the drive that is the source drive for a
5155          * dev-replace procedure, only choose it if no other non-missing
5156          * mirror is available
5157          */
5158         for (tolerance = 0; tolerance < 2; tolerance++) {
5159                 if (map->stripes[optimal].dev->bdev &&
5160                     (tolerance || map->stripes[optimal].dev != srcdev))
5161                         return optimal;
5162                 for (i = first; i < first + num; i++) {
5163                         if (map->stripes[i].dev->bdev &&
5164                             (tolerance || map->stripes[i].dev != srcdev))
5165                                 return i;
5166                 }
5167         }
5168
5169         /* we couldn't find one that doesn't fail.  Just return something
5170          * and the io error handling code will clean up eventually
5171          */
5172         return optimal;
5173 }
5174
5175 static inline int parity_smaller(u64 a, u64 b)
5176 {
5177         return a > b;
5178 }
5179
5180 /* Bubble-sort the stripe set to put the parity/syndrome stripes last */
5181 static void sort_parity_stripes(struct btrfs_bio *bbio, int num_stripes)
5182 {
5183         struct btrfs_bio_stripe s;
5184         int i;
5185         u64 l;
5186         int again = 1;
5187
5188         while (again) {
5189                 again = 0;
5190                 for (i = 0; i < num_stripes - 1; i++) {
5191                         if (parity_smaller(bbio->raid_map[i],
5192                                            bbio->raid_map[i+1])) {
5193                                 s = bbio->stripes[i];
5194                                 l = bbio->raid_map[i];
5195                                 bbio->stripes[i] = bbio->stripes[i+1];
5196                                 bbio->raid_map[i] = bbio->raid_map[i+1];
5197                                 bbio->stripes[i+1] = s;
5198                                 bbio->raid_map[i+1] = l;
5199
5200                                 again = 1;
5201                         }
5202                 }
5203         }
5204 }
5205
5206 static struct btrfs_bio *alloc_btrfs_bio(int total_stripes, int real_stripes)
5207 {
5208         struct btrfs_bio *bbio = kzalloc(
5209                  /* the size of the btrfs_bio */
5210                 sizeof(struct btrfs_bio) +
5211                 /* plus the variable array for the stripes */
5212                 sizeof(struct btrfs_bio_stripe) * (total_stripes) +
5213                 /* plus the variable array for the tgt dev */
5214                 sizeof(int) * (real_stripes) +
5215                 /*
5216                  * plus the raid_map, which includes both the tgt dev
5217                  * and the stripes
5218                  */
5219                 sizeof(u64) * (total_stripes),
5220                 GFP_NOFS|__GFP_NOFAIL);
5221
5222         atomic_set(&bbio->error, 0);
5223         atomic_set(&bbio->refs, 1);
5224
5225         return bbio;
5226 }
5227
5228 void btrfs_get_bbio(struct btrfs_bio *bbio)
5229 {
5230         WARN_ON(!atomic_read(&bbio->refs));
5231         atomic_inc(&bbio->refs);
5232 }
5233
5234 void btrfs_put_bbio(struct btrfs_bio *bbio)
5235 {
5236         if (!bbio)
5237                 return;
5238         if (atomic_dec_and_test(&bbio->refs))
5239                 kfree(bbio);
5240 }
5241
5242 static int __btrfs_map_block(struct btrfs_fs_info *fs_info, int rw,
5243                              u64 logical, u64 *length,
5244                              struct btrfs_bio **bbio_ret,
5245                              int mirror_num, int need_raid_map)
5246 {
5247         struct extent_map *em;
5248         struct map_lookup *map;
5249         struct btrfs_mapping_tree *map_tree = &fs_info->mapping_tree;
5250         struct extent_map_tree *em_tree = &map_tree->map_tree;
5251         u64 offset;
5252         u64 stripe_offset;
5253         u64 stripe_end_offset;
5254         u64 stripe_nr;
5255         u64 stripe_nr_orig;
5256         u64 stripe_nr_end;
5257         u64 stripe_len;
5258         u32 stripe_index;
5259         int i;
5260         int ret = 0;
5261         int num_stripes;
5262         int max_errors = 0;
5263         int tgtdev_indexes = 0;
5264         struct btrfs_bio *bbio = NULL;
5265         struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
5266         int dev_replace_is_ongoing = 0;
5267         int num_alloc_stripes;
5268         int patch_the_first_stripe_for_dev_replace = 0;
5269         u64 physical_to_patch_in_first_stripe = 0;
5270         u64 raid56_full_stripe_start = (u64)-1;
5271
5272         read_lock(&em_tree->lock);
5273         em = lookup_extent_mapping(em_tree, logical, *length);
5274         read_unlock(&em_tree->lock);
5275
5276         if (!em) {
5277                 btrfs_crit(fs_info, "unable to find logical %llu len %llu",
5278                         logical, *length);
5279                 return -EINVAL;
5280         }
5281
5282         if (em->start > logical || em->start + em->len < logical) {
5283                 btrfs_crit(fs_info, "found a bad mapping, wanted %Lu, "
5284                            "found %Lu-%Lu", logical, em->start,
5285                            em->start + em->len);
5286                 free_extent_map(em);
5287                 return -EINVAL;
5288         }
5289
5290         map = em->map_lookup;
5291         offset = logical - em->start;
5292
5293         stripe_len = map->stripe_len;
5294         stripe_nr = offset;
5295         /*
5296          * stripe_nr counts the total number of stripes we have to stride
5297          * to get to this block
5298          */
5299         stripe_nr = div64_u64(stripe_nr, stripe_len);
5300
5301         stripe_offset = stripe_nr * stripe_len;
5302         BUG_ON(offset < stripe_offset);
5303
5304         /* stripe_offset is the offset of this block in its stripe*/
5305         stripe_offset = offset - stripe_offset;
5306
5307         /* if we're here for raid56, we need to know the stripe aligned start */
5308         if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5309                 unsigned long full_stripe_len = stripe_len * nr_data_stripes(map);
5310                 raid56_full_stripe_start = offset;
5311
5312                 /* allow a write of a full stripe, but make sure we don't
5313                  * allow straddling of stripes
5314                  */
5315                 raid56_full_stripe_start = div64_u64(raid56_full_stripe_start,
5316                                 full_stripe_len);
5317                 raid56_full_stripe_start *= full_stripe_len;
5318         }
5319
5320         if (rw & REQ_DISCARD) {
5321                 /* we don't discard raid56 yet */
5322                 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5323                         ret = -EOPNOTSUPP;
5324                         goto out;
5325                 }
5326                 *length = min_t(u64, em->len - offset, *length);
5327         } else if (map->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
5328                 u64 max_len;
5329                 /* For writes to RAID[56], allow a full stripeset across all disks.
5330                    For other RAID types and for RAID[56] reads, just allow a single
5331                    stripe (on a single disk). */
5332                 if ((map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) &&
5333                     (rw & REQ_WRITE)) {
5334                         max_len = stripe_len * nr_data_stripes(map) -
5335                                 (offset - raid56_full_stripe_start);
5336                 } else {
5337                         /* we limit the length of each bio to what fits in a stripe */
5338                         max_len = stripe_len - stripe_offset;
5339                 }
5340                 *length = min_t(u64, em->len - offset, max_len);
5341         } else {
5342                 *length = em->len - offset;
5343         }
5344
5345         /* This is for when we're called from btrfs_merge_bio_hook() and all
5346            it cares about is the length */
5347         if (!bbio_ret)
5348                 goto out;
5349
5350         btrfs_dev_replace_lock(dev_replace, 0);
5351         dev_replace_is_ongoing = btrfs_dev_replace_is_ongoing(dev_replace);
5352         if (!dev_replace_is_ongoing)
5353                 btrfs_dev_replace_unlock(dev_replace, 0);
5354         else
5355                 btrfs_dev_replace_set_lock_blocking(dev_replace);
5356
5357         if (dev_replace_is_ongoing && mirror_num == map->num_stripes + 1 &&
5358             !(rw & (REQ_WRITE | REQ_DISCARD | REQ_GET_READ_MIRRORS)) &&
5359             dev_replace->tgtdev != NULL) {
5360                 /*
5361                  * in dev-replace case, for repair case (that's the only
5362                  * case where the mirror is selected explicitly when
5363                  * calling btrfs_map_block), blocks left of the left cursor
5364                  * can also be read from the target drive.
5365                  * For REQ_GET_READ_MIRRORS, the target drive is added as
5366                  * the last one to the array of stripes. For READ, it also
5367                  * needs to be supported using the same mirror number.
5368                  * If the requested block is not left of the left cursor,
5369                  * EIO is returned. This can happen because btrfs_num_copies()
5370                  * returns one more in the dev-replace case.
5371                  */
5372                 u64 tmp_length = *length;
5373                 struct btrfs_bio *tmp_bbio = NULL;
5374                 int tmp_num_stripes;
5375                 u64 srcdev_devid = dev_replace->srcdev->devid;
5376                 int index_srcdev = 0;
5377                 int found = 0;
5378                 u64 physical_of_found = 0;
5379
5380                 ret = __btrfs_map_block(fs_info, REQ_GET_READ_MIRRORS,
5381                              logical, &tmp_length, &tmp_bbio, 0, 0);
5382                 if (ret) {
5383                         WARN_ON(tmp_bbio != NULL);
5384                         goto out;
5385                 }
5386
5387                 tmp_num_stripes = tmp_bbio->num_stripes;
5388                 if (mirror_num > tmp_num_stripes) {
5389                         /*
5390                          * REQ_GET_READ_MIRRORS does not contain this
5391                          * mirror, that means that the requested area
5392                          * is not left of the left cursor
5393                          */
5394                         ret = -EIO;
5395                         btrfs_put_bbio(tmp_bbio);
5396                         goto out;
5397                 }
5398
5399                 /*
5400                  * process the rest of the function using the mirror_num
5401                  * of the source drive. Therefore look it up first.
5402                  * At the end, patch the device pointer to the one of the
5403                  * target drive.
5404                  */
5405                 for (i = 0; i < tmp_num_stripes; i++) {
5406                         if (tmp_bbio->stripes[i].dev->devid != srcdev_devid)
5407                                 continue;
5408
5409                         /*
5410                          * In case of DUP, in order to keep it simple, only add
5411                          * the mirror with the lowest physical address
5412                          */
5413                         if (found &&
5414                             physical_of_found <= tmp_bbio->stripes[i].physical)
5415                                 continue;
5416
5417                         index_srcdev = i;
5418                         found = 1;
5419                         physical_of_found = tmp_bbio->stripes[i].physical;
5420                 }
5421
5422                 btrfs_put_bbio(tmp_bbio);
5423
5424                 if (!found) {
5425                         WARN_ON(1);
5426                         ret = -EIO;
5427                         goto out;
5428                 }
5429
5430                 mirror_num = index_srcdev + 1;
5431                 patch_the_first_stripe_for_dev_replace = 1;
5432                 physical_to_patch_in_first_stripe = physical_of_found;
5433         } else if (mirror_num > map->num_stripes) {
5434                 mirror_num = 0;
5435         }
5436
5437         num_stripes = 1;
5438         stripe_index = 0;
5439         stripe_nr_orig = stripe_nr;
5440         stripe_nr_end = ALIGN(offset + *length, map->stripe_len);
5441         stripe_nr_end = div_u64(stripe_nr_end, map->stripe_len);
5442         stripe_end_offset = stripe_nr_end * map->stripe_len -
5443                             (offset + *length);
5444
5445         if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
5446                 if (rw & REQ_DISCARD)
5447                         num_stripes = min_t(u64, map->num_stripes,
5448                                             stripe_nr_end - stripe_nr_orig);
5449                 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
5450                                 &stripe_index);
5451                 if (!(rw & (REQ_WRITE | REQ_DISCARD | REQ_GET_READ_MIRRORS)))
5452                         mirror_num = 1;
5453         } else if (map->type & BTRFS_BLOCK_GROUP_RAID1) {
5454                 if (rw & (REQ_WRITE | REQ_DISCARD | REQ_GET_READ_MIRRORS))
5455                         num_stripes = map->num_stripes;
5456                 else if (mirror_num)
5457                         stripe_index = mirror_num - 1;
5458                 else {
5459                         stripe_index = find_live_mirror(fs_info, map, 0,
5460                                             map->num_stripes,
5461                                             current->pid % map->num_stripes,
5462                                             dev_replace_is_ongoing);
5463                         mirror_num = stripe_index + 1;
5464                 }
5465
5466         } else if (map->type & BTRFS_BLOCK_GROUP_DUP) {
5467                 if (rw & (REQ_WRITE | REQ_DISCARD | REQ_GET_READ_MIRRORS)) {
5468                         num_stripes = map->num_stripes;
5469                 } else if (mirror_num) {
5470                         stripe_index = mirror_num - 1;
5471                 } else {
5472                         mirror_num = 1;
5473                 }
5474
5475         } else if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
5476                 u32 factor = map->num_stripes / map->sub_stripes;
5477
5478                 stripe_nr = div_u64_rem(stripe_nr, factor, &stripe_index);
5479                 stripe_index *= map->sub_stripes;
5480
5481                 if (rw & (REQ_WRITE | REQ_GET_READ_MIRRORS))
5482                         num_stripes = map->sub_stripes;
5483                 else if (rw & REQ_DISCARD)
5484                         num_stripes = min_t(u64, map->sub_stripes *
5485                                             (stripe_nr_end - stripe_nr_orig),
5486                                             map->num_stripes);
5487                 else if (mirror_num)
5488                         stripe_index += mirror_num - 1;
5489                 else {
5490                         int old_stripe_index = stripe_index;
5491                         stripe_index = find_live_mirror(fs_info, map,
5492                                               stripe_index,
5493                                               map->sub_stripes, stripe_index +
5494                                               current->pid % map->sub_stripes,
5495                                               dev_replace_is_ongoing);
5496                         mirror_num = stripe_index - old_stripe_index + 1;
5497                 }
5498
5499         } else if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5500                 if (need_raid_map &&
5501                     ((rw & (REQ_WRITE | REQ_GET_READ_MIRRORS)) ||
5502                      mirror_num > 1)) {
5503                         /* push stripe_nr back to the start of the full stripe */
5504                         stripe_nr = div_u64(raid56_full_stripe_start,
5505                                         stripe_len * nr_data_stripes(map));
5506
5507                         /* RAID[56] write or recovery. Return all stripes */
5508                         num_stripes = map->num_stripes;
5509                         max_errors = nr_parity_stripes(map);
5510
5511                         *length = map->stripe_len;
5512                         stripe_index = 0;
5513                         stripe_offset = 0;
5514                 } else {
5515                         /*
5516                          * Mirror #0 or #1 means the original data block.
5517                          * Mirror #2 is RAID5 parity block.
5518                          * Mirror #3 is RAID6 Q block.
5519                          */
5520                         stripe_nr = div_u64_rem(stripe_nr,
5521                                         nr_data_stripes(map), &stripe_index);
5522                         if (mirror_num > 1)
5523                                 stripe_index = nr_data_stripes(map) +
5524                                                 mirror_num - 2;
5525
5526                         /* We distribute the parity blocks across stripes */
5527                         div_u64_rem(stripe_nr + stripe_index, map->num_stripes,
5528                                         &stripe_index);
5529                         if (!(rw & (REQ_WRITE | REQ_DISCARD |
5530                                     REQ_GET_READ_MIRRORS)) && mirror_num <= 1)
5531                                 mirror_num = 1;
5532                 }
5533         } else {
5534                 /*
5535                  * after this, stripe_nr is the number of stripes on this
5536                  * device we have to walk to find the data, and stripe_index is
5537                  * the number of our device in the stripe array
5538                  */
5539                 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
5540                                 &stripe_index);
5541                 mirror_num = stripe_index + 1;
5542         }
5543         BUG_ON(stripe_index >= map->num_stripes);
5544
5545         num_alloc_stripes = num_stripes;
5546         if (dev_replace_is_ongoing) {
5547                 if (rw & (REQ_WRITE | REQ_DISCARD))
5548                         num_alloc_stripes <<= 1;
5549                 if (rw & REQ_GET_READ_MIRRORS)
5550                         num_alloc_stripes++;
5551                 tgtdev_indexes = num_stripes;
5552         }
5553
5554         bbio = alloc_btrfs_bio(num_alloc_stripes, tgtdev_indexes);
5555         if (!bbio) {
5556                 ret = -ENOMEM;
5557                 goto out;
5558         }
5559         if (dev_replace_is_ongoing)
5560                 bbio->tgtdev_map = (int *)(bbio->stripes + num_alloc_stripes);
5561
5562         /* build raid_map */
5563         if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK &&
5564             need_raid_map && ((rw & (REQ_WRITE | REQ_GET_READ_MIRRORS)) ||
5565             mirror_num > 1)) {
5566                 u64 tmp;
5567                 unsigned rot;
5568
5569                 bbio->raid_map = (u64 *)((void *)bbio->stripes +
5570                                  sizeof(struct btrfs_bio_stripe) *
5571                                  num_alloc_stripes +
5572                                  sizeof(int) * tgtdev_indexes);
5573
5574                 /* Work out the disk rotation on this stripe-set */
5575                 div_u64_rem(stripe_nr, num_stripes, &rot);
5576
5577                 /* Fill in the logical address of each stripe */
5578                 tmp = stripe_nr * nr_data_stripes(map);
5579                 for (i = 0; i < nr_data_stripes(map); i++)
5580                         bbio->raid_map[(i+rot) % num_stripes] =
5581                                 em->start + (tmp + i) * map->stripe_len;
5582
5583                 bbio->raid_map[(i+rot) % map->num_stripes] = RAID5_P_STRIPE;
5584                 if (map->type & BTRFS_BLOCK_GROUP_RAID6)
5585                         bbio->raid_map[(i+rot+1) % num_stripes] =
5586                                 RAID6_Q_STRIPE;
5587         }
5588
5589         if (rw & REQ_DISCARD) {
5590                 u32 factor = 0;
5591                 u32 sub_stripes = 0;
5592                 u64 stripes_per_dev = 0;
5593                 u32 remaining_stripes = 0;
5594                 u32 last_stripe = 0;
5595
5596                 if (map->type &
5597                     (BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID10)) {
5598                         if (map->type & BTRFS_BLOCK_GROUP_RAID0)
5599                                 sub_stripes = 1;
5600                         else
5601                                 sub_stripes = map->sub_stripes;
5602
5603                         factor = map->num_stripes / sub_stripes;
5604                         stripes_per_dev = div_u64_rem(stripe_nr_end -
5605                                                       stripe_nr_orig,
5606                                                       factor,
5607                                                       &remaining_stripes);
5608                         div_u64_rem(stripe_nr_end - 1, factor, &last_stripe);
5609                         last_stripe *= sub_stripes;
5610                 }
5611
5612                 for (i = 0; i < num_stripes; i++) {
5613                         bbio->stripes[i].physical =
5614                                 map->stripes[stripe_index].physical +
5615                                 stripe_offset + stripe_nr * map->stripe_len;
5616                         bbio->stripes[i].dev = map->stripes[stripe_index].dev;
5617
5618                         if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
5619                                          BTRFS_BLOCK_GROUP_RAID10)) {
5620                                 bbio->stripes[i].length = stripes_per_dev *
5621                                                           map->stripe_len;
5622
5623                                 if (i / sub_stripes < remaining_stripes)
5624                                         bbio->stripes[i].length +=
5625                                                 map->stripe_len;
5626
5627                                 /*
5628                                  * Special for the first stripe and
5629                                  * the last stripe:
5630                                  *
5631                                  * |-------|...|-------|
5632                                  *     |----------|
5633                                  *    off     end_off
5634                                  */
5635                                 if (i < sub_stripes)
5636                                         bbio->stripes[i].length -=
5637                                                 stripe_offset;
5638
5639                                 if (stripe_index >= last_stripe &&
5640                                     stripe_index <= (last_stripe +
5641                                                      sub_stripes - 1))
5642                                         bbio->stripes[i].length -=
5643                                                 stripe_end_offset;
5644
5645                                 if (i == sub_stripes - 1)
5646                                         stripe_offset = 0;
5647                         } else
5648                                 bbio->stripes[i].length = *length;
5649
5650                         stripe_index++;
5651                         if (stripe_index == map->num_stripes) {
5652                                 /* This could only happen for RAID0/10 */
5653                                 stripe_index = 0;
5654                                 stripe_nr++;
5655                         }
5656                 }
5657         } else {
5658                 for (i = 0; i < num_stripes; i++) {
5659                         bbio->stripes[i].physical =
5660                                 map->stripes[stripe_index].physical +
5661                                 stripe_offset +
5662                                 stripe_nr * map->stripe_len;
5663                         bbio->stripes[i].dev =
5664                                 map->stripes[stripe_index].dev;
5665                         stripe_index++;
5666                 }
5667         }
5668
5669         if (rw & (REQ_WRITE | REQ_GET_READ_MIRRORS))
5670                 max_errors = btrfs_chunk_max_errors(map);
5671
5672         if (bbio->raid_map)
5673                 sort_parity_stripes(bbio, num_stripes);
5674
5675         tgtdev_indexes = 0;
5676         if (dev_replace_is_ongoing && (rw & (REQ_WRITE | REQ_DISCARD)) &&
5677             dev_replace->tgtdev != NULL) {
5678                 int index_where_to_add;
5679                 u64 srcdev_devid = dev_replace->srcdev->devid;
5680
5681                 /*
5682                  * duplicate the write operations while the dev replace
5683                  * procedure is running. Since the copying of the old disk
5684                  * to the new disk takes place at run time while the
5685                  * filesystem is mounted writable, the regular write
5686                  * operations to the old disk have to be duplicated to go
5687                  * to the new disk as well.
5688                  * Note that device->missing is handled by the caller, and
5689                  * that the write to the old disk is already set up in the
5690                  * stripes array.
5691                  */
5692                 index_where_to_add = num_stripes;
5693                 for (i = 0; i < num_stripes; i++) {
5694                         if (bbio->stripes[i].dev->devid == srcdev_devid) {
5695                                 /* write to new disk, too */
5696                                 struct btrfs_bio_stripe *new =
5697                                         bbio->stripes + index_where_to_add;
5698                                 struct btrfs_bio_stripe *old =
5699                                         bbio->stripes + i;
5700
5701                                 new->physical = old->physical;
5702                                 new->length = old->length;
5703                                 new->dev = dev_replace->tgtdev;
5704                                 bbio->tgtdev_map[i] = index_where_to_add;
5705                                 index_where_to_add++;
5706                                 max_errors++;
5707                                 tgtdev_indexes++;
5708                         }
5709                 }
5710                 num_stripes = index_where_to_add;
5711         } else if (dev_replace_is_ongoing && (rw & REQ_GET_READ_MIRRORS) &&
5712                    dev_replace->tgtdev != NULL) {
5713                 u64 srcdev_devid = dev_replace->srcdev->devid;
5714                 int index_srcdev = 0;
5715                 int found = 0;
5716                 u64 physical_of_found = 0;
5717
5718                 /*
5719                  * During the dev-replace procedure, the target drive can
5720                  * also be used to read data in case it is needed to repair
5721                  * a corrupt block elsewhere. This is possible if the
5722                  * requested area is left of the left cursor. In this area,
5723                  * the target drive is a full copy of the source drive.
5724                  */
5725                 for (i = 0; i < num_stripes; i++) {
5726                         if (bbio->stripes[i].dev->devid == srcdev_devid) {
5727                                 /*
5728                                  * In case of DUP, in order to keep it
5729                                  * simple, only add the mirror with the
5730                                  * lowest physical address
5731                                  */
5732                                 if (found &&
5733                                     physical_of_found <=
5734                                      bbio->stripes[i].physical)
5735                                         continue;
5736                                 index_srcdev = i;
5737                                 found = 1;
5738                                 physical_of_found = bbio->stripes[i].physical;
5739                         }
5740                 }
5741                 if (found) {
5742                         if (physical_of_found + map->stripe_len <=
5743                             dev_replace->cursor_left) {
5744                                 struct btrfs_bio_stripe *tgtdev_stripe =
5745                                         bbio->stripes + num_stripes;
5746
5747                                 tgtdev_stripe->physical = physical_of_found;
5748                                 tgtdev_stripe->length =
5749                                         bbio->stripes[index_srcdev].length;
5750                                 tgtdev_stripe->dev = dev_replace->tgtdev;
5751                                 bbio->tgtdev_map[index_srcdev] = num_stripes;
5752
5753                                 tgtdev_indexes++;
5754                                 num_stripes++;
5755                         }
5756                 }
5757         }
5758
5759         *bbio_ret = bbio;
5760         bbio->map_type = map->type;
5761         bbio->num_stripes = num_stripes;
5762         bbio->max_errors = max_errors;
5763         bbio->mirror_num = mirror_num;
5764         bbio->num_tgtdevs = tgtdev_indexes;
5765
5766         /*
5767          * this is the case that REQ_READ && dev_replace_is_ongoing &&
5768          * mirror_num == num_stripes + 1 && dev_replace target drive is
5769          * available as a mirror
5770          */
5771         if (patch_the_first_stripe_for_dev_replace && num_stripes > 0) {
5772                 WARN_ON(num_stripes > 1);
5773                 bbio->stripes[0].dev = dev_replace->tgtdev;
5774                 bbio->stripes[0].physical = physical_to_patch_in_first_stripe;
5775                 bbio->mirror_num = map->num_stripes + 1;
5776         }
5777 out:
5778         if (dev_replace_is_ongoing) {
5779                 btrfs_dev_replace_clear_lock_blocking(dev_replace);
5780                 btrfs_dev_replace_unlock(dev_replace, 0);
5781         }
5782         free_extent_map(em);
5783         return ret;
5784 }
5785
5786 int btrfs_map_block(struct btrfs_fs_info *fs_info, int rw,
5787                       u64 logical, u64 *length,
5788                       struct btrfs_bio **bbio_ret, int mirror_num)
5789 {
5790         return __btrfs_map_block(fs_info, rw, logical, length, bbio_ret,
5791                                  mirror_num, 0);
5792 }
5793
5794 /* For Scrub/replace */
5795 int btrfs_map_sblock(struct btrfs_fs_info *fs_info, int rw,
5796                      u64 logical, u64 *length,
5797                      struct btrfs_bio **bbio_ret, int mirror_num,
5798                      int need_raid_map)
5799 {
5800         return __btrfs_map_block(fs_info, rw, logical, length, bbio_ret,
5801                                  mirror_num, need_raid_map);
5802 }
5803
5804 int btrfs_rmap_block(struct btrfs_mapping_tree *map_tree,
5805                      u64 chunk_start, u64 physical, u64 devid,
5806                      u64 **logical, int *naddrs, int *stripe_len)
5807 {
5808         struct extent_map_tree *em_tree = &map_tree->map_tree;
5809         struct extent_map *em;
5810         struct map_lookup *map;
5811         u64 *buf;
5812         u64 bytenr;
5813         u64 length;
5814         u64 stripe_nr;
5815         u64 rmap_len;
5816         int i, j, nr = 0;
5817
5818         read_lock(&em_tree->lock);
5819         em = lookup_extent_mapping(em_tree, chunk_start, 1);
5820         read_unlock(&em_tree->lock);
5821
5822         if (!em) {
5823                 printk(KERN_ERR "BTRFS: couldn't find em for chunk %Lu\n",
5824                        chunk_start);
5825                 return -EIO;
5826         }
5827
5828         if (em->start != chunk_start) {
5829                 printk(KERN_ERR "BTRFS: bad chunk start, em=%Lu, wanted=%Lu\n",
5830                        em->start, chunk_start);
5831                 free_extent_map(em);
5832                 return -EIO;
5833         }
5834         map = em->map_lookup;
5835
5836         length = em->len;
5837         rmap_len = map->stripe_len;
5838
5839         if (map->type & BTRFS_BLOCK_GROUP_RAID10)
5840                 length = div_u64(length, map->num_stripes / map->sub_stripes);
5841         else if (map->type & BTRFS_BLOCK_GROUP_RAID0)
5842                 length = div_u64(length, map->num_stripes);
5843         else if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5844                 length = div_u64(length, nr_data_stripes(map));
5845                 rmap_len = map->stripe_len * nr_data_stripes(map);
5846         }
5847
5848         buf = kcalloc(map->num_stripes, sizeof(u64), GFP_NOFS);
5849         BUG_ON(!buf); /* -ENOMEM */
5850
5851         for (i = 0; i < map->num_stripes; i++) {
5852                 if (devid && map->stripes[i].dev->devid != devid)
5853                         continue;
5854                 if (map->stripes[i].physical > physical ||
5855                     map->stripes[i].physical + length <= physical)
5856                         continue;
5857
5858                 stripe_nr = physical - map->stripes[i].physical;
5859                 stripe_nr = div_u64(stripe_nr, map->stripe_len);
5860
5861                 if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
5862                         stripe_nr = stripe_nr * map->num_stripes + i;
5863                         stripe_nr = div_u64(stripe_nr, map->sub_stripes);
5864                 } else if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
5865                         stripe_nr = stripe_nr * map->num_stripes + i;
5866                 } /* else if RAID[56], multiply by nr_data_stripes().
5867                    * Alternatively, just use rmap_len below instead of
5868                    * map->stripe_len */
5869
5870                 bytenr = chunk_start + stripe_nr * rmap_len;
5871                 WARN_ON(nr >= map->num_stripes);
5872                 for (j = 0; j < nr; j++) {
5873                         if (buf[j] == bytenr)
5874                                 break;
5875                 }
5876                 if (j == nr) {
5877                         WARN_ON(nr >= map->num_stripes);
5878                         buf[nr++] = bytenr;
5879                 }
5880         }
5881
5882         *logical = buf;
5883         *naddrs = nr;
5884         *stripe_len = rmap_len;
5885
5886         free_extent_map(em);
5887         return 0;
5888 }
5889
5890 static inline void btrfs_end_bbio(struct btrfs_bio *bbio, struct bio *bio)
5891 {
5892         bio->bi_private = bbio->private;
5893         bio->bi_end_io = bbio->end_io;
5894         bio_endio(bio);
5895
5896         btrfs_put_bbio(bbio);
5897 }
5898
5899 static void btrfs_end_bio(struct bio *bio)
5900 {
5901         struct btrfs_bio *bbio = bio->bi_private;
5902         int is_orig_bio = 0;
5903
5904         if (bio->bi_error) {
5905                 atomic_inc(&bbio->error);
5906                 if (bio->bi_error == -EIO || bio->bi_error == -EREMOTEIO) {
5907                         unsigned int stripe_index =
5908                                 btrfs_io_bio(bio)->stripe_index;
5909                         struct btrfs_device *dev;
5910
5911                         BUG_ON(stripe_index >= bbio->num_stripes);
5912                         dev = bbio->stripes[stripe_index].dev;
5913                         if (dev->bdev) {
5914                                 if (bio->bi_rw & WRITE)
5915                                         btrfs_dev_stat_inc(dev,
5916                                                 BTRFS_DEV_STAT_WRITE_ERRS);
5917                                 else
5918                                         btrfs_dev_stat_inc(dev,
5919                                                 BTRFS_DEV_STAT_READ_ERRS);
5920                                 if ((bio->bi_rw & WRITE_FLUSH) == WRITE_FLUSH)
5921                                         btrfs_dev_stat_inc(dev,
5922                                                 BTRFS_DEV_STAT_FLUSH_ERRS);
5923                                 btrfs_dev_stat_print_on_error(dev);
5924                         }
5925                 }
5926         }
5927
5928         if (bio == bbio->orig_bio)
5929                 is_orig_bio = 1;
5930
5931         btrfs_bio_counter_dec(bbio->fs_info);
5932
5933         if (atomic_dec_and_test(&bbio->stripes_pending)) {
5934                 if (!is_orig_bio) {
5935                         bio_put(bio);
5936                         bio = bbio->orig_bio;
5937                 }
5938
5939                 btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
5940                 /* only send an error to the higher layers if it is
5941                  * beyond the tolerance of the btrfs bio
5942                  */
5943                 if (atomic_read(&bbio->error) > bbio->max_errors) {
5944                         bio->bi_error = -EIO;
5945                 } else {
5946                         /*
5947                          * this bio is actually up to date, we didn't
5948                          * go over the max number of errors
5949                          */
5950                         bio->bi_error = 0;
5951                 }
5952
5953                 btrfs_end_bbio(bbio, bio);
5954         } else if (!is_orig_bio) {
5955                 bio_put(bio);
5956         }
5957 }
5958
5959 /*
5960  * see run_scheduled_bios for a description of why bios are collected for
5961  * async submit.
5962  *
5963  * This will add one bio to the pending list for a device and make sure
5964  * the work struct is scheduled.
5965  */
5966 static noinline void btrfs_schedule_bio(struct btrfs_root *root,
5967                                         struct btrfs_device *device,
5968                                         int rw, struct bio *bio)
5969 {
5970         int should_queue = 1;
5971         struct btrfs_pending_bios *pending_bios;
5972
5973         if (device->missing || !device->bdev) {
5974                 bio_io_error(bio);
5975                 return;
5976         }
5977
5978         /* don't bother with additional async steps for reads, right now */
5979         if (!(rw & REQ_WRITE)) {
5980                 bio_get(bio);
5981                 btrfsic_submit_bio(rw, bio);
5982                 bio_put(bio);
5983                 return;
5984         }
5985
5986         /*
5987          * nr_async_bios allows us to reliably return congestion to the
5988          * higher layers.  Otherwise, the async bio makes it appear we have
5989          * made progress against dirty pages when we've really just put it
5990          * on a queue for later
5991          */
5992         atomic_inc(&root->fs_info->nr_async_bios);
5993         WARN_ON(bio->bi_next);
5994         bio->bi_next = NULL;
5995         bio->bi_rw |= rw;
5996
5997         spin_lock(&device->io_lock);
5998         if (bio->bi_rw & REQ_SYNC)
5999                 pending_bios = &device->pending_sync_bios;
6000         else
6001                 pending_bios = &device->pending_bios;
6002
6003         if (pending_bios->tail)
6004                 pending_bios->tail->bi_next = bio;
6005
6006         pending_bios->tail = bio;
6007         if (!pending_bios->head)
6008                 pending_bios->head = bio;
6009         if (device->running_pending)
6010                 should_queue = 0;
6011
6012         spin_unlock(&device->io_lock);
6013
6014         if (should_queue)
6015                 btrfs_queue_work(root->fs_info->submit_workers,
6016                                  &device->work);
6017 }
6018
6019 static void submit_stripe_bio(struct btrfs_root *root, struct btrfs_bio *bbio,
6020                               struct bio *bio, u64 physical, int dev_nr,
6021                               int rw, int async)
6022 {
6023         struct btrfs_device *dev = bbio->stripes[dev_nr].dev;
6024
6025         bio->bi_private = bbio;
6026         btrfs_io_bio(bio)->stripe_index = dev_nr;
6027         bio->bi_end_io = btrfs_end_bio;
6028         bio->bi_iter.bi_sector = physical >> 9;
6029 #ifdef DEBUG
6030         {
6031                 struct rcu_string *name;
6032
6033                 rcu_read_lock();
6034                 name = rcu_dereference(dev->name);
6035                 pr_debug("btrfs_map_bio: rw %d, sector=%llu, dev=%lu "
6036                          "(%s id %llu), size=%u\n", rw,
6037                          (u64)bio->bi_iter.bi_sector, (u_long)dev->bdev->bd_dev,
6038                          name->str, dev->devid, bio->bi_iter.bi_size);
6039                 rcu_read_unlock();
6040         }
6041 #endif
6042         bio->bi_bdev = dev->bdev;
6043
6044         btrfs_bio_counter_inc_noblocked(root->fs_info);
6045
6046         if (async)
6047                 btrfs_schedule_bio(root, dev, rw, bio);
6048         else
6049                 btrfsic_submit_bio(rw, bio);
6050 }
6051
6052 static void bbio_error(struct btrfs_bio *bbio, struct bio *bio, u64 logical)
6053 {
6054         atomic_inc(&bbio->error);
6055         if (atomic_dec_and_test(&bbio->stripes_pending)) {
6056                 /* Shoud be the original bio. */
6057                 WARN_ON(bio != bbio->orig_bio);
6058
6059                 btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
6060                 bio->bi_iter.bi_sector = logical >> 9;
6061                 bio->bi_error = -EIO;
6062                 btrfs_end_bbio(bbio, bio);
6063         }
6064 }
6065
6066 int btrfs_map_bio(struct btrfs_root *root, int rw, struct bio *bio,
6067                   int mirror_num, int async_submit)
6068 {
6069         struct btrfs_device *dev;
6070         struct bio *first_bio = bio;
6071         u64 logical = (u64)bio->bi_iter.bi_sector << 9;
6072         u64 length = 0;
6073         u64 map_length;
6074         int ret;
6075         int dev_nr;
6076         int total_devs;
6077         struct btrfs_bio *bbio = NULL;
6078
6079         length = bio->bi_iter.bi_size;
6080         map_length = length;
6081
6082         btrfs_bio_counter_inc_blocked(root->fs_info);
6083         ret = __btrfs_map_block(root->fs_info, rw, logical, &map_length, &bbio,
6084                               mirror_num, 1);
6085         if (ret) {
6086                 btrfs_bio_counter_dec(root->fs_info);
6087                 return ret;
6088         }
6089
6090         total_devs = bbio->num_stripes;
6091         bbio->orig_bio = first_bio;
6092         bbio->private = first_bio->bi_private;
6093         bbio->end_io = first_bio->bi_end_io;
6094         bbio->fs_info = root->fs_info;
6095         atomic_set(&bbio->stripes_pending, bbio->num_stripes);
6096
6097         if ((bbio->map_type & BTRFS_BLOCK_GROUP_RAID56_MASK) &&
6098             ((rw & WRITE) || (mirror_num > 1))) {
6099                 /* In this case, map_length has been set to the length of
6100                    a single stripe; not the whole write */
6101                 if (rw & WRITE) {
6102                         ret = raid56_parity_write(root, bio, bbio, map_length);
6103                 } else {
6104                         ret = raid56_parity_recover(root, bio, bbio, map_length,
6105                                                     mirror_num, 1);
6106                 }
6107
6108                 btrfs_bio_counter_dec(root->fs_info);
6109                 return ret;
6110         }
6111
6112         if (map_length < length) {
6113                 btrfs_crit(root->fs_info, "mapping failed logical %llu bio len %llu len %llu",
6114                         logical, length, map_length);
6115                 BUG();
6116         }
6117
6118         for (dev_nr = 0; dev_nr < total_devs; dev_nr++) {
6119                 dev = bbio->stripes[dev_nr].dev;
6120                 if (!dev || !dev->bdev || (rw & WRITE && !dev->writeable)) {
6121                         bbio_error(bbio, first_bio, logical);
6122                         continue;
6123                 }
6124
6125                 if (dev_nr < total_devs - 1) {
6126                         bio = btrfs_bio_clone(first_bio, GFP_NOFS);
6127                         BUG_ON(!bio); /* -ENOMEM */
6128                 } else
6129                         bio = first_bio;
6130
6131                 submit_stripe_bio(root, bbio, bio,
6132                                   bbio->stripes[dev_nr].physical, dev_nr, rw,
6133                                   async_submit);
6134         }
6135         btrfs_bio_counter_dec(root->fs_info);
6136         return 0;
6137 }
6138
6139 struct btrfs_device *btrfs_find_device(struct btrfs_fs_info *fs_info, u64 devid,
6140                                        u8 *uuid, u8 *fsid)
6141 {
6142         struct btrfs_device *device;
6143         struct btrfs_fs_devices *cur_devices;
6144
6145         cur_devices = fs_info->fs_devices;
6146         while (cur_devices) {
6147                 if (!fsid ||
6148                     !memcmp(cur_devices->fsid, fsid, BTRFS_UUID_SIZE)) {
6149                         device = __find_device(&cur_devices->devices,
6150                                                devid, uuid);
6151                         if (device)
6152                                 return device;
6153                 }
6154                 cur_devices = cur_devices->seed;
6155         }
6156         return NULL;
6157 }
6158
6159 static struct btrfs_device *add_missing_dev(struct btrfs_root *root,
6160                                             struct btrfs_fs_devices *fs_devices,
6161                                             u64 devid, u8 *dev_uuid)
6162 {
6163         struct btrfs_device *device;
6164
6165         device = btrfs_alloc_device(NULL, &devid, dev_uuid);
6166         if (IS_ERR(device))
6167                 return NULL;
6168
6169         list_add(&device->dev_list, &fs_devices->devices);
6170         device->fs_devices = fs_devices;
6171         fs_devices->num_devices++;
6172
6173         device->missing = 1;
6174         fs_devices->missing_devices++;
6175
6176         return device;
6177 }
6178
6179 /**
6180  * btrfs_alloc_device - allocate struct btrfs_device
6181  * @fs_info:    used only for generating a new devid, can be NULL if
6182  *              devid is provided (i.e. @devid != NULL).
6183  * @devid:      a pointer to devid for this device.  If NULL a new devid
6184  *              is generated.
6185  * @uuid:       a pointer to UUID for this device.  If NULL a new UUID
6186  *              is generated.
6187  *
6188  * Return: a pointer to a new &struct btrfs_device on success; ERR_PTR()
6189  * on error.  Returned struct is not linked onto any lists and can be
6190  * destroyed with kfree() right away.
6191  */
6192 struct btrfs_device *btrfs_alloc_device(struct btrfs_fs_info *fs_info,
6193                                         const u64 *devid,
6194                                         const u8 *uuid)
6195 {
6196         struct btrfs_device *dev;
6197         u64 tmp;
6198
6199         if (WARN_ON(!devid && !fs_info))
6200                 return ERR_PTR(-EINVAL);
6201
6202         dev = __alloc_device();
6203         if (IS_ERR(dev))
6204                 return dev;
6205
6206         if (devid)
6207                 tmp = *devid;
6208         else {
6209                 int ret;
6210
6211                 ret = find_next_devid(fs_info, &tmp);
6212                 if (ret) {
6213                         kfree(dev);
6214                         return ERR_PTR(ret);
6215                 }
6216         }
6217         dev->devid = tmp;
6218
6219         if (uuid)
6220                 memcpy(dev->uuid, uuid, BTRFS_UUID_SIZE);
6221         else
6222                 generate_random_uuid(dev->uuid);
6223
6224         btrfs_init_work(&dev->work, btrfs_submit_helper,
6225                         pending_bios_fn, NULL, NULL);
6226
6227         return dev;
6228 }
6229
6230 static int read_one_chunk(struct btrfs_root *root, struct btrfs_key *key,
6231                           struct extent_buffer *leaf,
6232                           struct btrfs_chunk *chunk)
6233 {
6234         struct btrfs_mapping_tree *map_tree = &root->fs_info->mapping_tree;
6235         struct map_lookup *map;
6236         struct extent_map *em;
6237         u64 logical;
6238         u64 length;
6239         u64 stripe_len;
6240         u64 devid;
6241         u8 uuid[BTRFS_UUID_SIZE];
6242         int num_stripes;
6243         int ret;
6244         int i;
6245
6246         logical = key->offset;
6247         length = btrfs_chunk_length(leaf, chunk);
6248         stripe_len = btrfs_chunk_stripe_len(leaf, chunk);
6249         num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
6250         /* Validation check */
6251         if (!num_stripes) {
6252                 btrfs_err(root->fs_info, "invalid chunk num_stripes: %u",
6253                           num_stripes);
6254                 return -EIO;
6255         }
6256         if (!IS_ALIGNED(logical, root->sectorsize)) {
6257                 btrfs_err(root->fs_info,
6258                           "invalid chunk logical %llu", logical);
6259                 return -EIO;
6260         }
6261         if (!length || !IS_ALIGNED(length, root->sectorsize)) {
6262                 btrfs_err(root->fs_info,
6263                         "invalid chunk length %llu", length);
6264                 return -EIO;
6265         }
6266         if (!is_power_of_2(stripe_len)) {
6267                 btrfs_err(root->fs_info, "invalid chunk stripe length: %llu",
6268                           stripe_len);
6269                 return -EIO;
6270         }
6271         if (~(BTRFS_BLOCK_GROUP_TYPE_MASK | BTRFS_BLOCK_GROUP_PROFILE_MASK) &
6272             btrfs_chunk_type(leaf, chunk)) {
6273                 btrfs_err(root->fs_info, "unrecognized chunk type: %llu",
6274                           ~(BTRFS_BLOCK_GROUP_TYPE_MASK |
6275                             BTRFS_BLOCK_GROUP_PROFILE_MASK) &
6276                           btrfs_chunk_type(leaf, chunk));
6277                 return -EIO;
6278         }
6279
6280         read_lock(&map_tree->map_tree.lock);
6281         em = lookup_extent_mapping(&map_tree->map_tree, logical, 1);
6282         read_unlock(&map_tree->map_tree.lock);
6283
6284         /* already mapped? */
6285         if (em && em->start <= logical && em->start + em->len > logical) {
6286                 free_extent_map(em);
6287                 return 0;
6288         } else if (em) {
6289                 free_extent_map(em);
6290         }
6291
6292         em = alloc_extent_map();
6293         if (!em)
6294                 return -ENOMEM;
6295         map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
6296         if (!map) {
6297                 free_extent_map(em);
6298                 return -ENOMEM;
6299         }
6300
6301         set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
6302         em->map_lookup = map;
6303         em->start = logical;
6304         em->len = length;
6305         em->orig_start = 0;
6306         em->block_start = 0;
6307         em->block_len = em->len;
6308
6309         map->num_stripes = num_stripes;
6310         map->io_width = btrfs_chunk_io_width(leaf, chunk);
6311         map->io_align = btrfs_chunk_io_align(leaf, chunk);
6312         map->sector_size = btrfs_chunk_sector_size(leaf, chunk);
6313         map->stripe_len = btrfs_chunk_stripe_len(leaf, chunk);
6314         map->type = btrfs_chunk_type(leaf, chunk);
6315         map->sub_stripes = btrfs_chunk_sub_stripes(leaf, chunk);
6316         for (i = 0; i < num_stripes; i++) {
6317                 map->stripes[i].physical =
6318                         btrfs_stripe_offset_nr(leaf, chunk, i);
6319                 devid = btrfs_stripe_devid_nr(leaf, chunk, i);
6320                 read_extent_buffer(leaf, uuid, (unsigned long)
6321                                    btrfs_stripe_dev_uuid_nr(chunk, i),
6322                                    BTRFS_UUID_SIZE);
6323                 map->stripes[i].dev = btrfs_find_device(root->fs_info, devid,
6324                                                         uuid, NULL);
6325                 if (!map->stripes[i].dev && !btrfs_test_opt(root, DEGRADED)) {
6326                         free_extent_map(em);
6327                         return -EIO;
6328                 }
6329                 if (!map->stripes[i].dev) {
6330                         map->stripes[i].dev =
6331                                 add_missing_dev(root, root->fs_info->fs_devices,
6332                                                 devid, uuid);
6333                         if (!map->stripes[i].dev) {
6334                                 free_extent_map(em);
6335                                 return -EIO;
6336                         }
6337                         btrfs_warn(root->fs_info, "devid %llu uuid %pU is missing",
6338                                                 devid, uuid);
6339                 }
6340                 map->stripes[i].dev->in_fs_metadata = 1;
6341         }
6342
6343         write_lock(&map_tree->map_tree.lock);
6344         ret = add_extent_mapping(&map_tree->map_tree, em, 0);
6345         write_unlock(&map_tree->map_tree.lock);
6346         BUG_ON(ret); /* Tree corruption */
6347         free_extent_map(em);
6348
6349         return 0;
6350 }
6351
6352 static void fill_device_from_item(struct extent_buffer *leaf,
6353                                  struct btrfs_dev_item *dev_item,
6354                                  struct btrfs_device *device)
6355 {
6356         unsigned long ptr;
6357
6358         device->devid = btrfs_device_id(leaf, dev_item);
6359         device->disk_total_bytes = btrfs_device_total_bytes(leaf, dev_item);
6360         device->total_bytes = device->disk_total_bytes;
6361         device->commit_total_bytes = device->disk_total_bytes;
6362         device->bytes_used = btrfs_device_bytes_used(leaf, dev_item);
6363         device->commit_bytes_used = device->bytes_used;
6364         device->type = btrfs_device_type(leaf, dev_item);
6365         device->io_align = btrfs_device_io_align(leaf, dev_item);
6366         device->io_width = btrfs_device_io_width(leaf, dev_item);
6367         device->sector_size = btrfs_device_sector_size(leaf, dev_item);
6368         WARN_ON(device->devid == BTRFS_DEV_REPLACE_DEVID);
6369         device->is_tgtdev_for_dev_replace = 0;
6370
6371         ptr = btrfs_device_uuid(dev_item);
6372         read_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
6373 }
6374
6375 static struct btrfs_fs_devices *open_seed_devices(struct btrfs_root *root,
6376                                                   u8 *fsid)
6377 {
6378         struct btrfs_fs_devices *fs_devices;
6379         int ret;
6380
6381         BUG_ON(!mutex_is_locked(&uuid_mutex));
6382
6383         fs_devices = root->fs_info->fs_devices->seed;
6384         while (fs_devices) {
6385                 if (!memcmp(fs_devices->fsid, fsid, BTRFS_UUID_SIZE))
6386                         return fs_devices;
6387
6388                 fs_devices = fs_devices->seed;
6389         }
6390
6391         fs_devices = find_fsid(fsid);
6392         if (!fs_devices) {
6393                 if (!btrfs_test_opt(root, DEGRADED))
6394                         return ERR_PTR(-ENOENT);
6395
6396                 fs_devices = alloc_fs_devices(fsid);
6397                 if (IS_ERR(fs_devices))
6398                         return fs_devices;
6399
6400                 fs_devices->seeding = 1;
6401                 fs_devices->opened = 1;
6402                 return fs_devices;
6403         }
6404
6405         fs_devices = clone_fs_devices(fs_devices);
6406         if (IS_ERR(fs_devices))
6407                 return fs_devices;
6408
6409         ret = __btrfs_open_devices(fs_devices, FMODE_READ,
6410                                    root->fs_info->bdev_holder);
6411         if (ret) {
6412                 free_fs_devices(fs_devices);
6413                 fs_devices = ERR_PTR(ret);
6414                 goto out;
6415         }
6416
6417         if (!fs_devices->seeding) {
6418                 __btrfs_close_devices(fs_devices);
6419                 free_fs_devices(fs_devices);
6420                 fs_devices = ERR_PTR(-EINVAL);
6421                 goto out;
6422         }
6423
6424         fs_devices->seed = root->fs_info->fs_devices->seed;
6425         root->fs_info->fs_devices->seed = fs_devices;
6426 out:
6427         return fs_devices;
6428 }
6429
6430 static int read_one_dev(struct btrfs_root *root,
6431                         struct extent_buffer *leaf,
6432                         struct btrfs_dev_item *dev_item)
6433 {
6434         struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
6435         struct btrfs_device *device;
6436         u64 devid;
6437         int ret;
6438         u8 fs_uuid[BTRFS_UUID_SIZE];
6439         u8 dev_uuid[BTRFS_UUID_SIZE];
6440
6441         devid = btrfs_device_id(leaf, dev_item);
6442         read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
6443                            BTRFS_UUID_SIZE);
6444         read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
6445                            BTRFS_UUID_SIZE);
6446
6447         if (memcmp(fs_uuid, root->fs_info->fsid, BTRFS_UUID_SIZE)) {
6448                 fs_devices = open_seed_devices(root, fs_uuid);
6449                 if (IS_ERR(fs_devices))
6450                         return PTR_ERR(fs_devices);
6451         }
6452
6453         device = btrfs_find_device(root->fs_info, devid, dev_uuid, fs_uuid);
6454         if (!device) {
6455                 if (!btrfs_test_opt(root, DEGRADED))
6456                         return -EIO;
6457
6458                 device = add_missing_dev(root, fs_devices, devid, dev_uuid);
6459                 if (!device)
6460                         return -ENOMEM;
6461                 btrfs_warn(root->fs_info, "devid %llu uuid %pU missing",
6462                                 devid, dev_uuid);
6463         } else {
6464                 if (!device->bdev && !btrfs_test_opt(root, DEGRADED))
6465                         return -EIO;
6466
6467                 if(!device->bdev && !device->missing) {
6468                         /*
6469                          * this happens when a device that was properly setup
6470                          * in the device info lists suddenly goes bad.
6471                          * device->bdev is NULL, and so we have to set
6472                          * device->missing to one here
6473                          */
6474                         device->fs_devices->missing_devices++;
6475                         device->missing = 1;
6476                 }
6477
6478                 /* Move the device to its own fs_devices */
6479                 if (device->fs_devices != fs_devices) {
6480                         ASSERT(device->missing);
6481
6482                         list_move(&device->dev_list, &fs_devices->devices);
6483                         device->fs_devices->num_devices--;
6484                         fs_devices->num_devices++;
6485
6486                         device->fs_devices->missing_devices--;
6487                         fs_devices->missing_devices++;
6488
6489                         device->fs_devices = fs_devices;
6490                 }
6491         }
6492
6493         if (device->fs_devices != root->fs_info->fs_devices) {
6494                 BUG_ON(device->writeable);
6495                 if (device->generation !=
6496                     btrfs_device_generation(leaf, dev_item))
6497                         return -EINVAL;
6498         }
6499
6500         fill_device_from_item(leaf, dev_item, device);
6501         device->in_fs_metadata = 1;
6502         if (device->writeable && !device->is_tgtdev_for_dev_replace) {
6503                 device->fs_devices->total_rw_bytes += device->total_bytes;
6504                 spin_lock(&root->fs_info->free_chunk_lock);
6505                 root->fs_info->free_chunk_space += device->total_bytes -
6506                         device->bytes_used;
6507                 spin_unlock(&root->fs_info->free_chunk_lock);
6508         }
6509         ret = 0;
6510         return ret;
6511 }
6512
6513 int btrfs_read_sys_array(struct btrfs_root *root)
6514 {
6515         struct btrfs_super_block *super_copy = root->fs_info->super_copy;
6516         struct extent_buffer *sb;
6517         struct btrfs_disk_key *disk_key;
6518         struct btrfs_chunk *chunk;
6519         u8 *array_ptr;
6520         unsigned long sb_array_offset;
6521         int ret = 0;
6522         u32 num_stripes;
6523         u32 array_size;
6524         u32 len = 0;
6525         u32 cur_offset;
6526         struct btrfs_key key;
6527
6528         ASSERT(BTRFS_SUPER_INFO_SIZE <= root->nodesize);
6529         /*
6530          * This will create extent buffer of nodesize, superblock size is
6531          * fixed to BTRFS_SUPER_INFO_SIZE. If nodesize > sb size, this will
6532          * overallocate but we can keep it as-is, only the first page is used.
6533          */
6534         sb = btrfs_find_create_tree_block(root, BTRFS_SUPER_INFO_OFFSET);
6535         if (!sb)
6536                 return -ENOMEM;
6537         set_extent_buffer_uptodate(sb);
6538         btrfs_set_buffer_lockdep_class(root->root_key.objectid, sb, 0);
6539         /*
6540          * The sb extent buffer is artifical and just used to read the system array.
6541          * set_extent_buffer_uptodate() call does not properly mark all it's
6542          * pages up-to-date when the page is larger: extent does not cover the
6543          * whole page and consequently check_page_uptodate does not find all
6544          * the page's extents up-to-date (the hole beyond sb),
6545          * write_extent_buffer then triggers a WARN_ON.
6546          *
6547          * Regular short extents go through mark_extent_buffer_dirty/writeback cycle,
6548          * but sb spans only this function. Add an explicit SetPageUptodate call
6549          * to silence the warning eg. on PowerPC 64.
6550          */
6551         if (PAGE_SIZE > BTRFS_SUPER_INFO_SIZE)
6552                 SetPageUptodate(sb->pages[0]);
6553
6554         write_extent_buffer(sb, super_copy, 0, BTRFS_SUPER_INFO_SIZE);
6555         array_size = btrfs_super_sys_array_size(super_copy);
6556
6557         array_ptr = super_copy->sys_chunk_array;
6558         sb_array_offset = offsetof(struct btrfs_super_block, sys_chunk_array);
6559         cur_offset = 0;
6560
6561         while (cur_offset < array_size) {
6562                 disk_key = (struct btrfs_disk_key *)array_ptr;
6563                 len = sizeof(*disk_key);
6564                 if (cur_offset + len > array_size)
6565                         goto out_short_read;
6566
6567                 btrfs_disk_key_to_cpu(&key, disk_key);
6568
6569                 array_ptr += len;
6570                 sb_array_offset += len;
6571                 cur_offset += len;
6572
6573                 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
6574                         chunk = (struct btrfs_chunk *)sb_array_offset;
6575                         /*
6576                          * At least one btrfs_chunk with one stripe must be
6577                          * present, exact stripe count check comes afterwards
6578                          */
6579                         len = btrfs_chunk_item_size(1);
6580                         if (cur_offset + len > array_size)
6581                                 goto out_short_read;
6582
6583                         num_stripes = btrfs_chunk_num_stripes(sb, chunk);
6584                         if (!num_stripes) {
6585                                 printk(KERN_ERR
6586             "BTRFS: invalid number of stripes %u in sys_array at offset %u\n",
6587                                         num_stripes, cur_offset);
6588                                 ret = -EIO;
6589                                 break;
6590                         }
6591
6592                         len = btrfs_chunk_item_size(num_stripes);
6593                         if (cur_offset + len > array_size)
6594                                 goto out_short_read;
6595
6596                         ret = read_one_chunk(root, &key, sb, chunk);
6597                         if (ret)
6598                                 break;
6599                 } else {
6600                         printk(KERN_ERR
6601                 "BTRFS: unexpected item type %u in sys_array at offset %u\n",
6602                                 (u32)key.type, cur_offset);
6603                         ret = -EIO;
6604                         break;
6605                 }
6606                 array_ptr += len;
6607                 sb_array_offset += len;
6608                 cur_offset += len;
6609         }
6610         free_extent_buffer(sb);
6611         return ret;
6612
6613 out_short_read:
6614         printk(KERN_ERR "BTRFS: sys_array too short to read %u bytes at offset %u\n",
6615                         len, cur_offset);
6616         free_extent_buffer(sb);
6617         return -EIO;
6618 }
6619
6620 int btrfs_read_chunk_tree(struct btrfs_root *root)
6621 {
6622         struct btrfs_path *path;
6623         struct extent_buffer *leaf;
6624         struct btrfs_key key;
6625         struct btrfs_key found_key;
6626         int ret;
6627         int slot;
6628
6629         root = root->fs_info->chunk_root;
6630
6631         path = btrfs_alloc_path();
6632         if (!path)
6633                 return -ENOMEM;
6634
6635         mutex_lock(&uuid_mutex);
6636         lock_chunks(root);
6637
6638         /*
6639          * Read all device items, and then all the chunk items. All
6640          * device items are found before any chunk item (their object id
6641          * is smaller than the lowest possible object id for a chunk
6642          * item - BTRFS_FIRST_CHUNK_TREE_OBJECTID).
6643          */
6644         key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
6645         key.offset = 0;
6646         key.type = 0;
6647         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6648         if (ret < 0)
6649                 goto error;
6650         while (1) {
6651                 leaf = path->nodes[0];
6652                 slot = path->slots[0];
6653                 if (slot >= btrfs_header_nritems(leaf)) {
6654                         ret = btrfs_next_leaf(root, path);
6655                         if (ret == 0)
6656                                 continue;
6657                         if (ret < 0)
6658                                 goto error;
6659                         break;
6660                 }
6661                 btrfs_item_key_to_cpu(leaf, &found_key, slot);
6662                 if (found_key.type == BTRFS_DEV_ITEM_KEY) {
6663                         struct btrfs_dev_item *dev_item;
6664                         dev_item = btrfs_item_ptr(leaf, slot,
6665                                                   struct btrfs_dev_item);
6666                         ret = read_one_dev(root, leaf, dev_item);
6667                         if (ret)
6668                                 goto error;
6669                 } else if (found_key.type == BTRFS_CHUNK_ITEM_KEY) {
6670                         struct btrfs_chunk *chunk;
6671                         chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
6672                         ret = read_one_chunk(root, &found_key, leaf, chunk);
6673                         if (ret)
6674                                 goto error;
6675                 }
6676                 path->slots[0]++;
6677         }
6678         ret = 0;
6679 error:
6680         unlock_chunks(root);
6681         mutex_unlock(&uuid_mutex);
6682
6683         btrfs_free_path(path);
6684         return ret;
6685 }
6686
6687 void btrfs_init_devices_late(struct btrfs_fs_info *fs_info)
6688 {
6689         struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
6690         struct btrfs_device *device;
6691
6692         while (fs_devices) {
6693                 mutex_lock(&fs_devices->device_list_mutex);
6694                 list_for_each_entry(device, &fs_devices->devices, dev_list)
6695                         device->dev_root = fs_info->dev_root;
6696                 mutex_unlock(&fs_devices->device_list_mutex);
6697
6698                 fs_devices = fs_devices->seed;
6699         }
6700 }
6701
6702 static void __btrfs_reset_dev_stats(struct btrfs_device *dev)
6703 {
6704         int i;
6705
6706         for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
6707                 btrfs_dev_stat_reset(dev, i);
6708 }
6709
6710 int btrfs_init_dev_stats(struct btrfs_fs_info *fs_info)
6711 {
6712         struct btrfs_key key;
6713         struct btrfs_key found_key;
6714         struct btrfs_root *dev_root = fs_info->dev_root;
6715         struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
6716         struct extent_buffer *eb;
6717         int slot;
6718         int ret = 0;
6719         struct btrfs_device *device;
6720         struct btrfs_path *path = NULL;
6721         int i;
6722
6723         path = btrfs_alloc_path();
6724         if (!path) {
6725                 ret = -ENOMEM;
6726                 goto out;
6727         }
6728
6729         mutex_lock(&fs_devices->device_list_mutex);
6730         list_for_each_entry(device, &fs_devices->devices, dev_list) {
6731                 int item_size;
6732                 struct btrfs_dev_stats_item *ptr;
6733
6734                 key.objectid = BTRFS_DEV_STATS_OBJECTID;
6735                 key.type = BTRFS_PERSISTENT_ITEM_KEY;
6736                 key.offset = device->devid;
6737                 ret = btrfs_search_slot(NULL, dev_root, &key, path, 0, 0);
6738                 if (ret) {
6739                         __btrfs_reset_dev_stats(device);
6740                         device->dev_stats_valid = 1;
6741                         btrfs_release_path(path);
6742                         continue;
6743                 }
6744                 slot = path->slots[0];
6745                 eb = path->nodes[0];
6746                 btrfs_item_key_to_cpu(eb, &found_key, slot);
6747                 item_size = btrfs_item_size_nr(eb, slot);
6748
6749                 ptr = btrfs_item_ptr(eb, slot,
6750                                      struct btrfs_dev_stats_item);
6751
6752                 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
6753                         if (item_size >= (1 + i) * sizeof(__le64))
6754                                 btrfs_dev_stat_set(device, i,
6755                                         btrfs_dev_stats_value(eb, ptr, i));
6756                         else
6757                                 btrfs_dev_stat_reset(device, i);
6758                 }
6759
6760                 device->dev_stats_valid = 1;
6761                 btrfs_dev_stat_print_on_load(device);
6762                 btrfs_release_path(path);
6763         }
6764         mutex_unlock(&fs_devices->device_list_mutex);
6765
6766 out:
6767         btrfs_free_path(path);
6768         return ret < 0 ? ret : 0;
6769 }
6770
6771 static int update_dev_stat_item(struct btrfs_trans_handle *trans,
6772                                 struct btrfs_root *dev_root,
6773                                 struct btrfs_device *device)
6774 {
6775         struct btrfs_path *path;
6776         struct btrfs_key key;
6777         struct extent_buffer *eb;
6778         struct btrfs_dev_stats_item *ptr;
6779         int ret;
6780         int i;
6781
6782         key.objectid = BTRFS_DEV_STATS_OBJECTID;
6783         key.type = BTRFS_PERSISTENT_ITEM_KEY;
6784         key.offset = device->devid;
6785
6786         path = btrfs_alloc_path();
6787         BUG_ON(!path);
6788         ret = btrfs_search_slot(trans, dev_root, &key, path, -1, 1);
6789         if (ret < 0) {
6790                 btrfs_warn_in_rcu(dev_root->fs_info,
6791                         "error %d while searching for dev_stats item for device %s",
6792                               ret, rcu_str_deref(device->name));
6793                 goto out;
6794         }
6795
6796         if (ret == 0 &&
6797             btrfs_item_size_nr(path->nodes[0], path->slots[0]) < sizeof(*ptr)) {
6798                 /* need to delete old one and insert a new one */
6799                 ret = btrfs_del_item(trans, dev_root, path);
6800                 if (ret != 0) {
6801                         btrfs_warn_in_rcu(dev_root->fs_info,
6802                                 "delete too small dev_stats item for device %s failed %d",
6803                                       rcu_str_deref(device->name), ret);
6804                         goto out;
6805                 }
6806                 ret = 1;
6807         }
6808
6809         if (ret == 1) {
6810                 /* need to insert a new item */
6811                 btrfs_release_path(path);
6812                 ret = btrfs_insert_empty_item(trans, dev_root, path,
6813                                               &key, sizeof(*ptr));
6814                 if (ret < 0) {
6815                         btrfs_warn_in_rcu(dev_root->fs_info,
6816                                 "insert dev_stats item for device %s failed %d",
6817                                 rcu_str_deref(device->name), ret);
6818                         goto out;
6819                 }
6820         }
6821
6822         eb = path->nodes[0];
6823         ptr = btrfs_item_ptr(eb, path->slots[0], struct btrfs_dev_stats_item);
6824         for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
6825                 btrfs_set_dev_stats_value(eb, ptr, i,
6826                                           btrfs_dev_stat_read(device, i));
6827         btrfs_mark_buffer_dirty(eb);
6828
6829 out:
6830         btrfs_free_path(path);
6831         return ret;
6832 }
6833
6834 /*
6835  * called from commit_transaction. Writes all changed device stats to disk.
6836  */
6837 int btrfs_run_dev_stats(struct btrfs_trans_handle *trans,
6838                         struct btrfs_fs_info *fs_info)
6839 {
6840         struct btrfs_root *dev_root = fs_info->dev_root;
6841         struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
6842         struct btrfs_device *device;
6843         int stats_cnt;
6844         int ret = 0;
6845
6846         mutex_lock(&fs_devices->device_list_mutex);
6847         list_for_each_entry(device, &fs_devices->devices, dev_list) {
6848                 if (!device->dev_stats_valid || !btrfs_dev_stats_dirty(device))
6849                         continue;
6850
6851                 stats_cnt = atomic_read(&device->dev_stats_ccnt);
6852                 ret = update_dev_stat_item(trans, dev_root, device);
6853                 if (!ret)
6854                         atomic_sub(stats_cnt, &device->dev_stats_ccnt);
6855         }
6856         mutex_unlock(&fs_devices->device_list_mutex);
6857
6858         return ret;
6859 }
6860
6861 void btrfs_dev_stat_inc_and_print(struct btrfs_device *dev, int index)
6862 {
6863         btrfs_dev_stat_inc(dev, index);
6864         btrfs_dev_stat_print_on_error(dev);
6865 }
6866
6867 static void btrfs_dev_stat_print_on_error(struct btrfs_device *dev)
6868 {
6869         if (!dev->dev_stats_valid)
6870                 return;
6871         btrfs_err_rl_in_rcu(dev->dev_root->fs_info,
6872                 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
6873                            rcu_str_deref(dev->name),
6874                            btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
6875                            btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
6876                            btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
6877                            btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
6878                            btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
6879 }
6880
6881 static void btrfs_dev_stat_print_on_load(struct btrfs_device *dev)
6882 {
6883         int i;
6884
6885         for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
6886                 if (btrfs_dev_stat_read(dev, i) != 0)
6887                         break;
6888         if (i == BTRFS_DEV_STAT_VALUES_MAX)
6889                 return; /* all values == 0, suppress message */
6890
6891         btrfs_info_in_rcu(dev->dev_root->fs_info,
6892                 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
6893                rcu_str_deref(dev->name),
6894                btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
6895                btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
6896                btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
6897                btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
6898                btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
6899 }
6900
6901 int btrfs_get_dev_stats(struct btrfs_root *root,
6902                         struct btrfs_ioctl_get_dev_stats *stats)
6903 {
6904         struct btrfs_device *dev;
6905         struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
6906         int i;
6907
6908         mutex_lock(&fs_devices->device_list_mutex);
6909         dev = btrfs_find_device(root->fs_info, stats->devid, NULL, NULL);
6910         mutex_unlock(&fs_devices->device_list_mutex);
6911
6912         if (!dev) {
6913                 btrfs_warn(root->fs_info, "get dev_stats failed, device not found");
6914                 return -ENODEV;
6915         } else if (!dev->dev_stats_valid) {
6916                 btrfs_warn(root->fs_info, "get dev_stats failed, not yet valid");
6917                 return -ENODEV;
6918         } else if (stats->flags & BTRFS_DEV_STATS_RESET) {
6919                 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
6920                         if (stats->nr_items > i)
6921                                 stats->values[i] =
6922                                         btrfs_dev_stat_read_and_reset(dev, i);
6923                         else
6924                                 btrfs_dev_stat_reset(dev, i);
6925                 }
6926         } else {
6927                 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
6928                         if (stats->nr_items > i)
6929                                 stats->values[i] = btrfs_dev_stat_read(dev, i);
6930         }
6931         if (stats->nr_items > BTRFS_DEV_STAT_VALUES_MAX)
6932                 stats->nr_items = BTRFS_DEV_STAT_VALUES_MAX;
6933         return 0;
6934 }
6935
6936 void btrfs_scratch_superblocks(struct block_device *bdev, char *device_path)
6937 {
6938         struct buffer_head *bh;
6939         struct btrfs_super_block *disk_super;
6940         int copy_num;
6941
6942         if (!bdev)
6943                 return;
6944
6945         for (copy_num = 0; copy_num < BTRFS_SUPER_MIRROR_MAX;
6946                 copy_num++) {
6947
6948                 if (btrfs_read_dev_one_super(bdev, copy_num, &bh))
6949                         continue;
6950
6951                 disk_super = (struct btrfs_super_block *)bh->b_data;
6952
6953                 memset(&disk_super->magic, 0, sizeof(disk_super->magic));
6954                 set_buffer_dirty(bh);
6955                 sync_dirty_buffer(bh);
6956                 brelse(bh);
6957         }
6958
6959         /* Notify udev that device has changed */
6960         btrfs_kobject_uevent(bdev, KOBJ_CHANGE);
6961
6962         /* Update ctime/mtime for device path for libblkid */
6963         update_dev_time(device_path);
6964 }
6965
6966 /*
6967  * Update the size of all devices, which is used for writing out the
6968  * super blocks.
6969  */
6970 void btrfs_update_commit_device_size(struct btrfs_fs_info *fs_info)
6971 {
6972         struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
6973         struct btrfs_device *curr, *next;
6974
6975         if (list_empty(&fs_devices->resized_devices))
6976                 return;
6977
6978         mutex_lock(&fs_devices->device_list_mutex);
6979         lock_chunks(fs_info->dev_root);
6980         list_for_each_entry_safe(curr, next, &fs_devices->resized_devices,
6981                                  resized_list) {
6982                 list_del_init(&curr->resized_list);
6983                 curr->commit_total_bytes = curr->disk_total_bytes;
6984         }
6985         unlock_chunks(fs_info->dev_root);
6986         mutex_unlock(&fs_devices->device_list_mutex);
6987 }
6988
6989 /* Must be invoked during the transaction commit */
6990 void btrfs_update_commit_device_bytes_used(struct btrfs_root *root,
6991                                         struct btrfs_transaction *transaction)
6992 {
6993         struct extent_map *em;
6994         struct map_lookup *map;
6995         struct btrfs_device *dev;
6996         int i;
6997
6998         if (list_empty(&transaction->pending_chunks))
6999                 return;
7000
7001         /* In order to kick the device replace finish process */
7002         lock_chunks(root);
7003         list_for_each_entry(em, &transaction->pending_chunks, list) {
7004                 map = em->map_lookup;
7005
7006                 for (i = 0; i < map->num_stripes; i++) {
7007                         dev = map->stripes[i].dev;
7008                         dev->commit_bytes_used = dev->bytes_used;
7009                 }
7010         }
7011         unlock_chunks(root);
7012 }
7013
7014 void btrfs_set_fs_info_ptr(struct btrfs_fs_info *fs_info)
7015 {
7016         struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7017         while (fs_devices) {
7018                 fs_devices->fs_info = fs_info;
7019                 fs_devices = fs_devices->seed;
7020         }
7021 }
7022
7023 void btrfs_reset_fs_info_ptr(struct btrfs_fs_info *fs_info)
7024 {
7025         struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7026         while (fs_devices) {
7027                 fs_devices->fs_info = NULL;
7028                 fs_devices = fs_devices->seed;
7029         }
7030 }
7031
7032 static void btrfs_close_one_device(struct btrfs_device *device)
7033 {
7034         struct btrfs_fs_devices *fs_devices = device->fs_devices;
7035         struct btrfs_device *new_device;
7036         struct rcu_string *name;
7037
7038         if (device->bdev)
7039                 fs_devices->open_devices--;
7040
7041         if (device->writeable &&
7042             device->devid != BTRFS_DEV_REPLACE_DEVID) {
7043                 list_del_init(&device->dev_alloc_list);
7044                 fs_devices->rw_devices--;
7045         }
7046
7047         if (device->missing)
7048                 fs_devices->missing_devices--;
7049
7050         new_device = btrfs_alloc_device(NULL, &device->devid,
7051                                         device->uuid);
7052         BUG_ON(IS_ERR(new_device)); /* -ENOMEM */
7053
7054         /* Safe because we are under uuid_mutex */
7055         if (device->name) {
7056                 name = rcu_string_strdup(device->name->str, GFP_NOFS);
7057                 BUG_ON(!name); /* -ENOMEM */
7058                 rcu_assign_pointer(new_device->name, name);
7059         }
7060
7061         list_replace_rcu(&device->dev_list, &new_device->dev_list);
7062         new_device->fs_devices = device->fs_devices;
7063
7064         call_rcu(&device->rcu, free_device);
7065 }