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