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