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