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