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