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