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