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