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