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