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