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