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