OSDN Git Service

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