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