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