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