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