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