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