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