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