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