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