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