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