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