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