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