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