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