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