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