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