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