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