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