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