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