OSDN Git Service

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