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