]> git.proxmox.com Git - mirror_ubuntu-jammy-kernel.git/blob - fs/btrfs/volumes.c
Btrfs: fix access to available allocation bits when starting balance
[mirror_ubuntu-jammy-kernel.git] / fs / btrfs / volumes.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3 * Copyright (C) 2007 Oracle. All rights reserved.
4 */
5
6 #include <linux/sched.h>
7 #include <linux/bio.h>
8 #include <linux/slab.h>
9 #include <linux/buffer_head.h>
10 #include <linux/blkdev.h>
11 #include <linux/ratelimit.h>
12 #include <linux/kthread.h>
13 #include <linux/raid/pq.h>
14 #include <linux/semaphore.h>
15 #include <linux/uuid.h>
16 #include <linux/list_sort.h>
17 #include "ctree.h"
18 #include "extent_map.h"
19 #include "disk-io.h"
20 #include "transaction.h"
21 #include "print-tree.h"
22 #include "volumes.h"
23 #include "raid56.h"
24 #include "async-thread.h"
25 #include "check-integrity.h"
26 #include "rcu-string.h"
27 #include "math.h"
28 #include "dev-replace.h"
29 #include "sysfs.h"
30
31 const struct btrfs_raid_attr btrfs_raid_array[BTRFS_NR_RAID_TYPES] = {
32 [BTRFS_RAID_RAID10] = {
33 .sub_stripes = 2,
34 .dev_stripes = 1,
35 .devs_max = 0, /* 0 == as many as possible */
36 .devs_min = 4,
37 .tolerated_failures = 1,
38 .devs_increment = 2,
39 .ncopies = 2,
40 .nparity = 0,
41 .raid_name = "raid10",
42 .bg_flag = BTRFS_BLOCK_GROUP_RAID10,
43 .mindev_error = BTRFS_ERROR_DEV_RAID10_MIN_NOT_MET,
44 },
45 [BTRFS_RAID_RAID1] = {
46 .sub_stripes = 1,
47 .dev_stripes = 1,
48 .devs_max = 2,
49 .devs_min = 2,
50 .tolerated_failures = 1,
51 .devs_increment = 2,
52 .ncopies = 2,
53 .nparity = 0,
54 .raid_name = "raid1",
55 .bg_flag = BTRFS_BLOCK_GROUP_RAID1,
56 .mindev_error = BTRFS_ERROR_DEV_RAID1_MIN_NOT_MET,
57 },
58 [BTRFS_RAID_DUP] = {
59 .sub_stripes = 1,
60 .dev_stripes = 2,
61 .devs_max = 1,
62 .devs_min = 1,
63 .tolerated_failures = 0,
64 .devs_increment = 1,
65 .ncopies = 2,
66 .nparity = 0,
67 .raid_name = "dup",
68 .bg_flag = BTRFS_BLOCK_GROUP_DUP,
69 .mindev_error = 0,
70 },
71 [BTRFS_RAID_RAID0] = {
72 .sub_stripes = 1,
73 .dev_stripes = 1,
74 .devs_max = 0,
75 .devs_min = 2,
76 .tolerated_failures = 0,
77 .devs_increment = 1,
78 .ncopies = 1,
79 .nparity = 0,
80 .raid_name = "raid0",
81 .bg_flag = BTRFS_BLOCK_GROUP_RAID0,
82 .mindev_error = 0,
83 },
84 [BTRFS_RAID_SINGLE] = {
85 .sub_stripes = 1,
86 .dev_stripes = 1,
87 .devs_max = 1,
88 .devs_min = 1,
89 .tolerated_failures = 0,
90 .devs_increment = 1,
91 .ncopies = 1,
92 .nparity = 0,
93 .raid_name = "single",
94 .bg_flag = 0,
95 .mindev_error = 0,
96 },
97 [BTRFS_RAID_RAID5] = {
98 .sub_stripes = 1,
99 .dev_stripes = 1,
100 .devs_max = 0,
101 .devs_min = 2,
102 .tolerated_failures = 1,
103 .devs_increment = 1,
104 .ncopies = 1,
105 .nparity = 1,
106 .raid_name = "raid5",
107 .bg_flag = BTRFS_BLOCK_GROUP_RAID5,
108 .mindev_error = BTRFS_ERROR_DEV_RAID5_MIN_NOT_MET,
109 },
110 [BTRFS_RAID_RAID6] = {
111 .sub_stripes = 1,
112 .dev_stripes = 1,
113 .devs_max = 0,
114 .devs_min = 3,
115 .tolerated_failures = 2,
116 .devs_increment = 1,
117 .ncopies = 1,
118 .nparity = 2,
119 .raid_name = "raid6",
120 .bg_flag = BTRFS_BLOCK_GROUP_RAID6,
121 .mindev_error = BTRFS_ERROR_DEV_RAID6_MIN_NOT_MET,
122 },
123 };
124
125 const char *get_raid_name(enum btrfs_raid_types type)
126 {
127 if (type >= BTRFS_NR_RAID_TYPES)
128 return NULL;
129
130 return btrfs_raid_array[type].raid_name;
131 }
132
133 static int init_first_rw_device(struct btrfs_trans_handle *trans,
134 struct btrfs_fs_info *fs_info);
135 static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info);
136 static void __btrfs_reset_dev_stats(struct btrfs_device *dev);
137 static void btrfs_dev_stat_print_on_error(struct btrfs_device *dev);
138 static void btrfs_dev_stat_print_on_load(struct btrfs_device *device);
139 static int __btrfs_map_block(struct btrfs_fs_info *fs_info,
140 enum btrfs_map_op op,
141 u64 logical, u64 *length,
142 struct btrfs_bio **bbio_ret,
143 int mirror_num, int need_raid_map);
144
145 /*
146 * Device locking
147 * ==============
148 *
149 * There are several mutexes that protect manipulation of devices and low-level
150 * structures like chunks but not block groups, extents or files
151 *
152 * uuid_mutex (global lock)
153 * ------------------------
154 * protects the fs_uuids list that tracks all per-fs fs_devices, resulting from
155 * the SCAN_DEV ioctl registration or from mount either implicitly (the first
156 * device) or requested by the device= mount option
157 *
158 * the mutex can be very coarse and can cover long-running operations
159 *
160 * protects: updates to fs_devices counters like missing devices, rw devices,
161 * seeding, structure cloning, openning/closing devices at mount/umount time
162 *
163 * global::fs_devs - add, remove, updates to the global list
164 *
165 * does not protect: manipulation of the fs_devices::devices list!
166 *
167 * btrfs_device::name - renames (write side), read is RCU
168 *
169 * fs_devices::device_list_mutex (per-fs, with RCU)
170 * ------------------------------------------------
171 * protects updates to fs_devices::devices, ie. adding and deleting
172 *
173 * simple list traversal with read-only actions can be done with RCU protection
174 *
175 * may be used to exclude some operations from running concurrently without any
176 * modifications to the list (see write_all_supers)
177 *
178 * balance_mutex
179 * -------------
180 * protects balance structures (status, state) and context accessed from
181 * several places (internally, ioctl)
182 *
183 * chunk_mutex
184 * -----------
185 * protects chunks, adding or removing during allocation, trim or when a new
186 * device is added/removed
187 *
188 * cleaner_mutex
189 * -------------
190 * a big lock that is held by the cleaner thread and prevents running subvolume
191 * cleaning together with relocation or delayed iputs
192 *
193 *
194 * Lock nesting
195 * ============
196 *
197 * uuid_mutex
198 * volume_mutex
199 * device_list_mutex
200 * chunk_mutex
201 * balance_mutex
202 *
203 *
204 * Exclusive operations, BTRFS_FS_EXCL_OP
205 * ======================================
206 *
207 * Maintains the exclusivity of the following operations that apply to the
208 * whole filesystem and cannot run in parallel.
209 *
210 * - Balance (*)
211 * - Device add
212 * - Device remove
213 * - Device replace (*)
214 * - Resize
215 *
216 * The device operations (as above) can be in one of the following states:
217 *
218 * - Running state
219 * - Paused state
220 * - Completed state
221 *
222 * Only device operations marked with (*) can go into the Paused state for the
223 * following reasons:
224 *
225 * - ioctl (only Balance can be Paused through ioctl)
226 * - filesystem remounted as read-only
227 * - filesystem unmounted and mounted as read-only
228 * - system power-cycle and filesystem mounted as read-only
229 * - filesystem or device errors leading to forced read-only
230 *
231 * BTRFS_FS_EXCL_OP flag is set and cleared using atomic operations.
232 * During the course of Paused state, the BTRFS_FS_EXCL_OP remains set.
233 * A device operation in Paused or Running state can be canceled or resumed
234 * either by ioctl (Balance only) or when remounted as read-write.
235 * BTRFS_FS_EXCL_OP flag is cleared when the device operation is canceled or
236 * completed.
237 */
238
239 DEFINE_MUTEX(uuid_mutex);
240 static LIST_HEAD(fs_uuids);
241 struct list_head *btrfs_get_fs_uuids(void)
242 {
243 return &fs_uuids;
244 }
245
246 /*
247 * alloc_fs_devices - allocate struct btrfs_fs_devices
248 * @fsid: if not NULL, copy the UUID to fs_devices::fsid
249 * @metadata_fsid: if not NULL, copy the UUID to fs_devices::metadata_fsid
250 *
251 * Return a pointer to a new struct btrfs_fs_devices on success, or ERR_PTR().
252 * The returned struct is not linked onto any lists and can be destroyed with
253 * kfree() right away.
254 */
255 static struct btrfs_fs_devices *alloc_fs_devices(const u8 *fsid,
256 const u8 *metadata_fsid)
257 {
258 struct btrfs_fs_devices *fs_devs;
259
260 fs_devs = kzalloc(sizeof(*fs_devs), GFP_KERNEL);
261 if (!fs_devs)
262 return ERR_PTR(-ENOMEM);
263
264 mutex_init(&fs_devs->device_list_mutex);
265
266 INIT_LIST_HEAD(&fs_devs->devices);
267 INIT_LIST_HEAD(&fs_devs->resized_devices);
268 INIT_LIST_HEAD(&fs_devs->alloc_list);
269 INIT_LIST_HEAD(&fs_devs->fs_list);
270 if (fsid)
271 memcpy(fs_devs->fsid, fsid, BTRFS_FSID_SIZE);
272
273 if (metadata_fsid)
274 memcpy(fs_devs->metadata_uuid, metadata_fsid, BTRFS_FSID_SIZE);
275 else if (fsid)
276 memcpy(fs_devs->metadata_uuid, fsid, BTRFS_FSID_SIZE);
277
278 return fs_devs;
279 }
280
281 void btrfs_free_device(struct btrfs_device *device)
282 {
283 rcu_string_free(device->name);
284 bio_put(device->flush_bio);
285 kfree(device);
286 }
287
288 static void free_fs_devices(struct btrfs_fs_devices *fs_devices)
289 {
290 struct btrfs_device *device;
291 WARN_ON(fs_devices->opened);
292 while (!list_empty(&fs_devices->devices)) {
293 device = list_entry(fs_devices->devices.next,
294 struct btrfs_device, dev_list);
295 list_del(&device->dev_list);
296 btrfs_free_device(device);
297 }
298 kfree(fs_devices);
299 }
300
301 static void btrfs_kobject_uevent(struct block_device *bdev,
302 enum kobject_action action)
303 {
304 int ret;
305
306 ret = kobject_uevent(&disk_to_dev(bdev->bd_disk)->kobj, action);
307 if (ret)
308 pr_warn("BTRFS: Sending event '%d' to kobject: '%s' (%p): failed\n",
309 action,
310 kobject_name(&disk_to_dev(bdev->bd_disk)->kobj),
311 &disk_to_dev(bdev->bd_disk)->kobj);
312 }
313
314 void __exit btrfs_cleanup_fs_uuids(void)
315 {
316 struct btrfs_fs_devices *fs_devices;
317
318 while (!list_empty(&fs_uuids)) {
319 fs_devices = list_entry(fs_uuids.next,
320 struct btrfs_fs_devices, fs_list);
321 list_del(&fs_devices->fs_list);
322 free_fs_devices(fs_devices);
323 }
324 }
325
326 /*
327 * Returns a pointer to a new btrfs_device on success; ERR_PTR() on error.
328 * Returned struct is not linked onto any lists and must be destroyed using
329 * btrfs_free_device.
330 */
331 static struct btrfs_device *__alloc_device(void)
332 {
333 struct btrfs_device *dev;
334
335 dev = kzalloc(sizeof(*dev), GFP_KERNEL);
336 if (!dev)
337 return ERR_PTR(-ENOMEM);
338
339 /*
340 * Preallocate a bio that's always going to be used for flushing device
341 * barriers and matches the device lifespan
342 */
343 dev->flush_bio = bio_alloc_bioset(GFP_KERNEL, 0, NULL);
344 if (!dev->flush_bio) {
345 kfree(dev);
346 return ERR_PTR(-ENOMEM);
347 }
348
349 INIT_LIST_HEAD(&dev->dev_list);
350 INIT_LIST_HEAD(&dev->dev_alloc_list);
351 INIT_LIST_HEAD(&dev->resized_list);
352
353 spin_lock_init(&dev->io_lock);
354
355 atomic_set(&dev->reada_in_flight, 0);
356 atomic_set(&dev->dev_stats_ccnt, 0);
357 btrfs_device_data_ordered_init(dev);
358 INIT_RADIX_TREE(&dev->reada_zones, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
359 INIT_RADIX_TREE(&dev->reada_extents, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
360
361 return dev;
362 }
363
364 /*
365 * Find a device specified by @devid or @uuid in the list of @fs_devices, or
366 * return NULL.
367 *
368 * If devid and uuid are both specified, the match must be exact, otherwise
369 * only devid is used.
370 */
371 static struct btrfs_device *find_device(struct btrfs_fs_devices *fs_devices,
372 u64 devid, const u8 *uuid)
373 {
374 struct btrfs_device *dev;
375
376 list_for_each_entry(dev, &fs_devices->devices, dev_list) {
377 if (dev->devid == devid &&
378 (!uuid || !memcmp(dev->uuid, uuid, BTRFS_UUID_SIZE))) {
379 return dev;
380 }
381 }
382 return NULL;
383 }
384
385 static noinline struct btrfs_fs_devices *find_fsid(
386 const u8 *fsid, const u8 *metadata_fsid)
387 {
388 struct btrfs_fs_devices *fs_devices;
389
390 ASSERT(fsid);
391
392 if (metadata_fsid) {
393 /*
394 * Handle scanned device having completed its fsid change but
395 * belonging to a fs_devices that was created by first scanning
396 * a device which didn't have its fsid/metadata_uuid changed
397 * at all and the CHANGING_FSID_V2 flag set.
398 */
399 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
400 if (fs_devices->fsid_change &&
401 memcmp(metadata_fsid, fs_devices->fsid,
402 BTRFS_FSID_SIZE) == 0 &&
403 memcmp(fs_devices->fsid, fs_devices->metadata_uuid,
404 BTRFS_FSID_SIZE) == 0) {
405 return fs_devices;
406 }
407 }
408 /*
409 * Handle scanned device having completed its fsid change but
410 * belonging to a fs_devices that was created by a device that
411 * has an outdated pair of fsid/metadata_uuid and
412 * CHANGING_FSID_V2 flag set.
413 */
414 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
415 if (fs_devices->fsid_change &&
416 memcmp(fs_devices->metadata_uuid,
417 fs_devices->fsid, BTRFS_FSID_SIZE) != 0 &&
418 memcmp(metadata_fsid, fs_devices->metadata_uuid,
419 BTRFS_FSID_SIZE) == 0) {
420 return fs_devices;
421 }
422 }
423 }
424
425 /* Handle non-split brain cases */
426 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
427 if (metadata_fsid) {
428 if (memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE) == 0
429 && memcmp(metadata_fsid, fs_devices->metadata_uuid,
430 BTRFS_FSID_SIZE) == 0)
431 return fs_devices;
432 } else {
433 if (memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE) == 0)
434 return fs_devices;
435 }
436 }
437 return NULL;
438 }
439
440 static int
441 btrfs_get_bdev_and_sb(const char *device_path, fmode_t flags, void *holder,
442 int flush, struct block_device **bdev,
443 struct buffer_head **bh)
444 {
445 int ret;
446
447 *bdev = blkdev_get_by_path(device_path, flags, holder);
448
449 if (IS_ERR(*bdev)) {
450 ret = PTR_ERR(*bdev);
451 goto error;
452 }
453
454 if (flush)
455 filemap_write_and_wait((*bdev)->bd_inode->i_mapping);
456 ret = set_blocksize(*bdev, BTRFS_BDEV_BLOCKSIZE);
457 if (ret) {
458 blkdev_put(*bdev, flags);
459 goto error;
460 }
461 invalidate_bdev(*bdev);
462 *bh = btrfs_read_dev_super(*bdev);
463 if (IS_ERR(*bh)) {
464 ret = PTR_ERR(*bh);
465 blkdev_put(*bdev, flags);
466 goto error;
467 }
468
469 return 0;
470
471 error:
472 *bdev = NULL;
473 *bh = NULL;
474 return ret;
475 }
476
477 static void requeue_list(struct btrfs_pending_bios *pending_bios,
478 struct bio *head, struct bio *tail)
479 {
480
481 struct bio *old_head;
482
483 old_head = pending_bios->head;
484 pending_bios->head = head;
485 if (pending_bios->tail)
486 tail->bi_next = old_head;
487 else
488 pending_bios->tail = tail;
489 }
490
491 /*
492 * we try to collect pending bios for a device so we don't get a large
493 * number of procs sending bios down to the same device. This greatly
494 * improves the schedulers ability to collect and merge the bios.
495 *
496 * But, it also turns into a long list of bios to process and that is sure
497 * to eventually make the worker thread block. The solution here is to
498 * make some progress and then put this work struct back at the end of
499 * the list if the block device is congested. This way, multiple devices
500 * can make progress from a single worker thread.
501 */
502 static noinline void run_scheduled_bios(struct btrfs_device *device)
503 {
504 struct btrfs_fs_info *fs_info = device->fs_info;
505 struct bio *pending;
506 struct backing_dev_info *bdi;
507 struct btrfs_pending_bios *pending_bios;
508 struct bio *tail;
509 struct bio *cur;
510 int again = 0;
511 unsigned long num_run;
512 unsigned long batch_run = 0;
513 unsigned long last_waited = 0;
514 int force_reg = 0;
515 int sync_pending = 0;
516 struct blk_plug plug;
517
518 /*
519 * this function runs all the bios we've collected for
520 * a particular device. We don't want to wander off to
521 * another device without first sending all of these down.
522 * So, setup a plug here and finish it off before we return
523 */
524 blk_start_plug(&plug);
525
526 bdi = device->bdev->bd_bdi;
527
528 loop:
529 spin_lock(&device->io_lock);
530
531 loop_lock:
532 num_run = 0;
533
534 /* take all the bios off the list at once and process them
535 * later on (without the lock held). But, remember the
536 * tail and other pointers so the bios can be properly reinserted
537 * into the list if we hit congestion
538 */
539 if (!force_reg && device->pending_sync_bios.head) {
540 pending_bios = &device->pending_sync_bios;
541 force_reg = 1;
542 } else {
543 pending_bios = &device->pending_bios;
544 force_reg = 0;
545 }
546
547 pending = pending_bios->head;
548 tail = pending_bios->tail;
549 WARN_ON(pending && !tail);
550
551 /*
552 * if pending was null this time around, no bios need processing
553 * at all and we can stop. Otherwise it'll loop back up again
554 * and do an additional check so no bios are missed.
555 *
556 * device->running_pending is used to synchronize with the
557 * schedule_bio code.
558 */
559 if (device->pending_sync_bios.head == NULL &&
560 device->pending_bios.head == NULL) {
561 again = 0;
562 device->running_pending = 0;
563 } else {
564 again = 1;
565 device->running_pending = 1;
566 }
567
568 pending_bios->head = NULL;
569 pending_bios->tail = NULL;
570
571 spin_unlock(&device->io_lock);
572
573 while (pending) {
574
575 rmb();
576 /* we want to work on both lists, but do more bios on the
577 * sync list than the regular list
578 */
579 if ((num_run > 32 &&
580 pending_bios != &device->pending_sync_bios &&
581 device->pending_sync_bios.head) ||
582 (num_run > 64 && pending_bios == &device->pending_sync_bios &&
583 device->pending_bios.head)) {
584 spin_lock(&device->io_lock);
585 requeue_list(pending_bios, pending, tail);
586 goto loop_lock;
587 }
588
589 cur = pending;
590 pending = pending->bi_next;
591 cur->bi_next = NULL;
592
593 BUG_ON(atomic_read(&cur->__bi_cnt) == 0);
594
595 /*
596 * if we're doing the sync list, record that our
597 * plug has some sync requests on it
598 *
599 * If we're doing the regular list and there are
600 * sync requests sitting around, unplug before
601 * we add more
602 */
603 if (pending_bios == &device->pending_sync_bios) {
604 sync_pending = 1;
605 } else if (sync_pending) {
606 blk_finish_plug(&plug);
607 blk_start_plug(&plug);
608 sync_pending = 0;
609 }
610
611 btrfsic_submit_bio(cur);
612 num_run++;
613 batch_run++;
614
615 cond_resched();
616
617 /*
618 * we made progress, there is more work to do and the bdi
619 * is now congested. Back off and let other work structs
620 * run instead
621 */
622 if (pending && bdi_write_congested(bdi) && batch_run > 8 &&
623 fs_info->fs_devices->open_devices > 1) {
624 struct io_context *ioc;
625
626 ioc = current->io_context;
627
628 /*
629 * the main goal here is that we don't want to
630 * block if we're going to be able to submit
631 * more requests without blocking.
632 *
633 * This code does two great things, it pokes into
634 * the elevator code from a filesystem _and_
635 * it makes assumptions about how batching works.
636 */
637 if (ioc && ioc->nr_batch_requests > 0 &&
638 time_before(jiffies, ioc->last_waited + HZ/50UL) &&
639 (last_waited == 0 ||
640 ioc->last_waited == last_waited)) {
641 /*
642 * we want to go through our batch of
643 * requests and stop. So, we copy out
644 * the ioc->last_waited time and test
645 * against it before looping
646 */
647 last_waited = ioc->last_waited;
648 cond_resched();
649 continue;
650 }
651 spin_lock(&device->io_lock);
652 requeue_list(pending_bios, pending, tail);
653 device->running_pending = 1;
654
655 spin_unlock(&device->io_lock);
656 btrfs_queue_work(fs_info->submit_workers,
657 &device->work);
658 goto done;
659 }
660 }
661
662 cond_resched();
663 if (again)
664 goto loop;
665
666 spin_lock(&device->io_lock);
667 if (device->pending_bios.head || device->pending_sync_bios.head)
668 goto loop_lock;
669 spin_unlock(&device->io_lock);
670
671 done:
672 blk_finish_plug(&plug);
673 }
674
675 static void pending_bios_fn(struct btrfs_work *work)
676 {
677 struct btrfs_device *device;
678
679 device = container_of(work, struct btrfs_device, work);
680 run_scheduled_bios(device);
681 }
682
683 /*
684 * Search and remove all stale (devices which are not mounted) devices.
685 * When both inputs are NULL, it will search and release all stale devices.
686 * path: Optional. When provided will it release all unmounted devices
687 * matching this path only.
688 * skip_dev: Optional. Will skip this device when searching for the stale
689 * devices.
690 */
691 static void btrfs_free_stale_devices(const char *path,
692 struct btrfs_device *skip_device)
693 {
694 struct btrfs_fs_devices *fs_devices, *tmp_fs_devices;
695 struct btrfs_device *device, *tmp_device;
696
697 list_for_each_entry_safe(fs_devices, tmp_fs_devices, &fs_uuids, fs_list) {
698 mutex_lock(&fs_devices->device_list_mutex);
699 if (fs_devices->opened) {
700 mutex_unlock(&fs_devices->device_list_mutex);
701 continue;
702 }
703
704 list_for_each_entry_safe(device, tmp_device,
705 &fs_devices->devices, dev_list) {
706 int not_found = 0;
707
708 if (skip_device && skip_device == device)
709 continue;
710 if (path && !device->name)
711 continue;
712
713 rcu_read_lock();
714 if (path)
715 not_found = strcmp(rcu_str_deref(device->name),
716 path);
717 rcu_read_unlock();
718 if (not_found)
719 continue;
720
721 /* delete the stale device */
722 fs_devices->num_devices--;
723 list_del(&device->dev_list);
724 btrfs_free_device(device);
725
726 if (fs_devices->num_devices == 0)
727 break;
728 }
729 mutex_unlock(&fs_devices->device_list_mutex);
730 if (fs_devices->num_devices == 0) {
731 btrfs_sysfs_remove_fsid(fs_devices);
732 list_del(&fs_devices->fs_list);
733 free_fs_devices(fs_devices);
734 }
735 }
736 }
737
738 static int btrfs_open_one_device(struct btrfs_fs_devices *fs_devices,
739 struct btrfs_device *device, fmode_t flags,
740 void *holder)
741 {
742 struct request_queue *q;
743 struct block_device *bdev;
744 struct buffer_head *bh;
745 struct btrfs_super_block *disk_super;
746 u64 devid;
747 int ret;
748
749 if (device->bdev)
750 return -EINVAL;
751 if (!device->name)
752 return -EINVAL;
753
754 ret = btrfs_get_bdev_and_sb(device->name->str, flags, holder, 1,
755 &bdev, &bh);
756 if (ret)
757 return ret;
758
759 disk_super = (struct btrfs_super_block *)bh->b_data;
760 devid = btrfs_stack_device_id(&disk_super->dev_item);
761 if (devid != device->devid)
762 goto error_brelse;
763
764 if (memcmp(device->uuid, disk_super->dev_item.uuid, BTRFS_UUID_SIZE))
765 goto error_brelse;
766
767 device->generation = btrfs_super_generation(disk_super);
768
769 if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_SEEDING) {
770 if (btrfs_super_incompat_flags(disk_super) &
771 BTRFS_FEATURE_INCOMPAT_METADATA_UUID) {
772 pr_err(
773 "BTRFS: Invalid seeding and uuid-changed device detected\n");
774 goto error_brelse;
775 }
776
777 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
778 fs_devices->seeding = 1;
779 } else {
780 if (bdev_read_only(bdev))
781 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
782 else
783 set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
784 }
785
786 q = bdev_get_queue(bdev);
787 if (!blk_queue_nonrot(q))
788 fs_devices->rotating = 1;
789
790 device->bdev = bdev;
791 clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
792 device->mode = flags;
793
794 fs_devices->open_devices++;
795 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
796 device->devid != BTRFS_DEV_REPLACE_DEVID) {
797 fs_devices->rw_devices++;
798 list_add_tail(&device->dev_alloc_list, &fs_devices->alloc_list);
799 }
800 brelse(bh);
801
802 return 0;
803
804 error_brelse:
805 brelse(bh);
806 blkdev_put(bdev, flags);
807
808 return -EINVAL;
809 }
810
811 /*
812 * Handle scanned device having its CHANGING_FSID_V2 flag set and the fs_devices
813 * being created with a disk that has already completed its fsid change.
814 */
815 static struct btrfs_fs_devices *find_fsid_inprogress(
816 struct btrfs_super_block *disk_super)
817 {
818 struct btrfs_fs_devices *fs_devices;
819
820 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
821 if (memcmp(fs_devices->metadata_uuid, fs_devices->fsid,
822 BTRFS_FSID_SIZE) != 0 &&
823 memcmp(fs_devices->metadata_uuid, disk_super->fsid,
824 BTRFS_FSID_SIZE) == 0 && !fs_devices->fsid_change) {
825 return fs_devices;
826 }
827 }
828
829 return NULL;
830 }
831
832
833 static struct btrfs_fs_devices *find_fsid_changed(
834 struct btrfs_super_block *disk_super)
835 {
836 struct btrfs_fs_devices *fs_devices;
837
838 /*
839 * Handles the case where scanned device is part of an fs that had
840 * multiple successful changes of FSID but curently device didn't
841 * observe it. Meaning our fsid will be different than theirs.
842 */
843 list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
844 if (memcmp(fs_devices->metadata_uuid, fs_devices->fsid,
845 BTRFS_FSID_SIZE) != 0 &&
846 memcmp(fs_devices->metadata_uuid, disk_super->metadata_uuid,
847 BTRFS_FSID_SIZE) == 0 &&
848 memcmp(fs_devices->fsid, disk_super->fsid,
849 BTRFS_FSID_SIZE) != 0) {
850 return fs_devices;
851 }
852 }
853
854 return NULL;
855 }
856 /*
857 * Add new device to list of registered devices
858 *
859 * Returns:
860 * device pointer which was just added or updated when successful
861 * error pointer when failed
862 */
863 static noinline struct btrfs_device *device_list_add(const char *path,
864 struct btrfs_super_block *disk_super,
865 bool *new_device_added)
866 {
867 struct btrfs_device *device;
868 struct btrfs_fs_devices *fs_devices = NULL;
869 struct rcu_string *name;
870 u64 found_transid = btrfs_super_generation(disk_super);
871 u64 devid = btrfs_stack_device_id(&disk_super->dev_item);
872 bool has_metadata_uuid = (btrfs_super_incompat_flags(disk_super) &
873 BTRFS_FEATURE_INCOMPAT_METADATA_UUID);
874 bool fsid_change_in_progress = (btrfs_super_flags(disk_super) &
875 BTRFS_SUPER_FLAG_CHANGING_FSID_V2);
876
877 if (fsid_change_in_progress) {
878 if (!has_metadata_uuid) {
879 /*
880 * When we have an image which has CHANGING_FSID_V2 set
881 * it might belong to either a filesystem which has
882 * disks with completed fsid change or it might belong
883 * to fs with no UUID changes in effect, handle both.
884 */
885 fs_devices = find_fsid_inprogress(disk_super);
886 if (!fs_devices)
887 fs_devices = find_fsid(disk_super->fsid, NULL);
888 } else {
889 fs_devices = find_fsid_changed(disk_super);
890 }
891 } else if (has_metadata_uuid) {
892 fs_devices = find_fsid(disk_super->fsid,
893 disk_super->metadata_uuid);
894 } else {
895 fs_devices = find_fsid(disk_super->fsid, NULL);
896 }
897
898
899 if (!fs_devices) {
900 if (has_metadata_uuid)
901 fs_devices = alloc_fs_devices(disk_super->fsid,
902 disk_super->metadata_uuid);
903 else
904 fs_devices = alloc_fs_devices(disk_super->fsid, NULL);
905
906 fs_devices->fsid_change = fsid_change_in_progress;
907
908 if (IS_ERR(fs_devices))
909 return ERR_CAST(fs_devices);
910
911 mutex_lock(&fs_devices->device_list_mutex);
912 list_add(&fs_devices->fs_list, &fs_uuids);
913
914 device = NULL;
915 } else {
916 mutex_lock(&fs_devices->device_list_mutex);
917 device = find_device(fs_devices, devid,
918 disk_super->dev_item.uuid);
919
920 /*
921 * If this disk has been pulled into an fs devices created by
922 * a device which had the CHANGING_FSID_V2 flag then replace the
923 * metadata_uuid/fsid values of the fs_devices.
924 */
925 if (has_metadata_uuid && fs_devices->fsid_change &&
926 found_transid > fs_devices->latest_generation) {
927 memcpy(fs_devices->fsid, disk_super->fsid,
928 BTRFS_FSID_SIZE);
929 memcpy(fs_devices->metadata_uuid,
930 disk_super->metadata_uuid, BTRFS_FSID_SIZE);
931
932 fs_devices->fsid_change = false;
933 }
934 }
935
936 if (!device) {
937 if (fs_devices->opened) {
938 mutex_unlock(&fs_devices->device_list_mutex);
939 return ERR_PTR(-EBUSY);
940 }
941
942 device = btrfs_alloc_device(NULL, &devid,
943 disk_super->dev_item.uuid);
944 if (IS_ERR(device)) {
945 mutex_unlock(&fs_devices->device_list_mutex);
946 /* we can safely leave the fs_devices entry around */
947 return device;
948 }
949
950 name = rcu_string_strdup(path, GFP_NOFS);
951 if (!name) {
952 btrfs_free_device(device);
953 mutex_unlock(&fs_devices->device_list_mutex);
954 return ERR_PTR(-ENOMEM);
955 }
956 rcu_assign_pointer(device->name, name);
957
958 list_add_rcu(&device->dev_list, &fs_devices->devices);
959 fs_devices->num_devices++;
960
961 device->fs_devices = fs_devices;
962 *new_device_added = true;
963
964 if (disk_super->label[0])
965 pr_info("BTRFS: device label %s devid %llu transid %llu %s\n",
966 disk_super->label, devid, found_transid, path);
967 else
968 pr_info("BTRFS: device fsid %pU devid %llu transid %llu %s\n",
969 disk_super->fsid, devid, found_transid, path);
970
971 } else if (!device->name || strcmp(device->name->str, path)) {
972 /*
973 * When FS is already mounted.
974 * 1. If you are here and if the device->name is NULL that
975 * means this device was missing at time of FS mount.
976 * 2. If you are here and if the device->name is different
977 * from 'path' that means either
978 * a. The same device disappeared and reappeared with
979 * different name. or
980 * b. The missing-disk-which-was-replaced, has
981 * reappeared now.
982 *
983 * We must allow 1 and 2a above. But 2b would be a spurious
984 * and unintentional.
985 *
986 * Further in case of 1 and 2a above, the disk at 'path'
987 * would have missed some transaction when it was away and
988 * in case of 2a the stale bdev has to be updated as well.
989 * 2b must not be allowed at all time.
990 */
991
992 /*
993 * For now, we do allow update to btrfs_fs_device through the
994 * btrfs dev scan cli after FS has been mounted. We're still
995 * tracking a problem where systems fail mount by subvolume id
996 * when we reject replacement on a mounted FS.
997 */
998 if (!fs_devices->opened && found_transid < device->generation) {
999 /*
1000 * That is if the FS is _not_ mounted and if you
1001 * are here, that means there is more than one
1002 * disk with same uuid and devid.We keep the one
1003 * with larger generation number or the last-in if
1004 * generation are equal.
1005 */
1006 mutex_unlock(&fs_devices->device_list_mutex);
1007 return ERR_PTR(-EEXIST);
1008 }
1009
1010 /*
1011 * We are going to replace the device path for a given devid,
1012 * make sure it's the same device if the device is mounted
1013 */
1014 if (device->bdev) {
1015 struct block_device *path_bdev;
1016
1017 path_bdev = lookup_bdev(path);
1018 if (IS_ERR(path_bdev)) {
1019 mutex_unlock(&fs_devices->device_list_mutex);
1020 return ERR_CAST(path_bdev);
1021 }
1022
1023 if (device->bdev != path_bdev) {
1024 bdput(path_bdev);
1025 mutex_unlock(&fs_devices->device_list_mutex);
1026 btrfs_warn_in_rcu(device->fs_info,
1027 "duplicate device fsid:devid for %pU:%llu old:%s new:%s",
1028 disk_super->fsid, devid,
1029 rcu_str_deref(device->name), path);
1030 return ERR_PTR(-EEXIST);
1031 }
1032 bdput(path_bdev);
1033 btrfs_info_in_rcu(device->fs_info,
1034 "device fsid %pU devid %llu moved old:%s new:%s",
1035 disk_super->fsid, devid,
1036 rcu_str_deref(device->name), path);
1037 }
1038
1039 name = rcu_string_strdup(path, GFP_NOFS);
1040 if (!name) {
1041 mutex_unlock(&fs_devices->device_list_mutex);
1042 return ERR_PTR(-ENOMEM);
1043 }
1044 rcu_string_free(device->name);
1045 rcu_assign_pointer(device->name, name);
1046 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
1047 fs_devices->missing_devices--;
1048 clear_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
1049 }
1050 }
1051
1052 /*
1053 * Unmount does not free the btrfs_device struct but would zero
1054 * generation along with most of the other members. So just update
1055 * it back. We need it to pick the disk with largest generation
1056 * (as above).
1057 */
1058 if (!fs_devices->opened) {
1059 device->generation = found_transid;
1060 fs_devices->latest_generation = max_t(u64, found_transid,
1061 fs_devices->latest_generation);
1062 }
1063
1064 fs_devices->total_devices = btrfs_super_num_devices(disk_super);
1065
1066 mutex_unlock(&fs_devices->device_list_mutex);
1067 return device;
1068 }
1069
1070 static struct btrfs_fs_devices *clone_fs_devices(struct btrfs_fs_devices *orig)
1071 {
1072 struct btrfs_fs_devices *fs_devices;
1073 struct btrfs_device *device;
1074 struct btrfs_device *orig_dev;
1075
1076 fs_devices = alloc_fs_devices(orig->fsid, NULL);
1077 if (IS_ERR(fs_devices))
1078 return fs_devices;
1079
1080 mutex_lock(&orig->device_list_mutex);
1081 fs_devices->total_devices = orig->total_devices;
1082
1083 /* We have held the volume lock, it is safe to get the devices. */
1084 list_for_each_entry(orig_dev, &orig->devices, dev_list) {
1085 struct rcu_string *name;
1086
1087 device = btrfs_alloc_device(NULL, &orig_dev->devid,
1088 orig_dev->uuid);
1089 if (IS_ERR(device))
1090 goto error;
1091
1092 /*
1093 * This is ok to do without rcu read locked because we hold the
1094 * uuid mutex so nothing we touch in here is going to disappear.
1095 */
1096 if (orig_dev->name) {
1097 name = rcu_string_strdup(orig_dev->name->str,
1098 GFP_KERNEL);
1099 if (!name) {
1100 btrfs_free_device(device);
1101 goto error;
1102 }
1103 rcu_assign_pointer(device->name, name);
1104 }
1105
1106 list_add(&device->dev_list, &fs_devices->devices);
1107 device->fs_devices = fs_devices;
1108 fs_devices->num_devices++;
1109 }
1110 mutex_unlock(&orig->device_list_mutex);
1111 return fs_devices;
1112 error:
1113 mutex_unlock(&orig->device_list_mutex);
1114 free_fs_devices(fs_devices);
1115 return ERR_PTR(-ENOMEM);
1116 }
1117
1118 /*
1119 * After we have read the system tree and know devids belonging to
1120 * this filesystem, remove the device which does not belong there.
1121 */
1122 void btrfs_free_extra_devids(struct btrfs_fs_devices *fs_devices, int step)
1123 {
1124 struct btrfs_device *device, *next;
1125 struct btrfs_device *latest_dev = NULL;
1126
1127 mutex_lock(&uuid_mutex);
1128 again:
1129 /* This is the initialized path, it is safe to release the devices. */
1130 list_for_each_entry_safe(device, next, &fs_devices->devices, dev_list) {
1131 if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
1132 &device->dev_state)) {
1133 if (!test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
1134 &device->dev_state) &&
1135 (!latest_dev ||
1136 device->generation > latest_dev->generation)) {
1137 latest_dev = device;
1138 }
1139 continue;
1140 }
1141
1142 if (device->devid == BTRFS_DEV_REPLACE_DEVID) {
1143 /*
1144 * In the first step, keep the device which has
1145 * the correct fsid and the devid that is used
1146 * for the dev_replace procedure.
1147 * In the second step, the dev_replace state is
1148 * read from the device tree and it is known
1149 * whether the procedure is really active or
1150 * not, which means whether this device is
1151 * used or whether it should be removed.
1152 */
1153 if (step == 0 || test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
1154 &device->dev_state)) {
1155 continue;
1156 }
1157 }
1158 if (device->bdev) {
1159 blkdev_put(device->bdev, device->mode);
1160 device->bdev = NULL;
1161 fs_devices->open_devices--;
1162 }
1163 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
1164 list_del_init(&device->dev_alloc_list);
1165 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
1166 if (!test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
1167 &device->dev_state))
1168 fs_devices->rw_devices--;
1169 }
1170 list_del_init(&device->dev_list);
1171 fs_devices->num_devices--;
1172 btrfs_free_device(device);
1173 }
1174
1175 if (fs_devices->seed) {
1176 fs_devices = fs_devices->seed;
1177 goto again;
1178 }
1179
1180 fs_devices->latest_bdev = latest_dev->bdev;
1181
1182 mutex_unlock(&uuid_mutex);
1183 }
1184
1185 static void free_device_rcu(struct rcu_head *head)
1186 {
1187 struct btrfs_device *device;
1188
1189 device = container_of(head, struct btrfs_device, rcu);
1190 btrfs_free_device(device);
1191 }
1192
1193 static void btrfs_close_bdev(struct btrfs_device *device)
1194 {
1195 if (!device->bdev)
1196 return;
1197
1198 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
1199 sync_blockdev(device->bdev);
1200 invalidate_bdev(device->bdev);
1201 }
1202
1203 blkdev_put(device->bdev, device->mode);
1204 }
1205
1206 static void btrfs_close_one_device(struct btrfs_device *device)
1207 {
1208 struct btrfs_fs_devices *fs_devices = device->fs_devices;
1209 struct btrfs_device *new_device;
1210 struct rcu_string *name;
1211
1212 if (device->bdev)
1213 fs_devices->open_devices--;
1214
1215 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
1216 device->devid != BTRFS_DEV_REPLACE_DEVID) {
1217 list_del_init(&device->dev_alloc_list);
1218 fs_devices->rw_devices--;
1219 }
1220
1221 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state))
1222 fs_devices->missing_devices--;
1223
1224 btrfs_close_bdev(device);
1225
1226 new_device = btrfs_alloc_device(NULL, &device->devid,
1227 device->uuid);
1228 BUG_ON(IS_ERR(new_device)); /* -ENOMEM */
1229
1230 /* Safe because we are under uuid_mutex */
1231 if (device->name) {
1232 name = rcu_string_strdup(device->name->str, GFP_NOFS);
1233 BUG_ON(!name); /* -ENOMEM */
1234 rcu_assign_pointer(new_device->name, name);
1235 }
1236
1237 list_replace_rcu(&device->dev_list, &new_device->dev_list);
1238 new_device->fs_devices = device->fs_devices;
1239
1240 call_rcu(&device->rcu, free_device_rcu);
1241 }
1242
1243 static int close_fs_devices(struct btrfs_fs_devices *fs_devices)
1244 {
1245 struct btrfs_device *device, *tmp;
1246
1247 if (--fs_devices->opened > 0)
1248 return 0;
1249
1250 mutex_lock(&fs_devices->device_list_mutex);
1251 list_for_each_entry_safe(device, tmp, &fs_devices->devices, dev_list) {
1252 btrfs_close_one_device(device);
1253 }
1254 mutex_unlock(&fs_devices->device_list_mutex);
1255
1256 WARN_ON(fs_devices->open_devices);
1257 WARN_ON(fs_devices->rw_devices);
1258 fs_devices->opened = 0;
1259 fs_devices->seeding = 0;
1260
1261 return 0;
1262 }
1263
1264 int btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
1265 {
1266 struct btrfs_fs_devices *seed_devices = NULL;
1267 int ret;
1268
1269 mutex_lock(&uuid_mutex);
1270 ret = close_fs_devices(fs_devices);
1271 if (!fs_devices->opened) {
1272 seed_devices = fs_devices->seed;
1273 fs_devices->seed = NULL;
1274 }
1275 mutex_unlock(&uuid_mutex);
1276
1277 while (seed_devices) {
1278 fs_devices = seed_devices;
1279 seed_devices = fs_devices->seed;
1280 close_fs_devices(fs_devices);
1281 free_fs_devices(fs_devices);
1282 }
1283 return ret;
1284 }
1285
1286 static int open_fs_devices(struct btrfs_fs_devices *fs_devices,
1287 fmode_t flags, void *holder)
1288 {
1289 struct btrfs_device *device;
1290 struct btrfs_device *latest_dev = NULL;
1291 int ret = 0;
1292
1293 flags |= FMODE_EXCL;
1294
1295 list_for_each_entry(device, &fs_devices->devices, dev_list) {
1296 /* Just open everything we can; ignore failures here */
1297 if (btrfs_open_one_device(fs_devices, device, flags, holder))
1298 continue;
1299
1300 if (!latest_dev ||
1301 device->generation > latest_dev->generation)
1302 latest_dev = device;
1303 }
1304 if (fs_devices->open_devices == 0) {
1305 ret = -EINVAL;
1306 goto out;
1307 }
1308 fs_devices->opened = 1;
1309 fs_devices->latest_bdev = latest_dev->bdev;
1310 fs_devices->total_rw_bytes = 0;
1311 out:
1312 return ret;
1313 }
1314
1315 static int devid_cmp(void *priv, struct list_head *a, struct list_head *b)
1316 {
1317 struct btrfs_device *dev1, *dev2;
1318
1319 dev1 = list_entry(a, struct btrfs_device, dev_list);
1320 dev2 = list_entry(b, struct btrfs_device, dev_list);
1321
1322 if (dev1->devid < dev2->devid)
1323 return -1;
1324 else if (dev1->devid > dev2->devid)
1325 return 1;
1326 return 0;
1327 }
1328
1329 int btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
1330 fmode_t flags, void *holder)
1331 {
1332 int ret;
1333
1334 lockdep_assert_held(&uuid_mutex);
1335
1336 mutex_lock(&fs_devices->device_list_mutex);
1337 if (fs_devices->opened) {
1338 fs_devices->opened++;
1339 ret = 0;
1340 } else {
1341 list_sort(NULL, &fs_devices->devices, devid_cmp);
1342 ret = open_fs_devices(fs_devices, flags, holder);
1343 }
1344 mutex_unlock(&fs_devices->device_list_mutex);
1345
1346 return ret;
1347 }
1348
1349 static void btrfs_release_disk_super(struct page *page)
1350 {
1351 kunmap(page);
1352 put_page(page);
1353 }
1354
1355 static int btrfs_read_disk_super(struct block_device *bdev, u64 bytenr,
1356 struct page **page,
1357 struct btrfs_super_block **disk_super)
1358 {
1359 void *p;
1360 pgoff_t index;
1361
1362 /* make sure our super fits in the device */
1363 if (bytenr + PAGE_SIZE >= i_size_read(bdev->bd_inode))
1364 return 1;
1365
1366 /* make sure our super fits in the page */
1367 if (sizeof(**disk_super) > PAGE_SIZE)
1368 return 1;
1369
1370 /* make sure our super doesn't straddle pages on disk */
1371 index = bytenr >> PAGE_SHIFT;
1372 if ((bytenr + sizeof(**disk_super) - 1) >> PAGE_SHIFT != index)
1373 return 1;
1374
1375 /* pull in the page with our super */
1376 *page = read_cache_page_gfp(bdev->bd_inode->i_mapping,
1377 index, GFP_KERNEL);
1378
1379 if (IS_ERR_OR_NULL(*page))
1380 return 1;
1381
1382 p = kmap(*page);
1383
1384 /* align our pointer to the offset of the super block */
1385 *disk_super = p + (bytenr & ~PAGE_MASK);
1386
1387 if (btrfs_super_bytenr(*disk_super) != bytenr ||
1388 btrfs_super_magic(*disk_super) != BTRFS_MAGIC) {
1389 btrfs_release_disk_super(*page);
1390 return 1;
1391 }
1392
1393 if ((*disk_super)->label[0] &&
1394 (*disk_super)->label[BTRFS_LABEL_SIZE - 1])
1395 (*disk_super)->label[BTRFS_LABEL_SIZE - 1] = '\0';
1396
1397 return 0;
1398 }
1399
1400 /*
1401 * Look for a btrfs signature on a device. This may be called out of the mount path
1402 * and we are not allowed to call set_blocksize during the scan. The superblock
1403 * is read via pagecache
1404 */
1405 struct btrfs_device *btrfs_scan_one_device(const char *path, fmode_t flags,
1406 void *holder)
1407 {
1408 struct btrfs_super_block *disk_super;
1409 bool new_device_added = false;
1410 struct btrfs_device *device = NULL;
1411 struct block_device *bdev;
1412 struct page *page;
1413 u64 bytenr;
1414
1415 lockdep_assert_held(&uuid_mutex);
1416
1417 /*
1418 * we would like to check all the supers, but that would make
1419 * a btrfs mount succeed after a mkfs from a different FS.
1420 * So, we need to add a special mount option to scan for
1421 * later supers, using BTRFS_SUPER_MIRROR_MAX instead
1422 */
1423 bytenr = btrfs_sb_offset(0);
1424 flags |= FMODE_EXCL;
1425
1426 bdev = blkdev_get_by_path(path, flags, holder);
1427 if (IS_ERR(bdev))
1428 return ERR_CAST(bdev);
1429
1430 if (btrfs_read_disk_super(bdev, bytenr, &page, &disk_super)) {
1431 device = ERR_PTR(-EINVAL);
1432 goto error_bdev_put;
1433 }
1434
1435 device = device_list_add(path, disk_super, &new_device_added);
1436 if (!IS_ERR(device)) {
1437 if (new_device_added)
1438 btrfs_free_stale_devices(path, device);
1439 }
1440
1441 btrfs_release_disk_super(page);
1442
1443 error_bdev_put:
1444 blkdev_put(bdev, flags);
1445
1446 return device;
1447 }
1448
1449 static int contains_pending_extent(struct btrfs_transaction *transaction,
1450 struct btrfs_device *device,
1451 u64 *start, u64 len)
1452 {
1453 struct btrfs_fs_info *fs_info = device->fs_info;
1454 struct extent_map *em;
1455 struct list_head *search_list = &fs_info->pinned_chunks;
1456 int ret = 0;
1457 u64 physical_start = *start;
1458
1459 if (transaction)
1460 search_list = &transaction->pending_chunks;
1461 again:
1462 list_for_each_entry(em, search_list, list) {
1463 struct map_lookup *map;
1464 int i;
1465
1466 map = em->map_lookup;
1467 for (i = 0; i < map->num_stripes; i++) {
1468 u64 end;
1469
1470 if (map->stripes[i].dev != device)
1471 continue;
1472 if (map->stripes[i].physical >= physical_start + len ||
1473 map->stripes[i].physical + em->orig_block_len <=
1474 physical_start)
1475 continue;
1476 /*
1477 * Make sure that while processing the pinned list we do
1478 * not override our *start with a lower value, because
1479 * we can have pinned chunks that fall within this
1480 * device hole and that have lower physical addresses
1481 * than the pending chunks we processed before. If we
1482 * do not take this special care we can end up getting
1483 * 2 pending chunks that start at the same physical
1484 * device offsets because the end offset of a pinned
1485 * chunk can be equal to the start offset of some
1486 * pending chunk.
1487 */
1488 end = map->stripes[i].physical + em->orig_block_len;
1489 if (end > *start) {
1490 *start = end;
1491 ret = 1;
1492 }
1493 }
1494 }
1495 if (search_list != &fs_info->pinned_chunks) {
1496 search_list = &fs_info->pinned_chunks;
1497 goto again;
1498 }
1499
1500 return ret;
1501 }
1502
1503
1504 /*
1505 * find_free_dev_extent_start - find free space in the specified device
1506 * @device: the device which we search the free space in
1507 * @num_bytes: the size of the free space that we need
1508 * @search_start: the position from which to begin the search
1509 * @start: store the start of the free space.
1510 * @len: the size of the free space. that we find, or the size
1511 * of the max free space if we don't find suitable free space
1512 *
1513 * this uses a pretty simple search, the expectation is that it is
1514 * called very infrequently and that a given device has a small number
1515 * of extents
1516 *
1517 * @start is used to store the start of the free space if we find. But if we
1518 * don't find suitable free space, it will be used to store the start position
1519 * of the max free space.
1520 *
1521 * @len is used to store the size of the free space that we find.
1522 * But if we don't find suitable free space, it is used to store the size of
1523 * the max free space.
1524 */
1525 int find_free_dev_extent_start(struct btrfs_transaction *transaction,
1526 struct btrfs_device *device, u64 num_bytes,
1527 u64 search_start, u64 *start, u64 *len)
1528 {
1529 struct btrfs_fs_info *fs_info = device->fs_info;
1530 struct btrfs_root *root = fs_info->dev_root;
1531 struct btrfs_key key;
1532 struct btrfs_dev_extent *dev_extent;
1533 struct btrfs_path *path;
1534 u64 hole_size;
1535 u64 max_hole_start;
1536 u64 max_hole_size;
1537 u64 extent_end;
1538 u64 search_end = device->total_bytes;
1539 int ret;
1540 int slot;
1541 struct extent_buffer *l;
1542
1543 /*
1544 * We don't want to overwrite the superblock on the drive nor any area
1545 * used by the boot loader (grub for example), so we make sure to start
1546 * at an offset of at least 1MB.
1547 */
1548 search_start = max_t(u64, search_start, SZ_1M);
1549
1550 path = btrfs_alloc_path();
1551 if (!path)
1552 return -ENOMEM;
1553
1554 max_hole_start = search_start;
1555 max_hole_size = 0;
1556
1557 again:
1558 if (search_start >= search_end ||
1559 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
1560 ret = -ENOSPC;
1561 goto out;
1562 }
1563
1564 path->reada = READA_FORWARD;
1565 path->search_commit_root = 1;
1566 path->skip_locking = 1;
1567
1568 key.objectid = device->devid;
1569 key.offset = search_start;
1570 key.type = BTRFS_DEV_EXTENT_KEY;
1571
1572 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1573 if (ret < 0)
1574 goto out;
1575 if (ret > 0) {
1576 ret = btrfs_previous_item(root, path, key.objectid, key.type);
1577 if (ret < 0)
1578 goto out;
1579 }
1580
1581 while (1) {
1582 l = path->nodes[0];
1583 slot = path->slots[0];
1584 if (slot >= btrfs_header_nritems(l)) {
1585 ret = btrfs_next_leaf(root, path);
1586 if (ret == 0)
1587 continue;
1588 if (ret < 0)
1589 goto out;
1590
1591 break;
1592 }
1593 btrfs_item_key_to_cpu(l, &key, slot);
1594
1595 if (key.objectid < device->devid)
1596 goto next;
1597
1598 if (key.objectid > device->devid)
1599 break;
1600
1601 if (key.type != BTRFS_DEV_EXTENT_KEY)
1602 goto next;
1603
1604 if (key.offset > search_start) {
1605 hole_size = key.offset - search_start;
1606
1607 /*
1608 * Have to check before we set max_hole_start, otherwise
1609 * we could end up sending back this offset anyway.
1610 */
1611 if (contains_pending_extent(transaction, device,
1612 &search_start,
1613 hole_size)) {
1614 if (key.offset >= search_start) {
1615 hole_size = key.offset - search_start;
1616 } else {
1617 WARN_ON_ONCE(1);
1618 hole_size = 0;
1619 }
1620 }
1621
1622 if (hole_size > max_hole_size) {
1623 max_hole_start = search_start;
1624 max_hole_size = hole_size;
1625 }
1626
1627 /*
1628 * If this free space is greater than which we need,
1629 * it must be the max free space that we have found
1630 * until now, so max_hole_start must point to the start
1631 * of this free space and the length of this free space
1632 * is stored in max_hole_size. Thus, we return
1633 * max_hole_start and max_hole_size and go back to the
1634 * caller.
1635 */
1636 if (hole_size >= num_bytes) {
1637 ret = 0;
1638 goto out;
1639 }
1640 }
1641
1642 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
1643 extent_end = key.offset + btrfs_dev_extent_length(l,
1644 dev_extent);
1645 if (extent_end > search_start)
1646 search_start = extent_end;
1647 next:
1648 path->slots[0]++;
1649 cond_resched();
1650 }
1651
1652 /*
1653 * At this point, search_start should be the end of
1654 * allocated dev extents, and when shrinking the device,
1655 * search_end may be smaller than search_start.
1656 */
1657 if (search_end > search_start) {
1658 hole_size = search_end - search_start;
1659
1660 if (contains_pending_extent(transaction, device, &search_start,
1661 hole_size)) {
1662 btrfs_release_path(path);
1663 goto again;
1664 }
1665
1666 if (hole_size > max_hole_size) {
1667 max_hole_start = search_start;
1668 max_hole_size = hole_size;
1669 }
1670 }
1671
1672 /* See above. */
1673 if (max_hole_size < num_bytes)
1674 ret = -ENOSPC;
1675 else
1676 ret = 0;
1677
1678 out:
1679 btrfs_free_path(path);
1680 *start = max_hole_start;
1681 if (len)
1682 *len = max_hole_size;
1683 return ret;
1684 }
1685
1686 int find_free_dev_extent(struct btrfs_trans_handle *trans,
1687 struct btrfs_device *device, u64 num_bytes,
1688 u64 *start, u64 *len)
1689 {
1690 /* FIXME use last free of some kind */
1691 return find_free_dev_extent_start(trans->transaction, device,
1692 num_bytes, 0, start, len);
1693 }
1694
1695 static int btrfs_free_dev_extent(struct btrfs_trans_handle *trans,
1696 struct btrfs_device *device,
1697 u64 start, u64 *dev_extent_len)
1698 {
1699 struct btrfs_fs_info *fs_info = device->fs_info;
1700 struct btrfs_root *root = fs_info->dev_root;
1701 int ret;
1702 struct btrfs_path *path;
1703 struct btrfs_key key;
1704 struct btrfs_key found_key;
1705 struct extent_buffer *leaf = NULL;
1706 struct btrfs_dev_extent *extent = NULL;
1707
1708 path = btrfs_alloc_path();
1709 if (!path)
1710 return -ENOMEM;
1711
1712 key.objectid = device->devid;
1713 key.offset = start;
1714 key.type = BTRFS_DEV_EXTENT_KEY;
1715 again:
1716 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1717 if (ret > 0) {
1718 ret = btrfs_previous_item(root, path, key.objectid,
1719 BTRFS_DEV_EXTENT_KEY);
1720 if (ret)
1721 goto out;
1722 leaf = path->nodes[0];
1723 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1724 extent = btrfs_item_ptr(leaf, path->slots[0],
1725 struct btrfs_dev_extent);
1726 BUG_ON(found_key.offset > start || found_key.offset +
1727 btrfs_dev_extent_length(leaf, extent) < start);
1728 key = found_key;
1729 btrfs_release_path(path);
1730 goto again;
1731 } else if (ret == 0) {
1732 leaf = path->nodes[0];
1733 extent = btrfs_item_ptr(leaf, path->slots[0],
1734 struct btrfs_dev_extent);
1735 } else {
1736 btrfs_handle_fs_error(fs_info, ret, "Slot search failed");
1737 goto out;
1738 }
1739
1740 *dev_extent_len = btrfs_dev_extent_length(leaf, extent);
1741
1742 ret = btrfs_del_item(trans, root, path);
1743 if (ret) {
1744 btrfs_handle_fs_error(fs_info, ret,
1745 "Failed to remove dev extent item");
1746 } else {
1747 set_bit(BTRFS_TRANS_HAVE_FREE_BGS, &trans->transaction->flags);
1748 }
1749 out:
1750 btrfs_free_path(path);
1751 return ret;
1752 }
1753
1754 static int btrfs_alloc_dev_extent(struct btrfs_trans_handle *trans,
1755 struct btrfs_device *device,
1756 u64 chunk_offset, u64 start, u64 num_bytes)
1757 {
1758 int ret;
1759 struct btrfs_path *path;
1760 struct btrfs_fs_info *fs_info = device->fs_info;
1761 struct btrfs_root *root = fs_info->dev_root;
1762 struct btrfs_dev_extent *extent;
1763 struct extent_buffer *leaf;
1764 struct btrfs_key key;
1765
1766 WARN_ON(!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state));
1767 WARN_ON(test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state));
1768 path = btrfs_alloc_path();
1769 if (!path)
1770 return -ENOMEM;
1771
1772 key.objectid = device->devid;
1773 key.offset = start;
1774 key.type = BTRFS_DEV_EXTENT_KEY;
1775 ret = btrfs_insert_empty_item(trans, root, path, &key,
1776 sizeof(*extent));
1777 if (ret)
1778 goto out;
1779
1780 leaf = path->nodes[0];
1781 extent = btrfs_item_ptr(leaf, path->slots[0],
1782 struct btrfs_dev_extent);
1783 btrfs_set_dev_extent_chunk_tree(leaf, extent,
1784 BTRFS_CHUNK_TREE_OBJECTID);
1785 btrfs_set_dev_extent_chunk_objectid(leaf, extent,
1786 BTRFS_FIRST_CHUNK_TREE_OBJECTID);
1787 btrfs_set_dev_extent_chunk_offset(leaf, extent, chunk_offset);
1788
1789 btrfs_set_dev_extent_length(leaf, extent, num_bytes);
1790 btrfs_mark_buffer_dirty(leaf);
1791 out:
1792 btrfs_free_path(path);
1793 return ret;
1794 }
1795
1796 static u64 find_next_chunk(struct btrfs_fs_info *fs_info)
1797 {
1798 struct extent_map_tree *em_tree;
1799 struct extent_map *em;
1800 struct rb_node *n;
1801 u64 ret = 0;
1802
1803 em_tree = &fs_info->mapping_tree.map_tree;
1804 read_lock(&em_tree->lock);
1805 n = rb_last(&em_tree->map.rb_root);
1806 if (n) {
1807 em = rb_entry(n, struct extent_map, rb_node);
1808 ret = em->start + em->len;
1809 }
1810 read_unlock(&em_tree->lock);
1811
1812 return ret;
1813 }
1814
1815 static noinline int find_next_devid(struct btrfs_fs_info *fs_info,
1816 u64 *devid_ret)
1817 {
1818 int ret;
1819 struct btrfs_key key;
1820 struct btrfs_key found_key;
1821 struct btrfs_path *path;
1822
1823 path = btrfs_alloc_path();
1824 if (!path)
1825 return -ENOMEM;
1826
1827 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1828 key.type = BTRFS_DEV_ITEM_KEY;
1829 key.offset = (u64)-1;
1830
1831 ret = btrfs_search_slot(NULL, fs_info->chunk_root, &key, path, 0, 0);
1832 if (ret < 0)
1833 goto error;
1834
1835 BUG_ON(ret == 0); /* Corruption */
1836
1837 ret = btrfs_previous_item(fs_info->chunk_root, path,
1838 BTRFS_DEV_ITEMS_OBJECTID,
1839 BTRFS_DEV_ITEM_KEY);
1840 if (ret) {
1841 *devid_ret = 1;
1842 } else {
1843 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
1844 path->slots[0]);
1845 *devid_ret = found_key.offset + 1;
1846 }
1847 ret = 0;
1848 error:
1849 btrfs_free_path(path);
1850 return ret;
1851 }
1852
1853 /*
1854 * the device information is stored in the chunk root
1855 * the btrfs_device struct should be fully filled in
1856 */
1857 static int btrfs_add_dev_item(struct btrfs_trans_handle *trans,
1858 struct btrfs_device *device)
1859 {
1860 int ret;
1861 struct btrfs_path *path;
1862 struct btrfs_dev_item *dev_item;
1863 struct extent_buffer *leaf;
1864 struct btrfs_key key;
1865 unsigned long ptr;
1866
1867 path = btrfs_alloc_path();
1868 if (!path)
1869 return -ENOMEM;
1870
1871 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1872 key.type = BTRFS_DEV_ITEM_KEY;
1873 key.offset = device->devid;
1874
1875 ret = btrfs_insert_empty_item(trans, trans->fs_info->chunk_root, path,
1876 &key, sizeof(*dev_item));
1877 if (ret)
1878 goto out;
1879
1880 leaf = path->nodes[0];
1881 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
1882
1883 btrfs_set_device_id(leaf, dev_item, device->devid);
1884 btrfs_set_device_generation(leaf, dev_item, 0);
1885 btrfs_set_device_type(leaf, dev_item, device->type);
1886 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
1887 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
1888 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
1889 btrfs_set_device_total_bytes(leaf, dev_item,
1890 btrfs_device_get_disk_total_bytes(device));
1891 btrfs_set_device_bytes_used(leaf, dev_item,
1892 btrfs_device_get_bytes_used(device));
1893 btrfs_set_device_group(leaf, dev_item, 0);
1894 btrfs_set_device_seek_speed(leaf, dev_item, 0);
1895 btrfs_set_device_bandwidth(leaf, dev_item, 0);
1896 btrfs_set_device_start_offset(leaf, dev_item, 0);
1897
1898 ptr = btrfs_device_uuid(dev_item);
1899 write_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
1900 ptr = btrfs_device_fsid(dev_item);
1901 write_extent_buffer(leaf, trans->fs_info->fs_devices->metadata_uuid,
1902 ptr, BTRFS_FSID_SIZE);
1903 btrfs_mark_buffer_dirty(leaf);
1904
1905 ret = 0;
1906 out:
1907 btrfs_free_path(path);
1908 return ret;
1909 }
1910
1911 /*
1912 * Function to update ctime/mtime for a given device path.
1913 * Mainly used for ctime/mtime based probe like libblkid.
1914 */
1915 static void update_dev_time(const char *path_name)
1916 {
1917 struct file *filp;
1918
1919 filp = filp_open(path_name, O_RDWR, 0);
1920 if (IS_ERR(filp))
1921 return;
1922 file_update_time(filp);
1923 filp_close(filp, NULL);
1924 }
1925
1926 static int btrfs_rm_dev_item(struct btrfs_fs_info *fs_info,
1927 struct btrfs_device *device)
1928 {
1929 struct btrfs_root *root = fs_info->chunk_root;
1930 int ret;
1931 struct btrfs_path *path;
1932 struct btrfs_key key;
1933 struct btrfs_trans_handle *trans;
1934
1935 path = btrfs_alloc_path();
1936 if (!path)
1937 return -ENOMEM;
1938
1939 trans = btrfs_start_transaction(root, 0);
1940 if (IS_ERR(trans)) {
1941 btrfs_free_path(path);
1942 return PTR_ERR(trans);
1943 }
1944 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1945 key.type = BTRFS_DEV_ITEM_KEY;
1946 key.offset = device->devid;
1947
1948 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1949 if (ret) {
1950 if (ret > 0)
1951 ret = -ENOENT;
1952 btrfs_abort_transaction(trans, ret);
1953 btrfs_end_transaction(trans);
1954 goto out;
1955 }
1956
1957 ret = btrfs_del_item(trans, root, path);
1958 if (ret) {
1959 btrfs_abort_transaction(trans, ret);
1960 btrfs_end_transaction(trans);
1961 }
1962
1963 out:
1964 btrfs_free_path(path);
1965 if (!ret)
1966 ret = btrfs_commit_transaction(trans);
1967 return ret;
1968 }
1969
1970 /*
1971 * Verify that @num_devices satisfies the RAID profile constraints in the whole
1972 * filesystem. It's up to the caller to adjust that number regarding eg. device
1973 * replace.
1974 */
1975 static int btrfs_check_raid_min_devices(struct btrfs_fs_info *fs_info,
1976 u64 num_devices)
1977 {
1978 u64 all_avail;
1979 unsigned seq;
1980 int i;
1981
1982 do {
1983 seq = read_seqbegin(&fs_info->profiles_lock);
1984
1985 all_avail = fs_info->avail_data_alloc_bits |
1986 fs_info->avail_system_alloc_bits |
1987 fs_info->avail_metadata_alloc_bits;
1988 } while (read_seqretry(&fs_info->profiles_lock, seq));
1989
1990 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
1991 if (!(all_avail & btrfs_raid_array[i].bg_flag))
1992 continue;
1993
1994 if (num_devices < btrfs_raid_array[i].devs_min) {
1995 int ret = btrfs_raid_array[i].mindev_error;
1996
1997 if (ret)
1998 return ret;
1999 }
2000 }
2001
2002 return 0;
2003 }
2004
2005 static struct btrfs_device * btrfs_find_next_active_device(
2006 struct btrfs_fs_devices *fs_devs, struct btrfs_device *device)
2007 {
2008 struct btrfs_device *next_device;
2009
2010 list_for_each_entry(next_device, &fs_devs->devices, dev_list) {
2011 if (next_device != device &&
2012 !test_bit(BTRFS_DEV_STATE_MISSING, &next_device->dev_state)
2013 && next_device->bdev)
2014 return next_device;
2015 }
2016
2017 return NULL;
2018 }
2019
2020 /*
2021 * Helper function to check if the given device is part of s_bdev / latest_bdev
2022 * and replace it with the provided or the next active device, in the context
2023 * where this function called, there should be always be another device (or
2024 * this_dev) which is active.
2025 */
2026 void btrfs_assign_next_active_device(struct btrfs_device *device,
2027 struct btrfs_device *this_dev)
2028 {
2029 struct btrfs_fs_info *fs_info = device->fs_info;
2030 struct btrfs_device *next_device;
2031
2032 if (this_dev)
2033 next_device = this_dev;
2034 else
2035 next_device = btrfs_find_next_active_device(fs_info->fs_devices,
2036 device);
2037 ASSERT(next_device);
2038
2039 if (fs_info->sb->s_bdev &&
2040 (fs_info->sb->s_bdev == device->bdev))
2041 fs_info->sb->s_bdev = next_device->bdev;
2042
2043 if (fs_info->fs_devices->latest_bdev == device->bdev)
2044 fs_info->fs_devices->latest_bdev = next_device->bdev;
2045 }
2046
2047 /*
2048 * Return btrfs_fs_devices::num_devices excluding the device that's being
2049 * currently replaced.
2050 */
2051 static u64 btrfs_num_devices(struct btrfs_fs_info *fs_info)
2052 {
2053 u64 num_devices = fs_info->fs_devices->num_devices;
2054
2055 btrfs_dev_replace_read_lock(&fs_info->dev_replace);
2056 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace)) {
2057 ASSERT(num_devices > 1);
2058 num_devices--;
2059 }
2060 btrfs_dev_replace_read_unlock(&fs_info->dev_replace);
2061
2062 return num_devices;
2063 }
2064
2065 int btrfs_rm_device(struct btrfs_fs_info *fs_info, const char *device_path,
2066 u64 devid)
2067 {
2068 struct btrfs_device *device;
2069 struct btrfs_fs_devices *cur_devices;
2070 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2071 u64 num_devices;
2072 int ret = 0;
2073
2074 mutex_lock(&uuid_mutex);
2075
2076 num_devices = btrfs_num_devices(fs_info);
2077
2078 ret = btrfs_check_raid_min_devices(fs_info, num_devices - 1);
2079 if (ret)
2080 goto out;
2081
2082 device = btrfs_find_device_by_devspec(fs_info, devid, device_path);
2083
2084 if (IS_ERR(device)) {
2085 if (PTR_ERR(device) == -ENOENT &&
2086 strcmp(device_path, "missing") == 0)
2087 ret = BTRFS_ERROR_DEV_MISSING_NOT_FOUND;
2088 else
2089 ret = PTR_ERR(device);
2090 goto out;
2091 }
2092
2093 if (btrfs_pinned_by_swapfile(fs_info, device)) {
2094 btrfs_warn_in_rcu(fs_info,
2095 "cannot remove device %s (devid %llu) due to active swapfile",
2096 rcu_str_deref(device->name), device->devid);
2097 ret = -ETXTBSY;
2098 goto out;
2099 }
2100
2101 if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
2102 ret = BTRFS_ERROR_DEV_TGT_REPLACE;
2103 goto out;
2104 }
2105
2106 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
2107 fs_info->fs_devices->rw_devices == 1) {
2108 ret = BTRFS_ERROR_DEV_ONLY_WRITABLE;
2109 goto out;
2110 }
2111
2112 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
2113 mutex_lock(&fs_info->chunk_mutex);
2114 list_del_init(&device->dev_alloc_list);
2115 device->fs_devices->rw_devices--;
2116 mutex_unlock(&fs_info->chunk_mutex);
2117 }
2118
2119 mutex_unlock(&uuid_mutex);
2120 ret = btrfs_shrink_device(device, 0);
2121 mutex_lock(&uuid_mutex);
2122 if (ret)
2123 goto error_undo;
2124
2125 /*
2126 * TODO: the superblock still includes this device in its num_devices
2127 * counter although write_all_supers() is not locked out. This
2128 * could give a filesystem state which requires a degraded mount.
2129 */
2130 ret = btrfs_rm_dev_item(fs_info, device);
2131 if (ret)
2132 goto error_undo;
2133
2134 clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
2135 btrfs_scrub_cancel_dev(fs_info, device);
2136
2137 /*
2138 * the device list mutex makes sure that we don't change
2139 * the device list while someone else is writing out all
2140 * the device supers. Whoever is writing all supers, should
2141 * lock the device list mutex before getting the number of
2142 * devices in the super block (super_copy). Conversely,
2143 * whoever updates the number of devices in the super block
2144 * (super_copy) should hold the device list mutex.
2145 */
2146
2147 /*
2148 * In normal cases the cur_devices == fs_devices. But in case
2149 * of deleting a seed device, the cur_devices should point to
2150 * its own fs_devices listed under the fs_devices->seed.
2151 */
2152 cur_devices = device->fs_devices;
2153 mutex_lock(&fs_devices->device_list_mutex);
2154 list_del_rcu(&device->dev_list);
2155
2156 cur_devices->num_devices--;
2157 cur_devices->total_devices--;
2158 /* Update total_devices of the parent fs_devices if it's seed */
2159 if (cur_devices != fs_devices)
2160 fs_devices->total_devices--;
2161
2162 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state))
2163 cur_devices->missing_devices--;
2164
2165 btrfs_assign_next_active_device(device, NULL);
2166
2167 if (device->bdev) {
2168 cur_devices->open_devices--;
2169 /* remove sysfs entry */
2170 btrfs_sysfs_rm_device_link(fs_devices, device);
2171 }
2172
2173 num_devices = btrfs_super_num_devices(fs_info->super_copy) - 1;
2174 btrfs_set_super_num_devices(fs_info->super_copy, num_devices);
2175 mutex_unlock(&fs_devices->device_list_mutex);
2176
2177 /*
2178 * at this point, the device is zero sized and detached from
2179 * the devices list. All that's left is to zero out the old
2180 * supers and free the device.
2181 */
2182 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
2183 btrfs_scratch_superblocks(device->bdev, device->name->str);
2184
2185 btrfs_close_bdev(device);
2186 call_rcu(&device->rcu, free_device_rcu);
2187
2188 if (cur_devices->open_devices == 0) {
2189 while (fs_devices) {
2190 if (fs_devices->seed == cur_devices) {
2191 fs_devices->seed = cur_devices->seed;
2192 break;
2193 }
2194 fs_devices = fs_devices->seed;
2195 }
2196 cur_devices->seed = NULL;
2197 close_fs_devices(cur_devices);
2198 free_fs_devices(cur_devices);
2199 }
2200
2201 out:
2202 mutex_unlock(&uuid_mutex);
2203 return ret;
2204
2205 error_undo:
2206 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
2207 mutex_lock(&fs_info->chunk_mutex);
2208 list_add(&device->dev_alloc_list,
2209 &fs_devices->alloc_list);
2210 device->fs_devices->rw_devices++;
2211 mutex_unlock(&fs_info->chunk_mutex);
2212 }
2213 goto out;
2214 }
2215
2216 void btrfs_rm_dev_replace_remove_srcdev(struct btrfs_device *srcdev)
2217 {
2218 struct btrfs_fs_devices *fs_devices;
2219
2220 lockdep_assert_held(&srcdev->fs_info->fs_devices->device_list_mutex);
2221
2222 /*
2223 * in case of fs with no seed, srcdev->fs_devices will point
2224 * to fs_devices of fs_info. However when the dev being replaced is
2225 * a seed dev it will point to the seed's local fs_devices. In short
2226 * srcdev will have its correct fs_devices in both the cases.
2227 */
2228 fs_devices = srcdev->fs_devices;
2229
2230 list_del_rcu(&srcdev->dev_list);
2231 list_del(&srcdev->dev_alloc_list);
2232 fs_devices->num_devices--;
2233 if (test_bit(BTRFS_DEV_STATE_MISSING, &srcdev->dev_state))
2234 fs_devices->missing_devices--;
2235
2236 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &srcdev->dev_state))
2237 fs_devices->rw_devices--;
2238
2239 if (srcdev->bdev)
2240 fs_devices->open_devices--;
2241 }
2242
2243 void btrfs_rm_dev_replace_free_srcdev(struct btrfs_fs_info *fs_info,
2244 struct btrfs_device *srcdev)
2245 {
2246 struct btrfs_fs_devices *fs_devices = srcdev->fs_devices;
2247
2248 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &srcdev->dev_state)) {
2249 /* zero out the old super if it is writable */
2250 btrfs_scratch_superblocks(srcdev->bdev, srcdev->name->str);
2251 }
2252
2253 btrfs_close_bdev(srcdev);
2254 call_rcu(&srcdev->rcu, free_device_rcu);
2255
2256 /* if this is no devs we rather delete the fs_devices */
2257 if (!fs_devices->num_devices) {
2258 struct btrfs_fs_devices *tmp_fs_devices;
2259
2260 /*
2261 * On a mounted FS, num_devices can't be zero unless it's a
2262 * seed. In case of a seed device being replaced, the replace
2263 * target added to the sprout FS, so there will be no more
2264 * device left under the seed FS.
2265 */
2266 ASSERT(fs_devices->seeding);
2267
2268 tmp_fs_devices = fs_info->fs_devices;
2269 while (tmp_fs_devices) {
2270 if (tmp_fs_devices->seed == fs_devices) {
2271 tmp_fs_devices->seed = fs_devices->seed;
2272 break;
2273 }
2274 tmp_fs_devices = tmp_fs_devices->seed;
2275 }
2276 fs_devices->seed = NULL;
2277 close_fs_devices(fs_devices);
2278 free_fs_devices(fs_devices);
2279 }
2280 }
2281
2282 void btrfs_destroy_dev_replace_tgtdev(struct btrfs_device *tgtdev)
2283 {
2284 struct btrfs_fs_devices *fs_devices = tgtdev->fs_info->fs_devices;
2285
2286 WARN_ON(!tgtdev);
2287 mutex_lock(&fs_devices->device_list_mutex);
2288
2289 btrfs_sysfs_rm_device_link(fs_devices, tgtdev);
2290
2291 if (tgtdev->bdev)
2292 fs_devices->open_devices--;
2293
2294 fs_devices->num_devices--;
2295
2296 btrfs_assign_next_active_device(tgtdev, NULL);
2297
2298 list_del_rcu(&tgtdev->dev_list);
2299
2300 mutex_unlock(&fs_devices->device_list_mutex);
2301
2302 /*
2303 * The update_dev_time() with in btrfs_scratch_superblocks()
2304 * may lead to a call to btrfs_show_devname() which will try
2305 * to hold device_list_mutex. And here this device
2306 * is already out of device list, so we don't have to hold
2307 * the device_list_mutex lock.
2308 */
2309 btrfs_scratch_superblocks(tgtdev->bdev, tgtdev->name->str);
2310
2311 btrfs_close_bdev(tgtdev);
2312 call_rcu(&tgtdev->rcu, free_device_rcu);
2313 }
2314
2315 static struct btrfs_device *btrfs_find_device_by_path(
2316 struct btrfs_fs_info *fs_info, const char *device_path)
2317 {
2318 int ret = 0;
2319 struct btrfs_super_block *disk_super;
2320 u64 devid;
2321 u8 *dev_uuid;
2322 struct block_device *bdev;
2323 struct buffer_head *bh;
2324 struct btrfs_device *device;
2325
2326 ret = btrfs_get_bdev_and_sb(device_path, FMODE_READ,
2327 fs_info->bdev_holder, 0, &bdev, &bh);
2328 if (ret)
2329 return ERR_PTR(ret);
2330 disk_super = (struct btrfs_super_block *)bh->b_data;
2331 devid = btrfs_stack_device_id(&disk_super->dev_item);
2332 dev_uuid = disk_super->dev_item.uuid;
2333 if (btrfs_fs_incompat(fs_info, METADATA_UUID))
2334 device = btrfs_find_device(fs_info, devid, dev_uuid,
2335 disk_super->metadata_uuid);
2336 else
2337 device = btrfs_find_device(fs_info, devid,
2338 dev_uuid, disk_super->fsid);
2339
2340 brelse(bh);
2341 if (!device)
2342 device = ERR_PTR(-ENOENT);
2343 blkdev_put(bdev, FMODE_READ);
2344 return device;
2345 }
2346
2347 static struct btrfs_device *btrfs_find_device_missing_or_by_path(
2348 struct btrfs_fs_info *fs_info, const char *device_path)
2349 {
2350 struct btrfs_device *device = NULL;
2351 if (strcmp(device_path, "missing") == 0) {
2352 struct list_head *devices;
2353 struct btrfs_device *tmp;
2354
2355 devices = &fs_info->fs_devices->devices;
2356 list_for_each_entry(tmp, devices, dev_list) {
2357 if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
2358 &tmp->dev_state) && !tmp->bdev) {
2359 device = tmp;
2360 break;
2361 }
2362 }
2363
2364 if (!device)
2365 return ERR_PTR(-ENOENT);
2366 } else {
2367 device = btrfs_find_device_by_path(fs_info, device_path);
2368 }
2369
2370 return device;
2371 }
2372
2373 /*
2374 * Lookup a device given by device id, or the path if the id is 0.
2375 */
2376 struct btrfs_device *btrfs_find_device_by_devspec(
2377 struct btrfs_fs_info *fs_info, u64 devid, const char *devpath)
2378 {
2379 struct btrfs_device *device;
2380
2381 if (devid) {
2382 device = btrfs_find_device(fs_info, devid, NULL, NULL);
2383 if (!device)
2384 return ERR_PTR(-ENOENT);
2385 } else {
2386 if (!devpath || !devpath[0])
2387 return ERR_PTR(-EINVAL);
2388 device = btrfs_find_device_missing_or_by_path(fs_info, devpath);
2389 }
2390 return device;
2391 }
2392
2393 /*
2394 * does all the dirty work required for changing file system's UUID.
2395 */
2396 static int btrfs_prepare_sprout(struct btrfs_fs_info *fs_info)
2397 {
2398 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2399 struct btrfs_fs_devices *old_devices;
2400 struct btrfs_fs_devices *seed_devices;
2401 struct btrfs_super_block *disk_super = fs_info->super_copy;
2402 struct btrfs_device *device;
2403 u64 super_flags;
2404
2405 lockdep_assert_held(&uuid_mutex);
2406 if (!fs_devices->seeding)
2407 return -EINVAL;
2408
2409 seed_devices = alloc_fs_devices(NULL, NULL);
2410 if (IS_ERR(seed_devices))
2411 return PTR_ERR(seed_devices);
2412
2413 old_devices = clone_fs_devices(fs_devices);
2414 if (IS_ERR(old_devices)) {
2415 kfree(seed_devices);
2416 return PTR_ERR(old_devices);
2417 }
2418
2419 list_add(&old_devices->fs_list, &fs_uuids);
2420
2421 memcpy(seed_devices, fs_devices, sizeof(*seed_devices));
2422 seed_devices->opened = 1;
2423 INIT_LIST_HEAD(&seed_devices->devices);
2424 INIT_LIST_HEAD(&seed_devices->alloc_list);
2425 mutex_init(&seed_devices->device_list_mutex);
2426
2427 mutex_lock(&fs_devices->device_list_mutex);
2428 list_splice_init_rcu(&fs_devices->devices, &seed_devices->devices,
2429 synchronize_rcu);
2430 list_for_each_entry(device, &seed_devices->devices, dev_list)
2431 device->fs_devices = seed_devices;
2432
2433 mutex_lock(&fs_info->chunk_mutex);
2434 list_splice_init(&fs_devices->alloc_list, &seed_devices->alloc_list);
2435 mutex_unlock(&fs_info->chunk_mutex);
2436
2437 fs_devices->seeding = 0;
2438 fs_devices->num_devices = 0;
2439 fs_devices->open_devices = 0;
2440 fs_devices->missing_devices = 0;
2441 fs_devices->rotating = 0;
2442 fs_devices->seed = seed_devices;
2443
2444 generate_random_uuid(fs_devices->fsid);
2445 memcpy(fs_devices->metadata_uuid, fs_devices->fsid, BTRFS_FSID_SIZE);
2446 memcpy(disk_super->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
2447 mutex_unlock(&fs_devices->device_list_mutex);
2448
2449 super_flags = btrfs_super_flags(disk_super) &
2450 ~BTRFS_SUPER_FLAG_SEEDING;
2451 btrfs_set_super_flags(disk_super, super_flags);
2452
2453 return 0;
2454 }
2455
2456 /*
2457 * Store the expected generation for seed devices in device items.
2458 */
2459 static int btrfs_finish_sprout(struct btrfs_trans_handle *trans,
2460 struct btrfs_fs_info *fs_info)
2461 {
2462 struct btrfs_root *root = fs_info->chunk_root;
2463 struct btrfs_path *path;
2464 struct extent_buffer *leaf;
2465 struct btrfs_dev_item *dev_item;
2466 struct btrfs_device *device;
2467 struct btrfs_key key;
2468 u8 fs_uuid[BTRFS_FSID_SIZE];
2469 u8 dev_uuid[BTRFS_UUID_SIZE];
2470 u64 devid;
2471 int ret;
2472
2473 path = btrfs_alloc_path();
2474 if (!path)
2475 return -ENOMEM;
2476
2477 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2478 key.offset = 0;
2479 key.type = BTRFS_DEV_ITEM_KEY;
2480
2481 while (1) {
2482 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2483 if (ret < 0)
2484 goto error;
2485
2486 leaf = path->nodes[0];
2487 next_slot:
2488 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
2489 ret = btrfs_next_leaf(root, path);
2490 if (ret > 0)
2491 break;
2492 if (ret < 0)
2493 goto error;
2494 leaf = path->nodes[0];
2495 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2496 btrfs_release_path(path);
2497 continue;
2498 }
2499
2500 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2501 if (key.objectid != BTRFS_DEV_ITEMS_OBJECTID ||
2502 key.type != BTRFS_DEV_ITEM_KEY)
2503 break;
2504
2505 dev_item = btrfs_item_ptr(leaf, path->slots[0],
2506 struct btrfs_dev_item);
2507 devid = btrfs_device_id(leaf, dev_item);
2508 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
2509 BTRFS_UUID_SIZE);
2510 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
2511 BTRFS_FSID_SIZE);
2512 device = btrfs_find_device(fs_info, devid, dev_uuid, fs_uuid);
2513 BUG_ON(!device); /* Logic error */
2514
2515 if (device->fs_devices->seeding) {
2516 btrfs_set_device_generation(leaf, dev_item,
2517 device->generation);
2518 btrfs_mark_buffer_dirty(leaf);
2519 }
2520
2521 path->slots[0]++;
2522 goto next_slot;
2523 }
2524 ret = 0;
2525 error:
2526 btrfs_free_path(path);
2527 return ret;
2528 }
2529
2530 int btrfs_init_new_device(struct btrfs_fs_info *fs_info, const char *device_path)
2531 {
2532 struct btrfs_root *root = fs_info->dev_root;
2533 struct request_queue *q;
2534 struct btrfs_trans_handle *trans;
2535 struct btrfs_device *device;
2536 struct block_device *bdev;
2537 struct super_block *sb = fs_info->sb;
2538 struct rcu_string *name;
2539 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2540 u64 orig_super_total_bytes;
2541 u64 orig_super_num_devices;
2542 int seeding_dev = 0;
2543 int ret = 0;
2544 bool unlocked = false;
2545
2546 if (sb_rdonly(sb) && !fs_devices->seeding)
2547 return -EROFS;
2548
2549 bdev = blkdev_get_by_path(device_path, FMODE_WRITE | FMODE_EXCL,
2550 fs_info->bdev_holder);
2551 if (IS_ERR(bdev))
2552 return PTR_ERR(bdev);
2553
2554 if (fs_devices->seeding) {
2555 seeding_dev = 1;
2556 down_write(&sb->s_umount);
2557 mutex_lock(&uuid_mutex);
2558 }
2559
2560 filemap_write_and_wait(bdev->bd_inode->i_mapping);
2561
2562 mutex_lock(&fs_devices->device_list_mutex);
2563 list_for_each_entry(device, &fs_devices->devices, dev_list) {
2564 if (device->bdev == bdev) {
2565 ret = -EEXIST;
2566 mutex_unlock(
2567 &fs_devices->device_list_mutex);
2568 goto error;
2569 }
2570 }
2571 mutex_unlock(&fs_devices->device_list_mutex);
2572
2573 device = btrfs_alloc_device(fs_info, NULL, NULL);
2574 if (IS_ERR(device)) {
2575 /* we can safely leave the fs_devices entry around */
2576 ret = PTR_ERR(device);
2577 goto error;
2578 }
2579
2580 name = rcu_string_strdup(device_path, GFP_KERNEL);
2581 if (!name) {
2582 ret = -ENOMEM;
2583 goto error_free_device;
2584 }
2585 rcu_assign_pointer(device->name, name);
2586
2587 trans = btrfs_start_transaction(root, 0);
2588 if (IS_ERR(trans)) {
2589 ret = PTR_ERR(trans);
2590 goto error_free_device;
2591 }
2592
2593 q = bdev_get_queue(bdev);
2594 set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
2595 device->generation = trans->transid;
2596 device->io_width = fs_info->sectorsize;
2597 device->io_align = fs_info->sectorsize;
2598 device->sector_size = fs_info->sectorsize;
2599 device->total_bytes = round_down(i_size_read(bdev->bd_inode),
2600 fs_info->sectorsize);
2601 device->disk_total_bytes = device->total_bytes;
2602 device->commit_total_bytes = device->total_bytes;
2603 device->fs_info = fs_info;
2604 device->bdev = bdev;
2605 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
2606 clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
2607 device->mode = FMODE_EXCL;
2608 device->dev_stats_valid = 1;
2609 set_blocksize(device->bdev, BTRFS_BDEV_BLOCKSIZE);
2610
2611 if (seeding_dev) {
2612 sb->s_flags &= ~SB_RDONLY;
2613 ret = btrfs_prepare_sprout(fs_info);
2614 if (ret) {
2615 btrfs_abort_transaction(trans, ret);
2616 goto error_trans;
2617 }
2618 }
2619
2620 device->fs_devices = fs_devices;
2621
2622 mutex_lock(&fs_devices->device_list_mutex);
2623 mutex_lock(&fs_info->chunk_mutex);
2624 list_add_rcu(&device->dev_list, &fs_devices->devices);
2625 list_add(&device->dev_alloc_list, &fs_devices->alloc_list);
2626 fs_devices->num_devices++;
2627 fs_devices->open_devices++;
2628 fs_devices->rw_devices++;
2629 fs_devices->total_devices++;
2630 fs_devices->total_rw_bytes += device->total_bytes;
2631
2632 atomic64_add(device->total_bytes, &fs_info->free_chunk_space);
2633
2634 if (!blk_queue_nonrot(q))
2635 fs_devices->rotating = 1;
2636
2637 orig_super_total_bytes = btrfs_super_total_bytes(fs_info->super_copy);
2638 btrfs_set_super_total_bytes(fs_info->super_copy,
2639 round_down(orig_super_total_bytes + device->total_bytes,
2640 fs_info->sectorsize));
2641
2642 orig_super_num_devices = btrfs_super_num_devices(fs_info->super_copy);
2643 btrfs_set_super_num_devices(fs_info->super_copy,
2644 orig_super_num_devices + 1);
2645
2646 /* add sysfs device entry */
2647 btrfs_sysfs_add_device_link(fs_devices, device);
2648
2649 /*
2650 * we've got more storage, clear any full flags on the space
2651 * infos
2652 */
2653 btrfs_clear_space_info_full(fs_info);
2654
2655 mutex_unlock(&fs_info->chunk_mutex);
2656 mutex_unlock(&fs_devices->device_list_mutex);
2657
2658 if (seeding_dev) {
2659 mutex_lock(&fs_info->chunk_mutex);
2660 ret = init_first_rw_device(trans, fs_info);
2661 mutex_unlock(&fs_info->chunk_mutex);
2662 if (ret) {
2663 btrfs_abort_transaction(trans, ret);
2664 goto error_sysfs;
2665 }
2666 }
2667
2668 ret = btrfs_add_dev_item(trans, device);
2669 if (ret) {
2670 btrfs_abort_transaction(trans, ret);
2671 goto error_sysfs;
2672 }
2673
2674 if (seeding_dev) {
2675 char fsid_buf[BTRFS_UUID_UNPARSED_SIZE];
2676
2677 ret = btrfs_finish_sprout(trans, fs_info);
2678 if (ret) {
2679 btrfs_abort_transaction(trans, ret);
2680 goto error_sysfs;
2681 }
2682
2683 /* Sprouting would change fsid of the mounted root,
2684 * so rename the fsid on the sysfs
2685 */
2686 snprintf(fsid_buf, BTRFS_UUID_UNPARSED_SIZE, "%pU",
2687 fs_info->fs_devices->fsid);
2688 if (kobject_rename(&fs_devices->fsid_kobj, fsid_buf))
2689 btrfs_warn(fs_info,
2690 "sysfs: failed to create fsid for sprout");
2691 }
2692
2693 ret = btrfs_commit_transaction(trans);
2694
2695 if (seeding_dev) {
2696 mutex_unlock(&uuid_mutex);
2697 up_write(&sb->s_umount);
2698 unlocked = true;
2699
2700 if (ret) /* transaction commit */
2701 return ret;
2702
2703 ret = btrfs_relocate_sys_chunks(fs_info);
2704 if (ret < 0)
2705 btrfs_handle_fs_error(fs_info, ret,
2706 "Failed to relocate sys chunks after device initialization. This can be fixed using the \"btrfs balance\" command.");
2707 trans = btrfs_attach_transaction(root);
2708 if (IS_ERR(trans)) {
2709 if (PTR_ERR(trans) == -ENOENT)
2710 return 0;
2711 ret = PTR_ERR(trans);
2712 trans = NULL;
2713 goto error_sysfs;
2714 }
2715 ret = btrfs_commit_transaction(trans);
2716 }
2717
2718 /* Update ctime/mtime for libblkid */
2719 update_dev_time(device_path);
2720 return ret;
2721
2722 error_sysfs:
2723 btrfs_sysfs_rm_device_link(fs_devices, device);
2724 mutex_lock(&fs_info->fs_devices->device_list_mutex);
2725 mutex_lock(&fs_info->chunk_mutex);
2726 list_del_rcu(&device->dev_list);
2727 list_del(&device->dev_alloc_list);
2728 fs_info->fs_devices->num_devices--;
2729 fs_info->fs_devices->open_devices--;
2730 fs_info->fs_devices->rw_devices--;
2731 fs_info->fs_devices->total_devices--;
2732 fs_info->fs_devices->total_rw_bytes -= device->total_bytes;
2733 atomic64_sub(device->total_bytes, &fs_info->free_chunk_space);
2734 btrfs_set_super_total_bytes(fs_info->super_copy,
2735 orig_super_total_bytes);
2736 btrfs_set_super_num_devices(fs_info->super_copy,
2737 orig_super_num_devices);
2738 mutex_unlock(&fs_info->chunk_mutex);
2739 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2740 error_trans:
2741 if (seeding_dev)
2742 sb->s_flags |= SB_RDONLY;
2743 if (trans)
2744 btrfs_end_transaction(trans);
2745 error_free_device:
2746 btrfs_free_device(device);
2747 error:
2748 blkdev_put(bdev, FMODE_EXCL);
2749 if (seeding_dev && !unlocked) {
2750 mutex_unlock(&uuid_mutex);
2751 up_write(&sb->s_umount);
2752 }
2753 return ret;
2754 }
2755
2756 static noinline int btrfs_update_device(struct btrfs_trans_handle *trans,
2757 struct btrfs_device *device)
2758 {
2759 int ret;
2760 struct btrfs_path *path;
2761 struct btrfs_root *root = device->fs_info->chunk_root;
2762 struct btrfs_dev_item *dev_item;
2763 struct extent_buffer *leaf;
2764 struct btrfs_key key;
2765
2766 path = btrfs_alloc_path();
2767 if (!path)
2768 return -ENOMEM;
2769
2770 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2771 key.type = BTRFS_DEV_ITEM_KEY;
2772 key.offset = device->devid;
2773
2774 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2775 if (ret < 0)
2776 goto out;
2777
2778 if (ret > 0) {
2779 ret = -ENOENT;
2780 goto out;
2781 }
2782
2783 leaf = path->nodes[0];
2784 dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
2785
2786 btrfs_set_device_id(leaf, dev_item, device->devid);
2787 btrfs_set_device_type(leaf, dev_item, device->type);
2788 btrfs_set_device_io_align(leaf, dev_item, device->io_align);
2789 btrfs_set_device_io_width(leaf, dev_item, device->io_width);
2790 btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
2791 btrfs_set_device_total_bytes(leaf, dev_item,
2792 btrfs_device_get_disk_total_bytes(device));
2793 btrfs_set_device_bytes_used(leaf, dev_item,
2794 btrfs_device_get_bytes_used(device));
2795 btrfs_mark_buffer_dirty(leaf);
2796
2797 out:
2798 btrfs_free_path(path);
2799 return ret;
2800 }
2801
2802 int btrfs_grow_device(struct btrfs_trans_handle *trans,
2803 struct btrfs_device *device, u64 new_size)
2804 {
2805 struct btrfs_fs_info *fs_info = device->fs_info;
2806 struct btrfs_super_block *super_copy = fs_info->super_copy;
2807 struct btrfs_fs_devices *fs_devices;
2808 u64 old_total;
2809 u64 diff;
2810
2811 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
2812 return -EACCES;
2813
2814 new_size = round_down(new_size, fs_info->sectorsize);
2815
2816 mutex_lock(&fs_info->chunk_mutex);
2817 old_total = btrfs_super_total_bytes(super_copy);
2818 diff = round_down(new_size - device->total_bytes, fs_info->sectorsize);
2819
2820 if (new_size <= device->total_bytes ||
2821 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
2822 mutex_unlock(&fs_info->chunk_mutex);
2823 return -EINVAL;
2824 }
2825
2826 fs_devices = fs_info->fs_devices;
2827
2828 btrfs_set_super_total_bytes(super_copy,
2829 round_down(old_total + diff, fs_info->sectorsize));
2830 device->fs_devices->total_rw_bytes += diff;
2831
2832 btrfs_device_set_total_bytes(device, new_size);
2833 btrfs_device_set_disk_total_bytes(device, new_size);
2834 btrfs_clear_space_info_full(device->fs_info);
2835 if (list_empty(&device->resized_list))
2836 list_add_tail(&device->resized_list,
2837 &fs_devices->resized_devices);
2838 mutex_unlock(&fs_info->chunk_mutex);
2839
2840 return btrfs_update_device(trans, device);
2841 }
2842
2843 static int btrfs_free_chunk(struct btrfs_trans_handle *trans, u64 chunk_offset)
2844 {
2845 struct btrfs_fs_info *fs_info = trans->fs_info;
2846 struct btrfs_root *root = fs_info->chunk_root;
2847 int ret;
2848 struct btrfs_path *path;
2849 struct btrfs_key key;
2850
2851 path = btrfs_alloc_path();
2852 if (!path)
2853 return -ENOMEM;
2854
2855 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2856 key.offset = chunk_offset;
2857 key.type = BTRFS_CHUNK_ITEM_KEY;
2858
2859 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
2860 if (ret < 0)
2861 goto out;
2862 else if (ret > 0) { /* Logic error or corruption */
2863 btrfs_handle_fs_error(fs_info, -ENOENT,
2864 "Failed lookup while freeing chunk.");
2865 ret = -ENOENT;
2866 goto out;
2867 }
2868
2869 ret = btrfs_del_item(trans, root, path);
2870 if (ret < 0)
2871 btrfs_handle_fs_error(fs_info, ret,
2872 "Failed to delete chunk item.");
2873 out:
2874 btrfs_free_path(path);
2875 return ret;
2876 }
2877
2878 static int btrfs_del_sys_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
2879 {
2880 struct btrfs_super_block *super_copy = fs_info->super_copy;
2881 struct btrfs_disk_key *disk_key;
2882 struct btrfs_chunk *chunk;
2883 u8 *ptr;
2884 int ret = 0;
2885 u32 num_stripes;
2886 u32 array_size;
2887 u32 len = 0;
2888 u32 cur;
2889 struct btrfs_key key;
2890
2891 mutex_lock(&fs_info->chunk_mutex);
2892 array_size = btrfs_super_sys_array_size(super_copy);
2893
2894 ptr = super_copy->sys_chunk_array;
2895 cur = 0;
2896
2897 while (cur < array_size) {
2898 disk_key = (struct btrfs_disk_key *)ptr;
2899 btrfs_disk_key_to_cpu(&key, disk_key);
2900
2901 len = sizeof(*disk_key);
2902
2903 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
2904 chunk = (struct btrfs_chunk *)(ptr + len);
2905 num_stripes = btrfs_stack_chunk_num_stripes(chunk);
2906 len += btrfs_chunk_item_size(num_stripes);
2907 } else {
2908 ret = -EIO;
2909 break;
2910 }
2911 if (key.objectid == BTRFS_FIRST_CHUNK_TREE_OBJECTID &&
2912 key.offset == chunk_offset) {
2913 memmove(ptr, ptr + len, array_size - (cur + len));
2914 array_size -= len;
2915 btrfs_set_super_sys_array_size(super_copy, array_size);
2916 } else {
2917 ptr += len;
2918 cur += len;
2919 }
2920 }
2921 mutex_unlock(&fs_info->chunk_mutex);
2922 return ret;
2923 }
2924
2925 /*
2926 * btrfs_get_chunk_map() - Find the mapping containing the given logical extent.
2927 * @logical: Logical block offset in bytes.
2928 * @length: Length of extent in bytes.
2929 *
2930 * Return: Chunk mapping or ERR_PTR.
2931 */
2932 struct extent_map *btrfs_get_chunk_map(struct btrfs_fs_info *fs_info,
2933 u64 logical, u64 length)
2934 {
2935 struct extent_map_tree *em_tree;
2936 struct extent_map *em;
2937
2938 em_tree = &fs_info->mapping_tree.map_tree;
2939 read_lock(&em_tree->lock);
2940 em = lookup_extent_mapping(em_tree, logical, length);
2941 read_unlock(&em_tree->lock);
2942
2943 if (!em) {
2944 btrfs_crit(fs_info, "unable to find logical %llu length %llu",
2945 logical, length);
2946 return ERR_PTR(-EINVAL);
2947 }
2948
2949 if (em->start > logical || em->start + em->len < logical) {
2950 btrfs_crit(fs_info,
2951 "found a bad mapping, wanted %llu-%llu, found %llu-%llu",
2952 logical, length, em->start, em->start + em->len);
2953 free_extent_map(em);
2954 return ERR_PTR(-EINVAL);
2955 }
2956
2957 /* callers are responsible for dropping em's ref. */
2958 return em;
2959 }
2960
2961 int btrfs_remove_chunk(struct btrfs_trans_handle *trans, u64 chunk_offset)
2962 {
2963 struct btrfs_fs_info *fs_info = trans->fs_info;
2964 struct extent_map *em;
2965 struct map_lookup *map;
2966 u64 dev_extent_len = 0;
2967 int i, ret = 0;
2968 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2969
2970 em = btrfs_get_chunk_map(fs_info, chunk_offset, 1);
2971 if (IS_ERR(em)) {
2972 /*
2973 * This is a logic error, but we don't want to just rely on the
2974 * user having built with ASSERT enabled, so if ASSERT doesn't
2975 * do anything we still error out.
2976 */
2977 ASSERT(0);
2978 return PTR_ERR(em);
2979 }
2980 map = em->map_lookup;
2981 mutex_lock(&fs_info->chunk_mutex);
2982 check_system_chunk(trans, map->type);
2983 mutex_unlock(&fs_info->chunk_mutex);
2984
2985 /*
2986 * Take the device list mutex to prevent races with the final phase of
2987 * a device replace operation that replaces the device object associated
2988 * with map stripes (dev-replace.c:btrfs_dev_replace_finishing()).
2989 */
2990 mutex_lock(&fs_devices->device_list_mutex);
2991 for (i = 0; i < map->num_stripes; i++) {
2992 struct btrfs_device *device = map->stripes[i].dev;
2993 ret = btrfs_free_dev_extent(trans, device,
2994 map->stripes[i].physical,
2995 &dev_extent_len);
2996 if (ret) {
2997 mutex_unlock(&fs_devices->device_list_mutex);
2998 btrfs_abort_transaction(trans, ret);
2999 goto out;
3000 }
3001
3002 if (device->bytes_used > 0) {
3003 mutex_lock(&fs_info->chunk_mutex);
3004 btrfs_device_set_bytes_used(device,
3005 device->bytes_used - dev_extent_len);
3006 atomic64_add(dev_extent_len, &fs_info->free_chunk_space);
3007 btrfs_clear_space_info_full(fs_info);
3008 mutex_unlock(&fs_info->chunk_mutex);
3009 }
3010
3011 ret = btrfs_update_device(trans, device);
3012 if (ret) {
3013 mutex_unlock(&fs_devices->device_list_mutex);
3014 btrfs_abort_transaction(trans, ret);
3015 goto out;
3016 }
3017 }
3018 mutex_unlock(&fs_devices->device_list_mutex);
3019
3020 ret = btrfs_free_chunk(trans, chunk_offset);
3021 if (ret) {
3022 btrfs_abort_transaction(trans, ret);
3023 goto out;
3024 }
3025
3026 trace_btrfs_chunk_free(fs_info, map, chunk_offset, em->len);
3027
3028 if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
3029 ret = btrfs_del_sys_chunk(fs_info, chunk_offset);
3030 if (ret) {
3031 btrfs_abort_transaction(trans, ret);
3032 goto out;
3033 }
3034 }
3035
3036 ret = btrfs_remove_block_group(trans, chunk_offset, em);
3037 if (ret) {
3038 btrfs_abort_transaction(trans, ret);
3039 goto out;
3040 }
3041
3042 out:
3043 /* once for us */
3044 free_extent_map(em);
3045 return ret;
3046 }
3047
3048 static int btrfs_relocate_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
3049 {
3050 struct btrfs_root *root = fs_info->chunk_root;
3051 struct btrfs_trans_handle *trans;
3052 int ret;
3053
3054 /*
3055 * Prevent races with automatic removal of unused block groups.
3056 * After we relocate and before we remove the chunk with offset
3057 * chunk_offset, automatic removal of the block group can kick in,
3058 * resulting in a failure when calling btrfs_remove_chunk() below.
3059 *
3060 * Make sure to acquire this mutex before doing a tree search (dev
3061 * or chunk trees) to find chunks. Otherwise the cleaner kthread might
3062 * call btrfs_remove_chunk() (through btrfs_delete_unused_bgs()) after
3063 * we release the path used to search the chunk/dev tree and before
3064 * the current task acquires this mutex and calls us.
3065 */
3066 lockdep_assert_held(&fs_info->delete_unused_bgs_mutex);
3067
3068 ret = btrfs_can_relocate(fs_info, chunk_offset);
3069 if (ret)
3070 return -ENOSPC;
3071
3072 /* step one, relocate all the extents inside this chunk */
3073 btrfs_scrub_pause(fs_info);
3074 ret = btrfs_relocate_block_group(fs_info, chunk_offset);
3075 btrfs_scrub_continue(fs_info);
3076 if (ret)
3077 return ret;
3078
3079 /*
3080 * We add the kobjects here (and after forcing data chunk creation)
3081 * since relocation is the only place we'll create chunks of a new
3082 * type at runtime. The only place where we'll remove the last
3083 * chunk of a type is the call immediately below this one. Even
3084 * so, we're protected against races with the cleaner thread since
3085 * we're covered by the delete_unused_bgs_mutex.
3086 */
3087 btrfs_add_raid_kobjects(fs_info);
3088
3089 trans = btrfs_start_trans_remove_block_group(root->fs_info,
3090 chunk_offset);
3091 if (IS_ERR(trans)) {
3092 ret = PTR_ERR(trans);
3093 btrfs_handle_fs_error(root->fs_info, ret, NULL);
3094 return ret;
3095 }
3096
3097 /*
3098 * step two, delete the device extents and the
3099 * chunk tree entries
3100 */
3101 ret = btrfs_remove_chunk(trans, chunk_offset);
3102 btrfs_end_transaction(trans);
3103 return ret;
3104 }
3105
3106 static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info)
3107 {
3108 struct btrfs_root *chunk_root = fs_info->chunk_root;
3109 struct btrfs_path *path;
3110 struct extent_buffer *leaf;
3111 struct btrfs_chunk *chunk;
3112 struct btrfs_key key;
3113 struct btrfs_key found_key;
3114 u64 chunk_type;
3115 bool retried = false;
3116 int failed = 0;
3117 int ret;
3118
3119 path = btrfs_alloc_path();
3120 if (!path)
3121 return -ENOMEM;
3122
3123 again:
3124 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
3125 key.offset = (u64)-1;
3126 key.type = BTRFS_CHUNK_ITEM_KEY;
3127
3128 while (1) {
3129 mutex_lock(&fs_info->delete_unused_bgs_mutex);
3130 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
3131 if (ret < 0) {
3132 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3133 goto error;
3134 }
3135 BUG_ON(ret == 0); /* Corruption */
3136
3137 ret = btrfs_previous_item(chunk_root, path, key.objectid,
3138 key.type);
3139 if (ret)
3140 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3141 if (ret < 0)
3142 goto error;
3143 if (ret > 0)
3144 break;
3145
3146 leaf = path->nodes[0];
3147 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3148
3149 chunk = btrfs_item_ptr(leaf, path->slots[0],
3150 struct btrfs_chunk);
3151 chunk_type = btrfs_chunk_type(leaf, chunk);
3152 btrfs_release_path(path);
3153
3154 if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) {
3155 ret = btrfs_relocate_chunk(fs_info, found_key.offset);
3156 if (ret == -ENOSPC)
3157 failed++;
3158 else
3159 BUG_ON(ret);
3160 }
3161 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3162
3163 if (found_key.offset == 0)
3164 break;
3165 key.offset = found_key.offset - 1;
3166 }
3167 ret = 0;
3168 if (failed && !retried) {
3169 failed = 0;
3170 retried = true;
3171 goto again;
3172 } else if (WARN_ON(failed && retried)) {
3173 ret = -ENOSPC;
3174 }
3175 error:
3176 btrfs_free_path(path);
3177 return ret;
3178 }
3179
3180 /*
3181 * return 1 : allocate a data chunk successfully,
3182 * return <0: errors during allocating a data chunk,
3183 * return 0 : no need to allocate a data chunk.
3184 */
3185 static int btrfs_may_alloc_data_chunk(struct btrfs_fs_info *fs_info,
3186 u64 chunk_offset)
3187 {
3188 struct btrfs_block_group_cache *cache;
3189 u64 bytes_used;
3190 u64 chunk_type;
3191
3192 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3193 ASSERT(cache);
3194 chunk_type = cache->flags;
3195 btrfs_put_block_group(cache);
3196
3197 if (chunk_type & BTRFS_BLOCK_GROUP_DATA) {
3198 spin_lock(&fs_info->data_sinfo->lock);
3199 bytes_used = fs_info->data_sinfo->bytes_used;
3200 spin_unlock(&fs_info->data_sinfo->lock);
3201
3202 if (!bytes_used) {
3203 struct btrfs_trans_handle *trans;
3204 int ret;
3205
3206 trans = btrfs_join_transaction(fs_info->tree_root);
3207 if (IS_ERR(trans))
3208 return PTR_ERR(trans);
3209
3210 ret = btrfs_force_chunk_alloc(trans,
3211 BTRFS_BLOCK_GROUP_DATA);
3212 btrfs_end_transaction(trans);
3213 if (ret < 0)
3214 return ret;
3215
3216 btrfs_add_raid_kobjects(fs_info);
3217
3218 return 1;
3219 }
3220 }
3221 return 0;
3222 }
3223
3224 static int insert_balance_item(struct btrfs_fs_info *fs_info,
3225 struct btrfs_balance_control *bctl)
3226 {
3227 struct btrfs_root *root = fs_info->tree_root;
3228 struct btrfs_trans_handle *trans;
3229 struct btrfs_balance_item *item;
3230 struct btrfs_disk_balance_args disk_bargs;
3231 struct btrfs_path *path;
3232 struct extent_buffer *leaf;
3233 struct btrfs_key key;
3234 int ret, err;
3235
3236 path = btrfs_alloc_path();
3237 if (!path)
3238 return -ENOMEM;
3239
3240 trans = btrfs_start_transaction(root, 0);
3241 if (IS_ERR(trans)) {
3242 btrfs_free_path(path);
3243 return PTR_ERR(trans);
3244 }
3245
3246 key.objectid = BTRFS_BALANCE_OBJECTID;
3247 key.type = BTRFS_TEMPORARY_ITEM_KEY;
3248 key.offset = 0;
3249
3250 ret = btrfs_insert_empty_item(trans, root, path, &key,
3251 sizeof(*item));
3252 if (ret)
3253 goto out;
3254
3255 leaf = path->nodes[0];
3256 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
3257
3258 memzero_extent_buffer(leaf, (unsigned long)item, sizeof(*item));
3259
3260 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->data);
3261 btrfs_set_balance_data(leaf, item, &disk_bargs);
3262 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->meta);
3263 btrfs_set_balance_meta(leaf, item, &disk_bargs);
3264 btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->sys);
3265 btrfs_set_balance_sys(leaf, item, &disk_bargs);
3266
3267 btrfs_set_balance_flags(leaf, item, bctl->flags);
3268
3269 btrfs_mark_buffer_dirty(leaf);
3270 out:
3271 btrfs_free_path(path);
3272 err = btrfs_commit_transaction(trans);
3273 if (err && !ret)
3274 ret = err;
3275 return ret;
3276 }
3277
3278 static int del_balance_item(struct btrfs_fs_info *fs_info)
3279 {
3280 struct btrfs_root *root = fs_info->tree_root;
3281 struct btrfs_trans_handle *trans;
3282 struct btrfs_path *path;
3283 struct btrfs_key key;
3284 int ret, err;
3285
3286 path = btrfs_alloc_path();
3287 if (!path)
3288 return -ENOMEM;
3289
3290 trans = btrfs_start_transaction(root, 0);
3291 if (IS_ERR(trans)) {
3292 btrfs_free_path(path);
3293 return PTR_ERR(trans);
3294 }
3295
3296 key.objectid = BTRFS_BALANCE_OBJECTID;
3297 key.type = BTRFS_TEMPORARY_ITEM_KEY;
3298 key.offset = 0;
3299
3300 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3301 if (ret < 0)
3302 goto out;
3303 if (ret > 0) {
3304 ret = -ENOENT;
3305 goto out;
3306 }
3307
3308 ret = btrfs_del_item(trans, root, path);
3309 out:
3310 btrfs_free_path(path);
3311 err = btrfs_commit_transaction(trans);
3312 if (err && !ret)
3313 ret = err;
3314 return ret;
3315 }
3316
3317 /*
3318 * This is a heuristic used to reduce the number of chunks balanced on
3319 * resume after balance was interrupted.
3320 */
3321 static void update_balance_args(struct btrfs_balance_control *bctl)
3322 {
3323 /*
3324 * Turn on soft mode for chunk types that were being converted.
3325 */
3326 if (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)
3327 bctl->data.flags |= BTRFS_BALANCE_ARGS_SOFT;
3328 if (bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)
3329 bctl->sys.flags |= BTRFS_BALANCE_ARGS_SOFT;
3330 if (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)
3331 bctl->meta.flags |= BTRFS_BALANCE_ARGS_SOFT;
3332
3333 /*
3334 * Turn on usage filter if is not already used. The idea is
3335 * that chunks that we have already balanced should be
3336 * reasonably full. Don't do it for chunks that are being
3337 * converted - that will keep us from relocating unconverted
3338 * (albeit full) chunks.
3339 */
3340 if (!(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3341 !(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3342 !(bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3343 bctl->data.flags |= BTRFS_BALANCE_ARGS_USAGE;
3344 bctl->data.usage = 90;
3345 }
3346 if (!(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3347 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3348 !(bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3349 bctl->sys.flags |= BTRFS_BALANCE_ARGS_USAGE;
3350 bctl->sys.usage = 90;
3351 }
3352 if (!(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3353 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3354 !(bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3355 bctl->meta.flags |= BTRFS_BALANCE_ARGS_USAGE;
3356 bctl->meta.usage = 90;
3357 }
3358 }
3359
3360 /*
3361 * Clear the balance status in fs_info and delete the balance item from disk.
3362 */
3363 static void reset_balance_state(struct btrfs_fs_info *fs_info)
3364 {
3365 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3366 int ret;
3367
3368 BUG_ON(!fs_info->balance_ctl);
3369
3370 spin_lock(&fs_info->balance_lock);
3371 fs_info->balance_ctl = NULL;
3372 spin_unlock(&fs_info->balance_lock);
3373
3374 kfree(bctl);
3375 ret = del_balance_item(fs_info);
3376 if (ret)
3377 btrfs_handle_fs_error(fs_info, ret, NULL);
3378 }
3379
3380 /*
3381 * Balance filters. Return 1 if chunk should be filtered out
3382 * (should not be balanced).
3383 */
3384 static int chunk_profiles_filter(u64 chunk_type,
3385 struct btrfs_balance_args *bargs)
3386 {
3387 chunk_type = chunk_to_extended(chunk_type) &
3388 BTRFS_EXTENDED_PROFILE_MASK;
3389
3390 if (bargs->profiles & chunk_type)
3391 return 0;
3392
3393 return 1;
3394 }
3395
3396 static int chunk_usage_range_filter(struct btrfs_fs_info *fs_info, u64 chunk_offset,
3397 struct btrfs_balance_args *bargs)
3398 {
3399 struct btrfs_block_group_cache *cache;
3400 u64 chunk_used;
3401 u64 user_thresh_min;
3402 u64 user_thresh_max;
3403 int ret = 1;
3404
3405 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3406 chunk_used = btrfs_block_group_used(&cache->item);
3407
3408 if (bargs->usage_min == 0)
3409 user_thresh_min = 0;
3410 else
3411 user_thresh_min = div_factor_fine(cache->key.offset,
3412 bargs->usage_min);
3413
3414 if (bargs->usage_max == 0)
3415 user_thresh_max = 1;
3416 else if (bargs->usage_max > 100)
3417 user_thresh_max = cache->key.offset;
3418 else
3419 user_thresh_max = div_factor_fine(cache->key.offset,
3420 bargs->usage_max);
3421
3422 if (user_thresh_min <= chunk_used && chunk_used < user_thresh_max)
3423 ret = 0;
3424
3425 btrfs_put_block_group(cache);
3426 return ret;
3427 }
3428
3429 static int chunk_usage_filter(struct btrfs_fs_info *fs_info,
3430 u64 chunk_offset, struct btrfs_balance_args *bargs)
3431 {
3432 struct btrfs_block_group_cache *cache;
3433 u64 chunk_used, user_thresh;
3434 int ret = 1;
3435
3436 cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3437 chunk_used = btrfs_block_group_used(&cache->item);
3438
3439 if (bargs->usage_min == 0)
3440 user_thresh = 1;
3441 else if (bargs->usage > 100)
3442 user_thresh = cache->key.offset;
3443 else
3444 user_thresh = div_factor_fine(cache->key.offset,
3445 bargs->usage);
3446
3447 if (chunk_used < user_thresh)
3448 ret = 0;
3449
3450 btrfs_put_block_group(cache);
3451 return ret;
3452 }
3453
3454 static int chunk_devid_filter(struct extent_buffer *leaf,
3455 struct btrfs_chunk *chunk,
3456 struct btrfs_balance_args *bargs)
3457 {
3458 struct btrfs_stripe *stripe;
3459 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3460 int i;
3461
3462 for (i = 0; i < num_stripes; i++) {
3463 stripe = btrfs_stripe_nr(chunk, i);
3464 if (btrfs_stripe_devid(leaf, stripe) == bargs->devid)
3465 return 0;
3466 }
3467
3468 return 1;
3469 }
3470
3471 /* [pstart, pend) */
3472 static int chunk_drange_filter(struct extent_buffer *leaf,
3473 struct btrfs_chunk *chunk,
3474 struct btrfs_balance_args *bargs)
3475 {
3476 struct btrfs_stripe *stripe;
3477 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3478 u64 stripe_offset;
3479 u64 stripe_length;
3480 int factor;
3481 int i;
3482
3483 if (!(bargs->flags & BTRFS_BALANCE_ARGS_DEVID))
3484 return 0;
3485
3486 if (btrfs_chunk_type(leaf, chunk) & (BTRFS_BLOCK_GROUP_DUP |
3487 BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10)) {
3488 factor = num_stripes / 2;
3489 } else if (btrfs_chunk_type(leaf, chunk) & BTRFS_BLOCK_GROUP_RAID5) {
3490 factor = num_stripes - 1;
3491 } else if (btrfs_chunk_type(leaf, chunk) & BTRFS_BLOCK_GROUP_RAID6) {
3492 factor = num_stripes - 2;
3493 } else {
3494 factor = num_stripes;
3495 }
3496
3497 for (i = 0; i < num_stripes; i++) {
3498 stripe = btrfs_stripe_nr(chunk, i);
3499 if (btrfs_stripe_devid(leaf, stripe) != bargs->devid)
3500 continue;
3501
3502 stripe_offset = btrfs_stripe_offset(leaf, stripe);
3503 stripe_length = btrfs_chunk_length(leaf, chunk);
3504 stripe_length = div_u64(stripe_length, factor);
3505
3506 if (stripe_offset < bargs->pend &&
3507 stripe_offset + stripe_length > bargs->pstart)
3508 return 0;
3509 }
3510
3511 return 1;
3512 }
3513
3514 /* [vstart, vend) */
3515 static int chunk_vrange_filter(struct extent_buffer *leaf,
3516 struct btrfs_chunk *chunk,
3517 u64 chunk_offset,
3518 struct btrfs_balance_args *bargs)
3519 {
3520 if (chunk_offset < bargs->vend &&
3521 chunk_offset + btrfs_chunk_length(leaf, chunk) > bargs->vstart)
3522 /* at least part of the chunk is inside this vrange */
3523 return 0;
3524
3525 return 1;
3526 }
3527
3528 static int chunk_stripes_range_filter(struct extent_buffer *leaf,
3529 struct btrfs_chunk *chunk,
3530 struct btrfs_balance_args *bargs)
3531 {
3532 int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3533
3534 if (bargs->stripes_min <= num_stripes
3535 && num_stripes <= bargs->stripes_max)
3536 return 0;
3537
3538 return 1;
3539 }
3540
3541 static int chunk_soft_convert_filter(u64 chunk_type,
3542 struct btrfs_balance_args *bargs)
3543 {
3544 if (!(bargs->flags & BTRFS_BALANCE_ARGS_CONVERT))
3545 return 0;
3546
3547 chunk_type = chunk_to_extended(chunk_type) &
3548 BTRFS_EXTENDED_PROFILE_MASK;
3549
3550 if (bargs->target == chunk_type)
3551 return 1;
3552
3553 return 0;
3554 }
3555
3556 static int should_balance_chunk(struct btrfs_fs_info *fs_info,
3557 struct extent_buffer *leaf,
3558 struct btrfs_chunk *chunk, u64 chunk_offset)
3559 {
3560 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3561 struct btrfs_balance_args *bargs = NULL;
3562 u64 chunk_type = btrfs_chunk_type(leaf, chunk);
3563
3564 /* type filter */
3565 if (!((chunk_type & BTRFS_BLOCK_GROUP_TYPE_MASK) &
3566 (bctl->flags & BTRFS_BALANCE_TYPE_MASK))) {
3567 return 0;
3568 }
3569
3570 if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
3571 bargs = &bctl->data;
3572 else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
3573 bargs = &bctl->sys;
3574 else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
3575 bargs = &bctl->meta;
3576
3577 /* profiles filter */
3578 if ((bargs->flags & BTRFS_BALANCE_ARGS_PROFILES) &&
3579 chunk_profiles_filter(chunk_type, bargs)) {
3580 return 0;
3581 }
3582
3583 /* usage filter */
3584 if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE) &&
3585 chunk_usage_filter(fs_info, chunk_offset, bargs)) {
3586 return 0;
3587 } else if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3588 chunk_usage_range_filter(fs_info, chunk_offset, bargs)) {
3589 return 0;
3590 }
3591
3592 /* devid filter */
3593 if ((bargs->flags & BTRFS_BALANCE_ARGS_DEVID) &&
3594 chunk_devid_filter(leaf, chunk, bargs)) {
3595 return 0;
3596 }
3597
3598 /* drange filter, makes sense only with devid filter */
3599 if ((bargs->flags & BTRFS_BALANCE_ARGS_DRANGE) &&
3600 chunk_drange_filter(leaf, chunk, bargs)) {
3601 return 0;
3602 }
3603
3604 /* vrange filter */
3605 if ((bargs->flags & BTRFS_BALANCE_ARGS_VRANGE) &&
3606 chunk_vrange_filter(leaf, chunk, chunk_offset, bargs)) {
3607 return 0;
3608 }
3609
3610 /* stripes filter */
3611 if ((bargs->flags & BTRFS_BALANCE_ARGS_STRIPES_RANGE) &&
3612 chunk_stripes_range_filter(leaf, chunk, bargs)) {
3613 return 0;
3614 }
3615
3616 /* soft profile changing mode */
3617 if ((bargs->flags & BTRFS_BALANCE_ARGS_SOFT) &&
3618 chunk_soft_convert_filter(chunk_type, bargs)) {
3619 return 0;
3620 }
3621
3622 /*
3623 * limited by count, must be the last filter
3624 */
3625 if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT)) {
3626 if (bargs->limit == 0)
3627 return 0;
3628 else
3629 bargs->limit--;
3630 } else if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT_RANGE)) {
3631 /*
3632 * Same logic as the 'limit' filter; the minimum cannot be
3633 * determined here because we do not have the global information
3634 * about the count of all chunks that satisfy the filters.
3635 */
3636 if (bargs->limit_max == 0)
3637 return 0;
3638 else
3639 bargs->limit_max--;
3640 }
3641
3642 return 1;
3643 }
3644
3645 static int __btrfs_balance(struct btrfs_fs_info *fs_info)
3646 {
3647 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3648 struct btrfs_root *chunk_root = fs_info->chunk_root;
3649 struct btrfs_root *dev_root = fs_info->dev_root;
3650 struct list_head *devices;
3651 struct btrfs_device *device;
3652 u64 old_size;
3653 u64 size_to_free;
3654 u64 chunk_type;
3655 struct btrfs_chunk *chunk;
3656 struct btrfs_path *path = NULL;
3657 struct btrfs_key key;
3658 struct btrfs_key found_key;
3659 struct btrfs_trans_handle *trans;
3660 struct extent_buffer *leaf;
3661 int slot;
3662 int ret;
3663 int enospc_errors = 0;
3664 bool counting = true;
3665 /* The single value limit and min/max limits use the same bytes in the */
3666 u64 limit_data = bctl->data.limit;
3667 u64 limit_meta = bctl->meta.limit;
3668 u64 limit_sys = bctl->sys.limit;
3669 u32 count_data = 0;
3670 u32 count_meta = 0;
3671 u32 count_sys = 0;
3672 int chunk_reserved = 0;
3673
3674 /* step one make some room on all the devices */
3675 devices = &fs_info->fs_devices->devices;
3676 list_for_each_entry(device, devices, dev_list) {
3677 old_size = btrfs_device_get_total_bytes(device);
3678 size_to_free = div_factor(old_size, 1);
3679 size_to_free = min_t(u64, size_to_free, SZ_1M);
3680 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) ||
3681 btrfs_device_get_total_bytes(device) -
3682 btrfs_device_get_bytes_used(device) > size_to_free ||
3683 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
3684 continue;
3685
3686 ret = btrfs_shrink_device(device, old_size - size_to_free);
3687 if (ret == -ENOSPC)
3688 break;
3689 if (ret) {
3690 /* btrfs_shrink_device never returns ret > 0 */
3691 WARN_ON(ret > 0);
3692 goto error;
3693 }
3694
3695 trans = btrfs_start_transaction(dev_root, 0);
3696 if (IS_ERR(trans)) {
3697 ret = PTR_ERR(trans);
3698 btrfs_info_in_rcu(fs_info,
3699 "resize: unable to start transaction after shrinking device %s (error %d), old size %llu, new size %llu",
3700 rcu_str_deref(device->name), ret,
3701 old_size, old_size - size_to_free);
3702 goto error;
3703 }
3704
3705 ret = btrfs_grow_device(trans, device, old_size);
3706 if (ret) {
3707 btrfs_end_transaction(trans);
3708 /* btrfs_grow_device never returns ret > 0 */
3709 WARN_ON(ret > 0);
3710 btrfs_info_in_rcu(fs_info,
3711 "resize: unable to grow device after shrinking device %s (error %d), old size %llu, new size %llu",
3712 rcu_str_deref(device->name), ret,
3713 old_size, old_size - size_to_free);
3714 goto error;
3715 }
3716
3717 btrfs_end_transaction(trans);
3718 }
3719
3720 /* step two, relocate all the chunks */
3721 path = btrfs_alloc_path();
3722 if (!path) {
3723 ret = -ENOMEM;
3724 goto error;
3725 }
3726
3727 /* zero out stat counters */
3728 spin_lock(&fs_info->balance_lock);
3729 memset(&bctl->stat, 0, sizeof(bctl->stat));
3730 spin_unlock(&fs_info->balance_lock);
3731 again:
3732 if (!counting) {
3733 /*
3734 * The single value limit and min/max limits use the same bytes
3735 * in the
3736 */
3737 bctl->data.limit = limit_data;
3738 bctl->meta.limit = limit_meta;
3739 bctl->sys.limit = limit_sys;
3740 }
3741 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
3742 key.offset = (u64)-1;
3743 key.type = BTRFS_CHUNK_ITEM_KEY;
3744
3745 while (1) {
3746 if ((!counting && atomic_read(&fs_info->balance_pause_req)) ||
3747 atomic_read(&fs_info->balance_cancel_req)) {
3748 ret = -ECANCELED;
3749 goto error;
3750 }
3751
3752 mutex_lock(&fs_info->delete_unused_bgs_mutex);
3753 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
3754 if (ret < 0) {
3755 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3756 goto error;
3757 }
3758
3759 /*
3760 * this shouldn't happen, it means the last relocate
3761 * failed
3762 */
3763 if (ret == 0)
3764 BUG(); /* FIXME break ? */
3765
3766 ret = btrfs_previous_item(chunk_root, path, 0,
3767 BTRFS_CHUNK_ITEM_KEY);
3768 if (ret) {
3769 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3770 ret = 0;
3771 break;
3772 }
3773
3774 leaf = path->nodes[0];
3775 slot = path->slots[0];
3776 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3777
3778 if (found_key.objectid != key.objectid) {
3779 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3780 break;
3781 }
3782
3783 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
3784 chunk_type = btrfs_chunk_type(leaf, chunk);
3785
3786 if (!counting) {
3787 spin_lock(&fs_info->balance_lock);
3788 bctl->stat.considered++;
3789 spin_unlock(&fs_info->balance_lock);
3790 }
3791
3792 ret = should_balance_chunk(fs_info, leaf, chunk,
3793 found_key.offset);
3794
3795 btrfs_release_path(path);
3796 if (!ret) {
3797 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3798 goto loop;
3799 }
3800
3801 if (counting) {
3802 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3803 spin_lock(&fs_info->balance_lock);
3804 bctl->stat.expected++;
3805 spin_unlock(&fs_info->balance_lock);
3806
3807 if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
3808 count_data++;
3809 else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
3810 count_sys++;
3811 else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
3812 count_meta++;
3813
3814 goto loop;
3815 }
3816
3817 /*
3818 * Apply limit_min filter, no need to check if the LIMITS
3819 * filter is used, limit_min is 0 by default
3820 */
3821 if (((chunk_type & BTRFS_BLOCK_GROUP_DATA) &&
3822 count_data < bctl->data.limit_min)
3823 || ((chunk_type & BTRFS_BLOCK_GROUP_METADATA) &&
3824 count_meta < bctl->meta.limit_min)
3825 || ((chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) &&
3826 count_sys < bctl->sys.limit_min)) {
3827 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3828 goto loop;
3829 }
3830
3831 if (!chunk_reserved) {
3832 /*
3833 * We may be relocating the only data chunk we have,
3834 * which could potentially end up with losing data's
3835 * raid profile, so lets allocate an empty one in
3836 * advance.
3837 */
3838 ret = btrfs_may_alloc_data_chunk(fs_info,
3839 found_key.offset);
3840 if (ret < 0) {
3841 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3842 goto error;
3843 } else if (ret == 1) {
3844 chunk_reserved = 1;
3845 }
3846 }
3847
3848 ret = btrfs_relocate_chunk(fs_info, found_key.offset);
3849 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3850 if (ret == -ENOSPC) {
3851 enospc_errors++;
3852 } else if (ret == -ETXTBSY) {
3853 btrfs_info(fs_info,
3854 "skipping relocation of block group %llu due to active swapfile",
3855 found_key.offset);
3856 ret = 0;
3857 } else if (ret) {
3858 goto error;
3859 } else {
3860 spin_lock(&fs_info->balance_lock);
3861 bctl->stat.completed++;
3862 spin_unlock(&fs_info->balance_lock);
3863 }
3864 loop:
3865 if (found_key.offset == 0)
3866 break;
3867 key.offset = found_key.offset - 1;
3868 }
3869
3870 if (counting) {
3871 btrfs_release_path(path);
3872 counting = false;
3873 goto again;
3874 }
3875 error:
3876 btrfs_free_path(path);
3877 if (enospc_errors) {
3878 btrfs_info(fs_info, "%d enospc errors during balance",
3879 enospc_errors);
3880 if (!ret)
3881 ret = -ENOSPC;
3882 }
3883
3884 return ret;
3885 }
3886
3887 /**
3888 * alloc_profile_is_valid - see if a given profile is valid and reduced
3889 * @flags: profile to validate
3890 * @extended: if true @flags is treated as an extended profile
3891 */
3892 static int alloc_profile_is_valid(u64 flags, int extended)
3893 {
3894 u64 mask = (extended ? BTRFS_EXTENDED_PROFILE_MASK :
3895 BTRFS_BLOCK_GROUP_PROFILE_MASK);
3896
3897 flags &= ~BTRFS_BLOCK_GROUP_TYPE_MASK;
3898
3899 /* 1) check that all other bits are zeroed */
3900 if (flags & ~mask)
3901 return 0;
3902
3903 /* 2) see if profile is reduced */
3904 if (flags == 0)
3905 return !extended; /* "0" is valid for usual profiles */
3906
3907 /* true if exactly one bit set */
3908 return is_power_of_2(flags);
3909 }
3910
3911 static inline int balance_need_close(struct btrfs_fs_info *fs_info)
3912 {
3913 /* cancel requested || normal exit path */
3914 return atomic_read(&fs_info->balance_cancel_req) ||
3915 (atomic_read(&fs_info->balance_pause_req) == 0 &&
3916 atomic_read(&fs_info->balance_cancel_req) == 0);
3917 }
3918
3919 /* Non-zero return value signifies invalidity */
3920 static inline int validate_convert_profile(struct btrfs_balance_args *bctl_arg,
3921 u64 allowed)
3922 {
3923 return ((bctl_arg->flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3924 (!alloc_profile_is_valid(bctl_arg->target, 1) ||
3925 (bctl_arg->target & ~allowed)));
3926 }
3927
3928 /*
3929 * Should be called with balance mutexe held
3930 */
3931 int btrfs_balance(struct btrfs_fs_info *fs_info,
3932 struct btrfs_balance_control *bctl,
3933 struct btrfs_ioctl_balance_args *bargs)
3934 {
3935 u64 meta_target, data_target;
3936 u64 allowed;
3937 int mixed = 0;
3938 int ret;
3939 u64 num_devices;
3940 unsigned seq;
3941 bool reducing_integrity;
3942
3943 if (btrfs_fs_closing(fs_info) ||
3944 atomic_read(&fs_info->balance_pause_req) ||
3945 atomic_read(&fs_info->balance_cancel_req)) {
3946 ret = -EINVAL;
3947 goto out;
3948 }
3949
3950 allowed = btrfs_super_incompat_flags(fs_info->super_copy);
3951 if (allowed & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
3952 mixed = 1;
3953
3954 /*
3955 * In case of mixed groups both data and meta should be picked,
3956 * and identical options should be given for both of them.
3957 */
3958 allowed = BTRFS_BALANCE_DATA | BTRFS_BALANCE_METADATA;
3959 if (mixed && (bctl->flags & allowed)) {
3960 if (!(bctl->flags & BTRFS_BALANCE_DATA) ||
3961 !(bctl->flags & BTRFS_BALANCE_METADATA) ||
3962 memcmp(&bctl->data, &bctl->meta, sizeof(bctl->data))) {
3963 btrfs_err(fs_info,
3964 "balance: mixed groups data and metadata options must be the same");
3965 ret = -EINVAL;
3966 goto out;
3967 }
3968 }
3969
3970 num_devices = btrfs_num_devices(fs_info);
3971
3972 allowed = BTRFS_AVAIL_ALLOC_BIT_SINGLE | BTRFS_BLOCK_GROUP_DUP;
3973 if (num_devices > 1)
3974 allowed |= (BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID1);
3975 if (num_devices > 2)
3976 allowed |= BTRFS_BLOCK_GROUP_RAID5;
3977 if (num_devices > 3)
3978 allowed |= (BTRFS_BLOCK_GROUP_RAID10 |
3979 BTRFS_BLOCK_GROUP_RAID6);
3980 if (validate_convert_profile(&bctl->data, allowed)) {
3981 int index = btrfs_bg_flags_to_raid_index(bctl->data.target);
3982
3983 btrfs_err(fs_info,
3984 "balance: invalid convert data profile %s",
3985 get_raid_name(index));
3986 ret = -EINVAL;
3987 goto out;
3988 }
3989 if (validate_convert_profile(&bctl->meta, allowed)) {
3990 int index = btrfs_bg_flags_to_raid_index(bctl->meta.target);
3991
3992 btrfs_err(fs_info,
3993 "balance: invalid convert metadata profile %s",
3994 get_raid_name(index));
3995 ret = -EINVAL;
3996 goto out;
3997 }
3998 if (validate_convert_profile(&bctl->sys, allowed)) {
3999 int index = btrfs_bg_flags_to_raid_index(bctl->sys.target);
4000
4001 btrfs_err(fs_info,
4002 "balance: invalid convert system profile %s",
4003 get_raid_name(index));
4004 ret = -EINVAL;
4005 goto out;
4006 }
4007
4008 /* allow to reduce meta or sys integrity only if force set */
4009 allowed = BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1 |
4010 BTRFS_BLOCK_GROUP_RAID10 |
4011 BTRFS_BLOCK_GROUP_RAID5 |
4012 BTRFS_BLOCK_GROUP_RAID6;
4013 do {
4014 seq = read_seqbegin(&fs_info->profiles_lock);
4015
4016 if (((bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
4017 (fs_info->avail_system_alloc_bits & allowed) &&
4018 !(bctl->sys.target & allowed)) ||
4019 ((bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
4020 (fs_info->avail_metadata_alloc_bits & allowed) &&
4021 !(bctl->meta.target & allowed)))
4022 reducing_integrity = true;
4023 else
4024 reducing_integrity = false;
4025
4026 /* if we're not converting, the target field is uninitialized */
4027 meta_target = (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) ?
4028 bctl->meta.target : fs_info->avail_metadata_alloc_bits;
4029 data_target = (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) ?
4030 bctl->data.target : fs_info->avail_data_alloc_bits;
4031 } while (read_seqretry(&fs_info->profiles_lock, seq));
4032
4033 if (reducing_integrity) {
4034 if (bctl->flags & BTRFS_BALANCE_FORCE) {
4035 btrfs_info(fs_info,
4036 "balance: force reducing metadata integrity");
4037 } else {
4038 btrfs_err(fs_info,
4039 "balance: reduces metadata integrity, use --force if you want this");
4040 ret = -EINVAL;
4041 goto out;
4042 }
4043 }
4044
4045 if (btrfs_get_num_tolerated_disk_barrier_failures(meta_target) <
4046 btrfs_get_num_tolerated_disk_barrier_failures(data_target)) {
4047 int meta_index = btrfs_bg_flags_to_raid_index(meta_target);
4048 int data_index = btrfs_bg_flags_to_raid_index(data_target);
4049
4050 btrfs_warn(fs_info,
4051 "balance: metadata profile %s has lower redundancy than data profile %s",
4052 get_raid_name(meta_index), get_raid_name(data_index));
4053 }
4054
4055 ret = insert_balance_item(fs_info, bctl);
4056 if (ret && ret != -EEXIST)
4057 goto out;
4058
4059 if (!(bctl->flags & BTRFS_BALANCE_RESUME)) {
4060 BUG_ON(ret == -EEXIST);
4061 BUG_ON(fs_info->balance_ctl);
4062 spin_lock(&fs_info->balance_lock);
4063 fs_info->balance_ctl = bctl;
4064 spin_unlock(&fs_info->balance_lock);
4065 } else {
4066 BUG_ON(ret != -EEXIST);
4067 spin_lock(&fs_info->balance_lock);
4068 update_balance_args(bctl);
4069 spin_unlock(&fs_info->balance_lock);
4070 }
4071
4072 ASSERT(!test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4073 set_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags);
4074 mutex_unlock(&fs_info->balance_mutex);
4075
4076 ret = __btrfs_balance(fs_info);
4077
4078 mutex_lock(&fs_info->balance_mutex);
4079 clear_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags);
4080
4081 if (bargs) {
4082 memset(bargs, 0, sizeof(*bargs));
4083 btrfs_update_ioctl_balance_args(fs_info, bargs);
4084 }
4085
4086 if ((ret && ret != -ECANCELED && ret != -ENOSPC) ||
4087 balance_need_close(fs_info)) {
4088 reset_balance_state(fs_info);
4089 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
4090 }
4091
4092 wake_up(&fs_info->balance_wait_q);
4093
4094 return ret;
4095 out:
4096 if (bctl->flags & BTRFS_BALANCE_RESUME)
4097 reset_balance_state(fs_info);
4098 else
4099 kfree(bctl);
4100 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
4101
4102 return ret;
4103 }
4104
4105 static int balance_kthread(void *data)
4106 {
4107 struct btrfs_fs_info *fs_info = data;
4108 int ret = 0;
4109
4110 mutex_lock(&fs_info->balance_mutex);
4111 if (fs_info->balance_ctl) {
4112 btrfs_info(fs_info, "balance: resuming");
4113 ret = btrfs_balance(fs_info, fs_info->balance_ctl, NULL);
4114 }
4115 mutex_unlock(&fs_info->balance_mutex);
4116
4117 return ret;
4118 }
4119
4120 int btrfs_resume_balance_async(struct btrfs_fs_info *fs_info)
4121 {
4122 struct task_struct *tsk;
4123
4124 mutex_lock(&fs_info->balance_mutex);
4125 if (!fs_info->balance_ctl) {
4126 mutex_unlock(&fs_info->balance_mutex);
4127 return 0;
4128 }
4129 mutex_unlock(&fs_info->balance_mutex);
4130
4131 if (btrfs_test_opt(fs_info, SKIP_BALANCE)) {
4132 btrfs_info(fs_info, "balance: resume skipped");
4133 return 0;
4134 }
4135
4136 /*
4137 * A ro->rw remount sequence should continue with the paused balance
4138 * regardless of who pauses it, system or the user as of now, so set
4139 * the resume flag.
4140 */
4141 spin_lock(&fs_info->balance_lock);
4142 fs_info->balance_ctl->flags |= BTRFS_BALANCE_RESUME;
4143 spin_unlock(&fs_info->balance_lock);
4144
4145 tsk = kthread_run(balance_kthread, fs_info, "btrfs-balance");
4146 return PTR_ERR_OR_ZERO(tsk);
4147 }
4148
4149 int btrfs_recover_balance(struct btrfs_fs_info *fs_info)
4150 {
4151 struct btrfs_balance_control *bctl;
4152 struct btrfs_balance_item *item;
4153 struct btrfs_disk_balance_args disk_bargs;
4154 struct btrfs_path *path;
4155 struct extent_buffer *leaf;
4156 struct btrfs_key key;
4157 int ret;
4158
4159 path = btrfs_alloc_path();
4160 if (!path)
4161 return -ENOMEM;
4162
4163 key.objectid = BTRFS_BALANCE_OBJECTID;
4164 key.type = BTRFS_TEMPORARY_ITEM_KEY;
4165 key.offset = 0;
4166
4167 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
4168 if (ret < 0)
4169 goto out;
4170 if (ret > 0) { /* ret = -ENOENT; */
4171 ret = 0;
4172 goto out;
4173 }
4174
4175 bctl = kzalloc(sizeof(*bctl), GFP_NOFS);
4176 if (!bctl) {
4177 ret = -ENOMEM;
4178 goto out;
4179 }
4180
4181 leaf = path->nodes[0];
4182 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
4183
4184 bctl->flags = btrfs_balance_flags(leaf, item);
4185 bctl->flags |= BTRFS_BALANCE_RESUME;
4186
4187 btrfs_balance_data(leaf, item, &disk_bargs);
4188 btrfs_disk_balance_args_to_cpu(&bctl->data, &disk_bargs);
4189 btrfs_balance_meta(leaf, item, &disk_bargs);
4190 btrfs_disk_balance_args_to_cpu(&bctl->meta, &disk_bargs);
4191 btrfs_balance_sys(leaf, item, &disk_bargs);
4192 btrfs_disk_balance_args_to_cpu(&bctl->sys, &disk_bargs);
4193
4194 /*
4195 * This should never happen, as the paused balance state is recovered
4196 * during mount without any chance of other exclusive ops to collide.
4197 *
4198 * This gives the exclusive op status to balance and keeps in paused
4199 * state until user intervention (cancel or umount). If the ownership
4200 * cannot be assigned, show a message but do not fail. The balance
4201 * is in a paused state and must have fs_info::balance_ctl properly
4202 * set up.
4203 */
4204 if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags))
4205 btrfs_warn(fs_info,
4206 "balance: cannot set exclusive op status, resume manually");
4207
4208 mutex_lock(&fs_info->balance_mutex);
4209 BUG_ON(fs_info->balance_ctl);
4210 spin_lock(&fs_info->balance_lock);
4211 fs_info->balance_ctl = bctl;
4212 spin_unlock(&fs_info->balance_lock);
4213 mutex_unlock(&fs_info->balance_mutex);
4214 out:
4215 btrfs_free_path(path);
4216 return ret;
4217 }
4218
4219 int btrfs_pause_balance(struct btrfs_fs_info *fs_info)
4220 {
4221 int ret = 0;
4222
4223 mutex_lock(&fs_info->balance_mutex);
4224 if (!fs_info->balance_ctl) {
4225 mutex_unlock(&fs_info->balance_mutex);
4226 return -ENOTCONN;
4227 }
4228
4229 if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
4230 atomic_inc(&fs_info->balance_pause_req);
4231 mutex_unlock(&fs_info->balance_mutex);
4232
4233 wait_event(fs_info->balance_wait_q,
4234 !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4235
4236 mutex_lock(&fs_info->balance_mutex);
4237 /* we are good with balance_ctl ripped off from under us */
4238 BUG_ON(test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4239 atomic_dec(&fs_info->balance_pause_req);
4240 } else {
4241 ret = -ENOTCONN;
4242 }
4243
4244 mutex_unlock(&fs_info->balance_mutex);
4245 return ret;
4246 }
4247
4248 int btrfs_cancel_balance(struct btrfs_fs_info *fs_info)
4249 {
4250 mutex_lock(&fs_info->balance_mutex);
4251 if (!fs_info->balance_ctl) {
4252 mutex_unlock(&fs_info->balance_mutex);
4253 return -ENOTCONN;
4254 }
4255
4256 /*
4257 * A paused balance with the item stored on disk can be resumed at
4258 * mount time if the mount is read-write. Otherwise it's still paused
4259 * and we must not allow cancelling as it deletes the item.
4260 */
4261 if (sb_rdonly(fs_info->sb)) {
4262 mutex_unlock(&fs_info->balance_mutex);
4263 return -EROFS;
4264 }
4265
4266 atomic_inc(&fs_info->balance_cancel_req);
4267 /*
4268 * if we are running just wait and return, balance item is
4269 * deleted in btrfs_balance in this case
4270 */
4271 if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
4272 mutex_unlock(&fs_info->balance_mutex);
4273 wait_event(fs_info->balance_wait_q,
4274 !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4275 mutex_lock(&fs_info->balance_mutex);
4276 } else {
4277 mutex_unlock(&fs_info->balance_mutex);
4278 /*
4279 * Lock released to allow other waiters to continue, we'll
4280 * reexamine the status again.
4281 */
4282 mutex_lock(&fs_info->balance_mutex);
4283
4284 if (fs_info->balance_ctl) {
4285 reset_balance_state(fs_info);
4286 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
4287 btrfs_info(fs_info, "balance: canceled");
4288 }
4289 }
4290
4291 BUG_ON(fs_info->balance_ctl ||
4292 test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4293 atomic_dec(&fs_info->balance_cancel_req);
4294 mutex_unlock(&fs_info->balance_mutex);
4295 return 0;
4296 }
4297
4298 static int btrfs_uuid_scan_kthread(void *data)
4299 {
4300 struct btrfs_fs_info *fs_info = data;
4301 struct btrfs_root *root = fs_info->tree_root;
4302 struct btrfs_key key;
4303 struct btrfs_path *path = NULL;
4304 int ret = 0;
4305 struct extent_buffer *eb;
4306 int slot;
4307 struct btrfs_root_item root_item;
4308 u32 item_size;
4309 struct btrfs_trans_handle *trans = NULL;
4310
4311 path = btrfs_alloc_path();
4312 if (!path) {
4313 ret = -ENOMEM;
4314 goto out;
4315 }
4316
4317 key.objectid = 0;
4318 key.type = BTRFS_ROOT_ITEM_KEY;
4319 key.offset = 0;
4320
4321 while (1) {
4322 ret = btrfs_search_forward(root, &key, path,
4323 BTRFS_OLDEST_GENERATION);
4324 if (ret) {
4325 if (ret > 0)
4326 ret = 0;
4327 break;
4328 }
4329
4330 if (key.type != BTRFS_ROOT_ITEM_KEY ||
4331 (key.objectid < BTRFS_FIRST_FREE_OBJECTID &&
4332 key.objectid != BTRFS_FS_TREE_OBJECTID) ||
4333 key.objectid > BTRFS_LAST_FREE_OBJECTID)
4334 goto skip;
4335
4336 eb = path->nodes[0];
4337 slot = path->slots[0];
4338 item_size = btrfs_item_size_nr(eb, slot);
4339 if (item_size < sizeof(root_item))
4340 goto skip;
4341
4342 read_extent_buffer(eb, &root_item,
4343 btrfs_item_ptr_offset(eb, slot),
4344 (int)sizeof(root_item));
4345 if (btrfs_root_refs(&root_item) == 0)
4346 goto skip;
4347
4348 if (!btrfs_is_empty_uuid(root_item.uuid) ||
4349 !btrfs_is_empty_uuid(root_item.received_uuid)) {
4350 if (trans)
4351 goto update_tree;
4352
4353 btrfs_release_path(path);
4354 /*
4355 * 1 - subvol uuid item
4356 * 1 - received_subvol uuid item
4357 */
4358 trans = btrfs_start_transaction(fs_info->uuid_root, 2);
4359 if (IS_ERR(trans)) {
4360 ret = PTR_ERR(trans);
4361 break;
4362 }
4363 continue;
4364 } else {
4365 goto skip;
4366 }
4367 update_tree:
4368 if (!btrfs_is_empty_uuid(root_item.uuid)) {
4369 ret = btrfs_uuid_tree_add(trans, root_item.uuid,
4370 BTRFS_UUID_KEY_SUBVOL,
4371 key.objectid);
4372 if (ret < 0) {
4373 btrfs_warn(fs_info, "uuid_tree_add failed %d",
4374 ret);
4375 break;
4376 }
4377 }
4378
4379 if (!btrfs_is_empty_uuid(root_item.received_uuid)) {
4380 ret = btrfs_uuid_tree_add(trans,
4381 root_item.received_uuid,
4382 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4383 key.objectid);
4384 if (ret < 0) {
4385 btrfs_warn(fs_info, "uuid_tree_add failed %d",
4386 ret);
4387 break;
4388 }
4389 }
4390
4391 skip:
4392 if (trans) {
4393 ret = btrfs_end_transaction(trans);
4394 trans = NULL;
4395 if (ret)
4396 break;
4397 }
4398
4399 btrfs_release_path(path);
4400 if (key.offset < (u64)-1) {
4401 key.offset++;
4402 } else if (key.type < BTRFS_ROOT_ITEM_KEY) {
4403 key.offset = 0;
4404 key.type = BTRFS_ROOT_ITEM_KEY;
4405 } else if (key.objectid < (u64)-1) {
4406 key.offset = 0;
4407 key.type = BTRFS_ROOT_ITEM_KEY;
4408 key.objectid++;
4409 } else {
4410 break;
4411 }
4412 cond_resched();
4413 }
4414
4415 out:
4416 btrfs_free_path(path);
4417 if (trans && !IS_ERR(trans))
4418 btrfs_end_transaction(trans);
4419 if (ret)
4420 btrfs_warn(fs_info, "btrfs_uuid_scan_kthread failed %d", ret);
4421 else
4422 set_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags);
4423 up(&fs_info->uuid_tree_rescan_sem);
4424 return 0;
4425 }
4426
4427 /*
4428 * Callback for btrfs_uuid_tree_iterate().
4429 * returns:
4430 * 0 check succeeded, the entry is not outdated.
4431 * < 0 if an error occurred.
4432 * > 0 if the check failed, which means the caller shall remove the entry.
4433 */
4434 static int btrfs_check_uuid_tree_entry(struct btrfs_fs_info *fs_info,
4435 u8 *uuid, u8 type, u64 subid)
4436 {
4437 struct btrfs_key key;
4438 int ret = 0;
4439 struct btrfs_root *subvol_root;
4440
4441 if (type != BTRFS_UUID_KEY_SUBVOL &&
4442 type != BTRFS_UUID_KEY_RECEIVED_SUBVOL)
4443 goto out;
4444
4445 key.objectid = subid;
4446 key.type = BTRFS_ROOT_ITEM_KEY;
4447 key.offset = (u64)-1;
4448 subvol_root = btrfs_read_fs_root_no_name(fs_info, &key);
4449 if (IS_ERR(subvol_root)) {
4450 ret = PTR_ERR(subvol_root);
4451 if (ret == -ENOENT)
4452 ret = 1;
4453 goto out;
4454 }
4455
4456 switch (type) {
4457 case BTRFS_UUID_KEY_SUBVOL:
4458 if (memcmp(uuid, subvol_root->root_item.uuid, BTRFS_UUID_SIZE))
4459 ret = 1;
4460 break;
4461 case BTRFS_UUID_KEY_RECEIVED_SUBVOL:
4462 if (memcmp(uuid, subvol_root->root_item.received_uuid,
4463 BTRFS_UUID_SIZE))
4464 ret = 1;
4465 break;
4466 }
4467
4468 out:
4469 return ret;
4470 }
4471
4472 static int btrfs_uuid_rescan_kthread(void *data)
4473 {
4474 struct btrfs_fs_info *fs_info = (struct btrfs_fs_info *)data;
4475 int ret;
4476
4477 /*
4478 * 1st step is to iterate through the existing UUID tree and
4479 * to delete all entries that contain outdated data.
4480 * 2nd step is to add all missing entries to the UUID tree.
4481 */
4482 ret = btrfs_uuid_tree_iterate(fs_info, btrfs_check_uuid_tree_entry);
4483 if (ret < 0) {
4484 btrfs_warn(fs_info, "iterating uuid_tree failed %d", ret);
4485 up(&fs_info->uuid_tree_rescan_sem);
4486 return ret;
4487 }
4488 return btrfs_uuid_scan_kthread(data);
4489 }
4490
4491 int btrfs_create_uuid_tree(struct btrfs_fs_info *fs_info)
4492 {
4493 struct btrfs_trans_handle *trans;
4494 struct btrfs_root *tree_root = fs_info->tree_root;
4495 struct btrfs_root *uuid_root;
4496 struct task_struct *task;
4497 int ret;
4498
4499 /*
4500 * 1 - root node
4501 * 1 - root item
4502 */
4503 trans = btrfs_start_transaction(tree_root, 2);
4504 if (IS_ERR(trans))
4505 return PTR_ERR(trans);
4506
4507 uuid_root = btrfs_create_tree(trans, fs_info,
4508 BTRFS_UUID_TREE_OBJECTID);
4509 if (IS_ERR(uuid_root)) {
4510 ret = PTR_ERR(uuid_root);
4511 btrfs_abort_transaction(trans, ret);
4512 btrfs_end_transaction(trans);
4513 return ret;
4514 }
4515
4516 fs_info->uuid_root = uuid_root;
4517
4518 ret = btrfs_commit_transaction(trans);
4519 if (ret)
4520 return ret;
4521
4522 down(&fs_info->uuid_tree_rescan_sem);
4523 task = kthread_run(btrfs_uuid_scan_kthread, fs_info, "btrfs-uuid");
4524 if (IS_ERR(task)) {
4525 /* fs_info->update_uuid_tree_gen remains 0 in all error case */
4526 btrfs_warn(fs_info, "failed to start uuid_scan task");
4527 up(&fs_info->uuid_tree_rescan_sem);
4528 return PTR_ERR(task);
4529 }
4530
4531 return 0;
4532 }
4533
4534 int btrfs_check_uuid_tree(struct btrfs_fs_info *fs_info)
4535 {
4536 struct task_struct *task;
4537
4538 down(&fs_info->uuid_tree_rescan_sem);
4539 task = kthread_run(btrfs_uuid_rescan_kthread, fs_info, "btrfs-uuid");
4540 if (IS_ERR(task)) {
4541 /* fs_info->update_uuid_tree_gen remains 0 in all error case */
4542 btrfs_warn(fs_info, "failed to start uuid_rescan task");
4543 up(&fs_info->uuid_tree_rescan_sem);
4544 return PTR_ERR(task);
4545 }
4546
4547 return 0;
4548 }
4549
4550 /*
4551 * shrinking a device means finding all of the device extents past
4552 * the new size, and then following the back refs to the chunks.
4553 * The chunk relocation code actually frees the device extent
4554 */
4555 int btrfs_shrink_device(struct btrfs_device *device, u64 new_size)
4556 {
4557 struct btrfs_fs_info *fs_info = device->fs_info;
4558 struct btrfs_root *root = fs_info->dev_root;
4559 struct btrfs_trans_handle *trans;
4560 struct btrfs_dev_extent *dev_extent = NULL;
4561 struct btrfs_path *path;
4562 u64 length;
4563 u64 chunk_offset;
4564 int ret;
4565 int slot;
4566 int failed = 0;
4567 bool retried = false;
4568 bool checked_pending_chunks = false;
4569 struct extent_buffer *l;
4570 struct btrfs_key key;
4571 struct btrfs_super_block *super_copy = fs_info->super_copy;
4572 u64 old_total = btrfs_super_total_bytes(super_copy);
4573 u64 old_size = btrfs_device_get_total_bytes(device);
4574 u64 diff;
4575
4576 new_size = round_down(new_size, fs_info->sectorsize);
4577 diff = round_down(old_size - new_size, fs_info->sectorsize);
4578
4579 if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
4580 return -EINVAL;
4581
4582 path = btrfs_alloc_path();
4583 if (!path)
4584 return -ENOMEM;
4585
4586 path->reada = READA_BACK;
4587
4588 mutex_lock(&fs_info->chunk_mutex);
4589
4590 btrfs_device_set_total_bytes(device, new_size);
4591 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
4592 device->fs_devices->total_rw_bytes -= diff;
4593 atomic64_sub(diff, &fs_info->free_chunk_space);
4594 }
4595 mutex_unlock(&fs_info->chunk_mutex);
4596
4597 again:
4598 key.objectid = device->devid;
4599 key.offset = (u64)-1;
4600 key.type = BTRFS_DEV_EXTENT_KEY;
4601
4602 do {
4603 mutex_lock(&fs_info->delete_unused_bgs_mutex);
4604 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4605 if (ret < 0) {
4606 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4607 goto done;
4608 }
4609
4610 ret = btrfs_previous_item(root, path, 0, key.type);
4611 if (ret)
4612 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4613 if (ret < 0)
4614 goto done;
4615 if (ret) {
4616 ret = 0;
4617 btrfs_release_path(path);
4618 break;
4619 }
4620
4621 l = path->nodes[0];
4622 slot = path->slots[0];
4623 btrfs_item_key_to_cpu(l, &key, path->slots[0]);
4624
4625 if (key.objectid != device->devid) {
4626 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4627 btrfs_release_path(path);
4628 break;
4629 }
4630
4631 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
4632 length = btrfs_dev_extent_length(l, dev_extent);
4633
4634 if (key.offset + length <= new_size) {
4635 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4636 btrfs_release_path(path);
4637 break;
4638 }
4639
4640 chunk_offset = btrfs_dev_extent_chunk_offset(l, dev_extent);
4641 btrfs_release_path(path);
4642
4643 /*
4644 * We may be relocating the only data chunk we have,
4645 * which could potentially end up with losing data's
4646 * raid profile, so lets allocate an empty one in
4647 * advance.
4648 */
4649 ret = btrfs_may_alloc_data_chunk(fs_info, chunk_offset);
4650 if (ret < 0) {
4651 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4652 goto done;
4653 }
4654
4655 ret = btrfs_relocate_chunk(fs_info, chunk_offset);
4656 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4657 if (ret == -ENOSPC) {
4658 failed++;
4659 } else if (ret) {
4660 if (ret == -ETXTBSY) {
4661 btrfs_warn(fs_info,
4662 "could not shrink block group %llu due to active swapfile",
4663 chunk_offset);
4664 }
4665 goto done;
4666 }
4667 } while (key.offset-- > 0);
4668
4669 if (failed && !retried) {
4670 failed = 0;
4671 retried = true;
4672 goto again;
4673 } else if (failed && retried) {
4674 ret = -ENOSPC;
4675 goto done;
4676 }
4677
4678 /* Shrinking succeeded, else we would be at "done". */
4679 trans = btrfs_start_transaction(root, 0);
4680 if (IS_ERR(trans)) {
4681 ret = PTR_ERR(trans);
4682 goto done;
4683 }
4684
4685 mutex_lock(&fs_info->chunk_mutex);
4686
4687 /*
4688 * We checked in the above loop all device extents that were already in
4689 * the device tree. However before we have updated the device's
4690 * total_bytes to the new size, we might have had chunk allocations that
4691 * have not complete yet (new block groups attached to transaction
4692 * handles), and therefore their device extents were not yet in the
4693 * device tree and we missed them in the loop above. So if we have any
4694 * pending chunk using a device extent that overlaps the device range
4695 * that we can not use anymore, commit the current transaction and
4696 * repeat the search on the device tree - this way we guarantee we will
4697 * not have chunks using device extents that end beyond 'new_size'.
4698 */
4699 if (!checked_pending_chunks) {
4700 u64 start = new_size;
4701 u64 len = old_size - new_size;
4702
4703 if (contains_pending_extent(trans->transaction, device,
4704 &start, len)) {
4705 mutex_unlock(&fs_info->chunk_mutex);
4706 checked_pending_chunks = true;
4707 failed = 0;
4708 retried = false;
4709 ret = btrfs_commit_transaction(trans);
4710 if (ret)
4711 goto done;
4712 goto again;
4713 }
4714 }
4715
4716 btrfs_device_set_disk_total_bytes(device, new_size);
4717 if (list_empty(&device->resized_list))
4718 list_add_tail(&device->resized_list,
4719 &fs_info->fs_devices->resized_devices);
4720
4721 WARN_ON(diff > old_total);
4722 btrfs_set_super_total_bytes(super_copy,
4723 round_down(old_total - diff, fs_info->sectorsize));
4724 mutex_unlock(&fs_info->chunk_mutex);
4725
4726 /* Now btrfs_update_device() will change the on-disk size. */
4727 ret = btrfs_update_device(trans, device);
4728 if (ret < 0) {
4729 btrfs_abort_transaction(trans, ret);
4730 btrfs_end_transaction(trans);
4731 } else {
4732 ret = btrfs_commit_transaction(trans);
4733 }
4734 done:
4735 btrfs_free_path(path);
4736 if (ret) {
4737 mutex_lock(&fs_info->chunk_mutex);
4738 btrfs_device_set_total_bytes(device, old_size);
4739 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
4740 device->fs_devices->total_rw_bytes += diff;
4741 atomic64_add(diff, &fs_info->free_chunk_space);
4742 mutex_unlock(&fs_info->chunk_mutex);
4743 }
4744 return ret;
4745 }
4746
4747 static int btrfs_add_system_chunk(struct btrfs_fs_info *fs_info,
4748 struct btrfs_key *key,
4749 struct btrfs_chunk *chunk, int item_size)
4750 {
4751 struct btrfs_super_block *super_copy = fs_info->super_copy;
4752 struct btrfs_disk_key disk_key;
4753 u32 array_size;
4754 u8 *ptr;
4755
4756 mutex_lock(&fs_info->chunk_mutex);
4757 array_size = btrfs_super_sys_array_size(super_copy);
4758 if (array_size + item_size + sizeof(disk_key)
4759 > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE) {
4760 mutex_unlock(&fs_info->chunk_mutex);
4761 return -EFBIG;
4762 }
4763
4764 ptr = super_copy->sys_chunk_array + array_size;
4765 btrfs_cpu_key_to_disk(&disk_key, key);
4766 memcpy(ptr, &disk_key, sizeof(disk_key));
4767 ptr += sizeof(disk_key);
4768 memcpy(ptr, chunk, item_size);
4769 item_size += sizeof(disk_key);
4770 btrfs_set_super_sys_array_size(super_copy, array_size + item_size);
4771 mutex_unlock(&fs_info->chunk_mutex);
4772
4773 return 0;
4774 }
4775
4776 /*
4777 * sort the devices in descending order by max_avail, total_avail
4778 */
4779 static int btrfs_cmp_device_info(const void *a, const void *b)
4780 {
4781 const struct btrfs_device_info *di_a = a;
4782 const struct btrfs_device_info *di_b = b;
4783
4784 if (di_a->max_avail > di_b->max_avail)
4785 return -1;
4786 if (di_a->max_avail < di_b->max_avail)
4787 return 1;
4788 if (di_a->total_avail > di_b->total_avail)
4789 return -1;
4790 if (di_a->total_avail < di_b->total_avail)
4791 return 1;
4792 return 0;
4793 }
4794
4795 static void check_raid56_incompat_flag(struct btrfs_fs_info *info, u64 type)
4796 {
4797 if (!(type & BTRFS_BLOCK_GROUP_RAID56_MASK))
4798 return;
4799
4800 btrfs_set_fs_incompat(info, RAID56);
4801 }
4802
4803 #define BTRFS_MAX_DEVS(info) ((BTRFS_MAX_ITEM_SIZE(info) \
4804 - sizeof(struct btrfs_chunk)) \
4805 / sizeof(struct btrfs_stripe) + 1)
4806
4807 #define BTRFS_MAX_DEVS_SYS_CHUNK ((BTRFS_SYSTEM_CHUNK_ARRAY_SIZE \
4808 - 2 * sizeof(struct btrfs_disk_key) \
4809 - 2 * sizeof(struct btrfs_chunk)) \
4810 / sizeof(struct btrfs_stripe) + 1)
4811
4812 static int __btrfs_alloc_chunk(struct btrfs_trans_handle *trans,
4813 u64 start, u64 type)
4814 {
4815 struct btrfs_fs_info *info = trans->fs_info;
4816 struct btrfs_fs_devices *fs_devices = info->fs_devices;
4817 struct btrfs_device *device;
4818 struct map_lookup *map = NULL;
4819 struct extent_map_tree *em_tree;
4820 struct extent_map *em;
4821 struct btrfs_device_info *devices_info = NULL;
4822 u64 total_avail;
4823 int num_stripes; /* total number of stripes to allocate */
4824 int data_stripes; /* number of stripes that count for
4825 block group size */
4826 int sub_stripes; /* sub_stripes info for map */
4827 int dev_stripes; /* stripes per dev */
4828 int devs_max; /* max devs to use */
4829 int devs_min; /* min devs needed */
4830 int devs_increment; /* ndevs has to be a multiple of this */
4831 int ncopies; /* how many copies to data has */
4832 int nparity; /* number of stripes worth of bytes to
4833 store parity information */
4834 int ret;
4835 u64 max_stripe_size;
4836 u64 max_chunk_size;
4837 u64 stripe_size;
4838 u64 chunk_size;
4839 int ndevs;
4840 int i;
4841 int j;
4842 int index;
4843
4844 BUG_ON(!alloc_profile_is_valid(type, 0));
4845
4846 if (list_empty(&fs_devices->alloc_list)) {
4847 if (btrfs_test_opt(info, ENOSPC_DEBUG))
4848 btrfs_debug(info, "%s: no writable device", __func__);
4849 return -ENOSPC;
4850 }
4851
4852 index = btrfs_bg_flags_to_raid_index(type);
4853
4854 sub_stripes = btrfs_raid_array[index].sub_stripes;
4855 dev_stripes = btrfs_raid_array[index].dev_stripes;
4856 devs_max = btrfs_raid_array[index].devs_max;
4857 devs_min = btrfs_raid_array[index].devs_min;
4858 devs_increment = btrfs_raid_array[index].devs_increment;
4859 ncopies = btrfs_raid_array[index].ncopies;
4860 nparity = btrfs_raid_array[index].nparity;
4861
4862 if (type & BTRFS_BLOCK_GROUP_DATA) {
4863 max_stripe_size = SZ_1G;
4864 max_chunk_size = BTRFS_MAX_DATA_CHUNK_SIZE;
4865 if (!devs_max)
4866 devs_max = BTRFS_MAX_DEVS(info);
4867 } else if (type & BTRFS_BLOCK_GROUP_METADATA) {
4868 /* for larger filesystems, use larger metadata chunks */
4869 if (fs_devices->total_rw_bytes > 50ULL * SZ_1G)
4870 max_stripe_size = SZ_1G;
4871 else
4872 max_stripe_size = SZ_256M;
4873 max_chunk_size = max_stripe_size;
4874 if (!devs_max)
4875 devs_max = BTRFS_MAX_DEVS(info);
4876 } else if (type & BTRFS_BLOCK_GROUP_SYSTEM) {
4877 max_stripe_size = SZ_32M;
4878 max_chunk_size = 2 * max_stripe_size;
4879 if (!devs_max)
4880 devs_max = BTRFS_MAX_DEVS_SYS_CHUNK;
4881 } else {
4882 btrfs_err(info, "invalid chunk type 0x%llx requested",
4883 type);
4884 BUG_ON(1);
4885 }
4886
4887 /* we don't want a chunk larger than 10% of writeable space */
4888 max_chunk_size = min(div_factor(fs_devices->total_rw_bytes, 1),
4889 max_chunk_size);
4890
4891 devices_info = kcalloc(fs_devices->rw_devices, sizeof(*devices_info),
4892 GFP_NOFS);
4893 if (!devices_info)
4894 return -ENOMEM;
4895
4896 /*
4897 * in the first pass through the devices list, we gather information
4898 * about the available holes on each device.
4899 */
4900 ndevs = 0;
4901 list_for_each_entry(device, &fs_devices->alloc_list, dev_alloc_list) {
4902 u64 max_avail;
4903 u64 dev_offset;
4904
4905 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
4906 WARN(1, KERN_ERR
4907 "BTRFS: read-only device in alloc_list\n");
4908 continue;
4909 }
4910
4911 if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
4912 &device->dev_state) ||
4913 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
4914 continue;
4915
4916 if (device->total_bytes > device->bytes_used)
4917 total_avail = device->total_bytes - device->bytes_used;
4918 else
4919 total_avail = 0;
4920
4921 /* If there is no space on this device, skip it. */
4922 if (total_avail == 0)
4923 continue;
4924
4925 ret = find_free_dev_extent(trans, device,
4926 max_stripe_size * dev_stripes,
4927 &dev_offset, &max_avail);
4928 if (ret && ret != -ENOSPC)
4929 goto error;
4930
4931 if (ret == 0)
4932 max_avail = max_stripe_size * dev_stripes;
4933
4934 if (max_avail < BTRFS_STRIPE_LEN * dev_stripes) {
4935 if (btrfs_test_opt(info, ENOSPC_DEBUG))
4936 btrfs_debug(info,
4937 "%s: devid %llu has no free space, have=%llu want=%u",
4938 __func__, device->devid, max_avail,
4939 BTRFS_STRIPE_LEN * dev_stripes);
4940 continue;
4941 }
4942
4943 if (ndevs == fs_devices->rw_devices) {
4944 WARN(1, "%s: found more than %llu devices\n",
4945 __func__, fs_devices->rw_devices);
4946 break;
4947 }
4948 devices_info[ndevs].dev_offset = dev_offset;
4949 devices_info[ndevs].max_avail = max_avail;
4950 devices_info[ndevs].total_avail = total_avail;
4951 devices_info[ndevs].dev = device;
4952 ++ndevs;
4953 }
4954
4955 /*
4956 * now sort the devices by hole size / available space
4957 */
4958 sort(devices_info, ndevs, sizeof(struct btrfs_device_info),
4959 btrfs_cmp_device_info, NULL);
4960
4961 /* round down to number of usable stripes */
4962 ndevs = round_down(ndevs, devs_increment);
4963
4964 if (ndevs < devs_min) {
4965 ret = -ENOSPC;
4966 if (btrfs_test_opt(info, ENOSPC_DEBUG)) {
4967 btrfs_debug(info,
4968 "%s: not enough devices with free space: have=%d minimum required=%d",
4969 __func__, ndevs, devs_min);
4970 }
4971 goto error;
4972 }
4973
4974 ndevs = min(ndevs, devs_max);
4975
4976 /*
4977 * The primary goal is to maximize the number of stripes, so use as
4978 * many devices as possible, even if the stripes are not maximum sized.
4979 *
4980 * The DUP profile stores more than one stripe per device, the
4981 * max_avail is the total size so we have to adjust.
4982 */
4983 stripe_size = div_u64(devices_info[ndevs - 1].max_avail, dev_stripes);
4984 num_stripes = ndevs * dev_stripes;
4985
4986 /*
4987 * this will have to be fixed for RAID1 and RAID10 over
4988 * more drives
4989 */
4990 data_stripes = (num_stripes - nparity) / ncopies;
4991
4992 /*
4993 * Use the number of data stripes to figure out how big this chunk
4994 * is really going to be in terms of logical address space,
4995 * and compare that answer with the max chunk size. If it's higher,
4996 * we try to reduce stripe_size.
4997 */
4998 if (stripe_size * data_stripes > max_chunk_size) {
4999 /*
5000 * Reduce stripe_size, round it up to a 16MB boundary again and
5001 * then use it, unless it ends up being even bigger than the
5002 * previous value we had already.
5003 */
5004 stripe_size = min(round_up(div_u64(max_chunk_size,
5005 data_stripes), SZ_16M),
5006 stripe_size);
5007 }
5008
5009 /* align to BTRFS_STRIPE_LEN */
5010 stripe_size = round_down(stripe_size, BTRFS_STRIPE_LEN);
5011
5012 map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
5013 if (!map) {
5014 ret = -ENOMEM;
5015 goto error;
5016 }
5017 map->num_stripes = num_stripes;
5018
5019 for (i = 0; i < ndevs; ++i) {
5020 for (j = 0; j < dev_stripes; ++j) {
5021 int s = i * dev_stripes + j;
5022 map->stripes[s].dev = devices_info[i].dev;
5023 map->stripes[s].physical = devices_info[i].dev_offset +
5024 j * stripe_size;
5025 }
5026 }
5027 map->stripe_len = BTRFS_STRIPE_LEN;
5028 map->io_align = BTRFS_STRIPE_LEN;
5029 map->io_width = BTRFS_STRIPE_LEN;
5030 map->type = type;
5031 map->sub_stripes = sub_stripes;
5032
5033 chunk_size = stripe_size * data_stripes;
5034
5035 trace_btrfs_chunk_alloc(info, map, start, chunk_size);
5036
5037 em = alloc_extent_map();
5038 if (!em) {
5039 kfree(map);
5040 ret = -ENOMEM;
5041 goto error;
5042 }
5043 set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
5044 em->map_lookup = map;
5045 em->start = start;
5046 em->len = chunk_size;
5047 em->block_start = 0;
5048 em->block_len = em->len;
5049 em->orig_block_len = stripe_size;
5050
5051 em_tree = &info->mapping_tree.map_tree;
5052 write_lock(&em_tree->lock);
5053 ret = add_extent_mapping(em_tree, em, 0);
5054 if (ret) {
5055 write_unlock(&em_tree->lock);
5056 free_extent_map(em);
5057 goto error;
5058 }
5059
5060 list_add_tail(&em->list, &trans->transaction->pending_chunks);
5061 refcount_inc(&em->refs);
5062 write_unlock(&em_tree->lock);
5063
5064 ret = btrfs_make_block_group(trans, 0, type, start, chunk_size);
5065 if (ret)
5066 goto error_del_extent;
5067
5068 for (i = 0; i < map->num_stripes; i++)
5069 btrfs_device_set_bytes_used(map->stripes[i].dev,
5070 map->stripes[i].dev->bytes_used + stripe_size);
5071
5072 atomic64_sub(stripe_size * map->num_stripes, &info->free_chunk_space);
5073
5074 free_extent_map(em);
5075 check_raid56_incompat_flag(info, type);
5076
5077 kfree(devices_info);
5078 return 0;
5079
5080 error_del_extent:
5081 write_lock(&em_tree->lock);
5082 remove_extent_mapping(em_tree, em);
5083 write_unlock(&em_tree->lock);
5084
5085 /* One for our allocation */
5086 free_extent_map(em);
5087 /* One for the tree reference */
5088 free_extent_map(em);
5089 /* One for the pending_chunks list reference */
5090 free_extent_map(em);
5091 error:
5092 kfree(devices_info);
5093 return ret;
5094 }
5095
5096 int btrfs_finish_chunk_alloc(struct btrfs_trans_handle *trans,
5097 u64 chunk_offset, u64 chunk_size)
5098 {
5099 struct btrfs_fs_info *fs_info = trans->fs_info;
5100 struct btrfs_root *extent_root = fs_info->extent_root;
5101 struct btrfs_root *chunk_root = fs_info->chunk_root;
5102 struct btrfs_key key;
5103 struct btrfs_device *device;
5104 struct btrfs_chunk *chunk;
5105 struct btrfs_stripe *stripe;
5106 struct extent_map *em;
5107 struct map_lookup *map;
5108 size_t item_size;
5109 u64 dev_offset;
5110 u64 stripe_size;
5111 int i = 0;
5112 int ret = 0;
5113
5114 em = btrfs_get_chunk_map(fs_info, chunk_offset, chunk_size);
5115 if (IS_ERR(em))
5116 return PTR_ERR(em);
5117
5118 map = em->map_lookup;
5119 item_size = btrfs_chunk_item_size(map->num_stripes);
5120 stripe_size = em->orig_block_len;
5121
5122 chunk = kzalloc(item_size, GFP_NOFS);
5123 if (!chunk) {
5124 ret = -ENOMEM;
5125 goto out;
5126 }
5127
5128 /*
5129 * Take the device list mutex to prevent races with the final phase of
5130 * a device replace operation that replaces the device object associated
5131 * with the map's stripes, because the device object's id can change
5132 * at any time during that final phase of the device replace operation
5133 * (dev-replace.c:btrfs_dev_replace_finishing()).
5134 */
5135 mutex_lock(&fs_info->fs_devices->device_list_mutex);
5136 for (i = 0; i < map->num_stripes; i++) {
5137 device = map->stripes[i].dev;
5138 dev_offset = map->stripes[i].physical;
5139
5140 ret = btrfs_update_device(trans, device);
5141 if (ret)
5142 break;
5143 ret = btrfs_alloc_dev_extent(trans, device, chunk_offset,
5144 dev_offset, stripe_size);
5145 if (ret)
5146 break;
5147 }
5148 if (ret) {
5149 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
5150 goto out;
5151 }
5152
5153 stripe = &chunk->stripe;
5154 for (i = 0; i < map->num_stripes; i++) {
5155 device = map->stripes[i].dev;
5156 dev_offset = map->stripes[i].physical;
5157
5158 btrfs_set_stack_stripe_devid(stripe, device->devid);
5159 btrfs_set_stack_stripe_offset(stripe, dev_offset);
5160 memcpy(stripe->dev_uuid, device->uuid, BTRFS_UUID_SIZE);
5161 stripe++;
5162 }
5163 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
5164
5165 btrfs_set_stack_chunk_length(chunk, chunk_size);
5166 btrfs_set_stack_chunk_owner(chunk, extent_root->root_key.objectid);
5167 btrfs_set_stack_chunk_stripe_len(chunk, map->stripe_len);
5168 btrfs_set_stack_chunk_type(chunk, map->type);
5169 btrfs_set_stack_chunk_num_stripes(chunk, map->num_stripes);
5170 btrfs_set_stack_chunk_io_align(chunk, map->stripe_len);
5171 btrfs_set_stack_chunk_io_width(chunk, map->stripe_len);
5172 btrfs_set_stack_chunk_sector_size(chunk, fs_info->sectorsize);
5173 btrfs_set_stack_chunk_sub_stripes(chunk, map->sub_stripes);
5174
5175 key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
5176 key.type = BTRFS_CHUNK_ITEM_KEY;
5177 key.offset = chunk_offset;
5178
5179 ret = btrfs_insert_item(trans, chunk_root, &key, chunk, item_size);
5180 if (ret == 0 && map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
5181 /*
5182 * TODO: Cleanup of inserted chunk root in case of
5183 * failure.
5184 */
5185 ret = btrfs_add_system_chunk(fs_info, &key, chunk, item_size);
5186 }
5187
5188 out:
5189 kfree(chunk);
5190 free_extent_map(em);
5191 return ret;
5192 }
5193
5194 /*
5195 * Chunk allocation falls into two parts. The first part does works
5196 * that make the new allocated chunk useable, but not do any operation
5197 * that modifies the chunk tree. The second part does the works that
5198 * require modifying the chunk tree. This division is important for the
5199 * bootstrap process of adding storage to a seed btrfs.
5200 */
5201 int btrfs_alloc_chunk(struct btrfs_trans_handle *trans, u64 type)
5202 {
5203 u64 chunk_offset;
5204
5205 lockdep_assert_held(&trans->fs_info->chunk_mutex);
5206 chunk_offset = find_next_chunk(trans->fs_info);
5207 return __btrfs_alloc_chunk(trans, chunk_offset, type);
5208 }
5209
5210 static noinline int init_first_rw_device(struct btrfs_trans_handle *trans,
5211 struct btrfs_fs_info *fs_info)
5212 {
5213 u64 chunk_offset;
5214 u64 sys_chunk_offset;
5215 u64 alloc_profile;
5216 int ret;
5217
5218 chunk_offset = find_next_chunk(fs_info);
5219 alloc_profile = btrfs_metadata_alloc_profile(fs_info);
5220 ret = __btrfs_alloc_chunk(trans, chunk_offset, alloc_profile);
5221 if (ret)
5222 return ret;
5223
5224 sys_chunk_offset = find_next_chunk(fs_info);
5225 alloc_profile = btrfs_system_alloc_profile(fs_info);
5226 ret = __btrfs_alloc_chunk(trans, sys_chunk_offset, alloc_profile);
5227 return ret;
5228 }
5229
5230 static inline int btrfs_chunk_max_errors(struct map_lookup *map)
5231 {
5232 int max_errors;
5233
5234 if (map->type & (BTRFS_BLOCK_GROUP_RAID1 |
5235 BTRFS_BLOCK_GROUP_RAID10 |
5236 BTRFS_BLOCK_GROUP_RAID5 |
5237 BTRFS_BLOCK_GROUP_DUP)) {
5238 max_errors = 1;
5239 } else if (map->type & BTRFS_BLOCK_GROUP_RAID6) {
5240 max_errors = 2;
5241 } else {
5242 max_errors = 0;
5243 }
5244
5245 return max_errors;
5246 }
5247
5248 int btrfs_chunk_readonly(struct btrfs_fs_info *fs_info, u64 chunk_offset)
5249 {
5250 struct extent_map *em;
5251 struct map_lookup *map;
5252 int readonly = 0;
5253 int miss_ndevs = 0;
5254 int i;
5255
5256 em = btrfs_get_chunk_map(fs_info, chunk_offset, 1);
5257 if (IS_ERR(em))
5258 return 1;
5259
5260 map = em->map_lookup;
5261 for (i = 0; i < map->num_stripes; i++) {
5262 if (test_bit(BTRFS_DEV_STATE_MISSING,
5263 &map->stripes[i].dev->dev_state)) {
5264 miss_ndevs++;
5265 continue;
5266 }
5267 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE,
5268 &map->stripes[i].dev->dev_state)) {
5269 readonly = 1;
5270 goto end;
5271 }
5272 }
5273
5274 /*
5275 * If the number of missing devices is larger than max errors,
5276 * we can not write the data into that chunk successfully, so
5277 * set it readonly.
5278 */
5279 if (miss_ndevs > btrfs_chunk_max_errors(map))
5280 readonly = 1;
5281 end:
5282 free_extent_map(em);
5283 return readonly;
5284 }
5285
5286 void btrfs_mapping_init(struct btrfs_mapping_tree *tree)
5287 {
5288 extent_map_tree_init(&tree->map_tree);
5289 }
5290
5291 void btrfs_mapping_tree_free(struct btrfs_mapping_tree *tree)
5292 {
5293 struct extent_map *em;
5294
5295 while (1) {
5296 write_lock(&tree->map_tree.lock);
5297 em = lookup_extent_mapping(&tree->map_tree, 0, (u64)-1);
5298 if (em)
5299 remove_extent_mapping(&tree->map_tree, em);
5300 write_unlock(&tree->map_tree.lock);
5301 if (!em)
5302 break;
5303 /* once for us */
5304 free_extent_map(em);
5305 /* once for the tree */
5306 free_extent_map(em);
5307 }
5308 }
5309
5310 int btrfs_num_copies(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
5311 {
5312 struct extent_map *em;
5313 struct map_lookup *map;
5314 int ret;
5315
5316 em = btrfs_get_chunk_map(fs_info, logical, len);
5317 if (IS_ERR(em))
5318 /*
5319 * We could return errors for these cases, but that could get
5320 * ugly and we'd probably do the same thing which is just not do
5321 * anything else and exit, so return 1 so the callers don't try
5322 * to use other copies.
5323 */
5324 return 1;
5325
5326 map = em->map_lookup;
5327 if (map->type & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1))
5328 ret = map->num_stripes;
5329 else if (map->type & BTRFS_BLOCK_GROUP_RAID10)
5330 ret = map->sub_stripes;
5331 else if (map->type & BTRFS_BLOCK_GROUP_RAID5)
5332 ret = 2;
5333 else if (map->type & BTRFS_BLOCK_GROUP_RAID6)
5334 /*
5335 * There could be two corrupted data stripes, we need
5336 * to loop retry in order to rebuild the correct data.
5337 *
5338 * Fail a stripe at a time on every retry except the
5339 * stripe under reconstruction.
5340 */
5341 ret = map->num_stripes;
5342 else
5343 ret = 1;
5344 free_extent_map(em);
5345
5346 btrfs_dev_replace_read_lock(&fs_info->dev_replace);
5347 if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace) &&
5348 fs_info->dev_replace.tgtdev)
5349 ret++;
5350 btrfs_dev_replace_read_unlock(&fs_info->dev_replace);
5351
5352 return ret;
5353 }
5354
5355 unsigned long btrfs_full_stripe_len(struct btrfs_fs_info *fs_info,
5356 u64 logical)
5357 {
5358 struct extent_map *em;
5359 struct map_lookup *map;
5360 unsigned long len = fs_info->sectorsize;
5361
5362 em = btrfs_get_chunk_map(fs_info, logical, len);
5363
5364 if (!WARN_ON(IS_ERR(em))) {
5365 map = em->map_lookup;
5366 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
5367 len = map->stripe_len * nr_data_stripes(map);
5368 free_extent_map(em);
5369 }
5370 return len;
5371 }
5372
5373 int btrfs_is_parity_mirror(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
5374 {
5375 struct extent_map *em;
5376 struct map_lookup *map;
5377 int ret = 0;
5378
5379 em = btrfs_get_chunk_map(fs_info, logical, len);
5380
5381 if(!WARN_ON(IS_ERR(em))) {
5382 map = em->map_lookup;
5383 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
5384 ret = 1;
5385 free_extent_map(em);
5386 }
5387 return ret;
5388 }
5389
5390 static int find_live_mirror(struct btrfs_fs_info *fs_info,
5391 struct map_lookup *map, int first,
5392 int dev_replace_is_ongoing)
5393 {
5394 int i;
5395 int num_stripes;
5396 int preferred_mirror;
5397 int tolerance;
5398 struct btrfs_device *srcdev;
5399
5400 ASSERT((map->type &
5401 (BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10)));
5402
5403 if (map->type & BTRFS_BLOCK_GROUP_RAID10)
5404 num_stripes = map->sub_stripes;
5405 else
5406 num_stripes = map->num_stripes;
5407
5408 preferred_mirror = first + current->pid % num_stripes;
5409
5410 if (dev_replace_is_ongoing &&
5411 fs_info->dev_replace.cont_reading_from_srcdev_mode ==
5412 BTRFS_DEV_REPLACE_ITEM_CONT_READING_FROM_SRCDEV_MODE_AVOID)
5413 srcdev = fs_info->dev_replace.srcdev;
5414 else
5415 srcdev = NULL;
5416
5417 /*
5418 * try to avoid the drive that is the source drive for a
5419 * dev-replace procedure, only choose it if no other non-missing
5420 * mirror is available
5421 */
5422 for (tolerance = 0; tolerance < 2; tolerance++) {
5423 if (map->stripes[preferred_mirror].dev->bdev &&
5424 (tolerance || map->stripes[preferred_mirror].dev != srcdev))
5425 return preferred_mirror;
5426 for (i = first; i < first + num_stripes; i++) {
5427 if (map->stripes[i].dev->bdev &&
5428 (tolerance || map->stripes[i].dev != srcdev))
5429 return i;
5430 }
5431 }
5432
5433 /* we couldn't find one that doesn't fail. Just return something
5434 * and the io error handling code will clean up eventually
5435 */
5436 return preferred_mirror;
5437 }
5438
5439 static inline int parity_smaller(u64 a, u64 b)
5440 {
5441 return a > b;
5442 }
5443
5444 /* Bubble-sort the stripe set to put the parity/syndrome stripes last */
5445 static void sort_parity_stripes(struct btrfs_bio *bbio, int num_stripes)
5446 {
5447 struct btrfs_bio_stripe s;
5448 int i;
5449 u64 l;
5450 int again = 1;
5451
5452 while (again) {
5453 again = 0;
5454 for (i = 0; i < num_stripes - 1; i++) {
5455 if (parity_smaller(bbio->raid_map[i],
5456 bbio->raid_map[i+1])) {
5457 s = bbio->stripes[i];
5458 l = bbio->raid_map[i];
5459 bbio->stripes[i] = bbio->stripes[i+1];
5460 bbio->raid_map[i] = bbio->raid_map[i+1];
5461 bbio->stripes[i+1] = s;
5462 bbio->raid_map[i+1] = l;
5463
5464 again = 1;
5465 }
5466 }
5467 }
5468 }
5469
5470 static struct btrfs_bio *alloc_btrfs_bio(int total_stripes, int real_stripes)
5471 {
5472 struct btrfs_bio *bbio = kzalloc(
5473 /* the size of the btrfs_bio */
5474 sizeof(struct btrfs_bio) +
5475 /* plus the variable array for the stripes */
5476 sizeof(struct btrfs_bio_stripe) * (total_stripes) +
5477 /* plus the variable array for the tgt dev */
5478 sizeof(int) * (real_stripes) +
5479 /*
5480 * plus the raid_map, which includes both the tgt dev
5481 * and the stripes
5482 */
5483 sizeof(u64) * (total_stripes),
5484 GFP_NOFS|__GFP_NOFAIL);
5485
5486 atomic_set(&bbio->error, 0);
5487 refcount_set(&bbio->refs, 1);
5488
5489 return bbio;
5490 }
5491
5492 void btrfs_get_bbio(struct btrfs_bio *bbio)
5493 {
5494 WARN_ON(!refcount_read(&bbio->refs));
5495 refcount_inc(&bbio->refs);
5496 }
5497
5498 void btrfs_put_bbio(struct btrfs_bio *bbio)
5499 {
5500 if (!bbio)
5501 return;
5502 if (refcount_dec_and_test(&bbio->refs))
5503 kfree(bbio);
5504 }
5505
5506 /* can REQ_OP_DISCARD be sent with other REQ like REQ_OP_WRITE? */
5507 /*
5508 * Please note that, discard won't be sent to target device of device
5509 * replace.
5510 */
5511 static int __btrfs_map_block_for_discard(struct btrfs_fs_info *fs_info,
5512 u64 logical, u64 length,
5513 struct btrfs_bio **bbio_ret)
5514 {
5515 struct extent_map *em;
5516 struct map_lookup *map;
5517 struct btrfs_bio *bbio;
5518 u64 offset;
5519 u64 stripe_nr;
5520 u64 stripe_nr_end;
5521 u64 stripe_end_offset;
5522 u64 stripe_cnt;
5523 u64 stripe_len;
5524 u64 stripe_offset;
5525 u64 num_stripes;
5526 u32 stripe_index;
5527 u32 factor = 0;
5528 u32 sub_stripes = 0;
5529 u64 stripes_per_dev = 0;
5530 u32 remaining_stripes = 0;
5531 u32 last_stripe = 0;
5532 int ret = 0;
5533 int i;
5534
5535 /* discard always return a bbio */
5536 ASSERT(bbio_ret);
5537
5538 em = btrfs_get_chunk_map(fs_info, logical, length);
5539 if (IS_ERR(em))
5540 return PTR_ERR(em);
5541
5542 map = em->map_lookup;
5543 /* we don't discard raid56 yet */
5544 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5545 ret = -EOPNOTSUPP;
5546 goto out;
5547 }
5548
5549 offset = logical - em->start;
5550 length = min_t(u64, em->len - offset, length);
5551
5552 stripe_len = map->stripe_len;
5553 /*
5554 * stripe_nr counts the total number of stripes we have to stride
5555 * to get to this block
5556 */
5557 stripe_nr = div64_u64(offset, stripe_len);
5558
5559 /* stripe_offset is the offset of this block in its stripe */
5560 stripe_offset = offset - stripe_nr * stripe_len;
5561
5562 stripe_nr_end = round_up(offset + length, map->stripe_len);
5563 stripe_nr_end = div64_u64(stripe_nr_end, map->stripe_len);
5564 stripe_cnt = stripe_nr_end - stripe_nr;
5565 stripe_end_offset = stripe_nr_end * map->stripe_len -
5566 (offset + length);
5567 /*
5568 * after this, stripe_nr is the number of stripes on this
5569 * device we have to walk to find the data, and stripe_index is
5570 * the number of our device in the stripe array
5571 */
5572 num_stripes = 1;
5573 stripe_index = 0;
5574 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
5575 BTRFS_BLOCK_GROUP_RAID10)) {
5576 if (map->type & BTRFS_BLOCK_GROUP_RAID0)
5577 sub_stripes = 1;
5578 else
5579 sub_stripes = map->sub_stripes;
5580
5581 factor = map->num_stripes / sub_stripes;
5582 num_stripes = min_t(u64, map->num_stripes,
5583 sub_stripes * stripe_cnt);
5584 stripe_nr = div_u64_rem(stripe_nr, factor, &stripe_index);
5585 stripe_index *= sub_stripes;
5586 stripes_per_dev = div_u64_rem(stripe_cnt, factor,
5587 &remaining_stripes);
5588 div_u64_rem(stripe_nr_end - 1, factor, &last_stripe);
5589 last_stripe *= sub_stripes;
5590 } else if (map->type & (BTRFS_BLOCK_GROUP_RAID1 |
5591 BTRFS_BLOCK_GROUP_DUP)) {
5592 num_stripes = map->num_stripes;
5593 } else {
5594 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
5595 &stripe_index);
5596 }
5597
5598 bbio = alloc_btrfs_bio(num_stripes, 0);
5599 if (!bbio) {
5600 ret = -ENOMEM;
5601 goto out;
5602 }
5603
5604 for (i = 0; i < num_stripes; i++) {
5605 bbio->stripes[i].physical =
5606 map->stripes[stripe_index].physical +
5607 stripe_offset + stripe_nr * map->stripe_len;
5608 bbio->stripes[i].dev = map->stripes[stripe_index].dev;
5609
5610 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
5611 BTRFS_BLOCK_GROUP_RAID10)) {
5612 bbio->stripes[i].length = stripes_per_dev *
5613 map->stripe_len;
5614
5615 if (i / sub_stripes < remaining_stripes)
5616 bbio->stripes[i].length +=
5617 map->stripe_len;
5618
5619 /*
5620 * Special for the first stripe and
5621 * the last stripe:
5622 *
5623 * |-------|...|-------|
5624 * |----------|
5625 * off end_off
5626 */
5627 if (i < sub_stripes)
5628 bbio->stripes[i].length -=
5629 stripe_offset;
5630
5631 if (stripe_index >= last_stripe &&
5632 stripe_index <= (last_stripe +
5633 sub_stripes - 1))
5634 bbio->stripes[i].length -=
5635 stripe_end_offset;
5636
5637 if (i == sub_stripes - 1)
5638 stripe_offset = 0;
5639 } else {
5640 bbio->stripes[i].length = length;
5641 }
5642
5643 stripe_index++;
5644 if (stripe_index == map->num_stripes) {
5645 stripe_index = 0;
5646 stripe_nr++;
5647 }
5648 }
5649
5650 *bbio_ret = bbio;
5651 bbio->map_type = map->type;
5652 bbio->num_stripes = num_stripes;
5653 out:
5654 free_extent_map(em);
5655 return ret;
5656 }
5657
5658 /*
5659 * In dev-replace case, for repair case (that's the only case where the mirror
5660 * is selected explicitly when calling btrfs_map_block), blocks left of the
5661 * left cursor can also be read from the target drive.
5662 *
5663 * For REQ_GET_READ_MIRRORS, the target drive is added as the last one to the
5664 * array of stripes.
5665 * For READ, it also needs to be supported using the same mirror number.
5666 *
5667 * If the requested block is not left of the left cursor, EIO is returned. This
5668 * can happen because btrfs_num_copies() returns one more in the dev-replace
5669 * case.
5670 */
5671 static int get_extra_mirror_from_replace(struct btrfs_fs_info *fs_info,
5672 u64 logical, u64 length,
5673 u64 srcdev_devid, int *mirror_num,
5674 u64 *physical)
5675 {
5676 struct btrfs_bio *bbio = NULL;
5677 int num_stripes;
5678 int index_srcdev = 0;
5679 int found = 0;
5680 u64 physical_of_found = 0;
5681 int i;
5682 int ret = 0;
5683
5684 ret = __btrfs_map_block(fs_info, BTRFS_MAP_GET_READ_MIRRORS,
5685 logical, &length, &bbio, 0, 0);
5686 if (ret) {
5687 ASSERT(bbio == NULL);
5688 return ret;
5689 }
5690
5691 num_stripes = bbio->num_stripes;
5692 if (*mirror_num > num_stripes) {
5693 /*
5694 * BTRFS_MAP_GET_READ_MIRRORS does not contain this mirror,
5695 * that means that the requested area is not left of the left
5696 * cursor
5697 */
5698 btrfs_put_bbio(bbio);
5699 return -EIO;
5700 }
5701
5702 /*
5703 * process the rest of the function using the mirror_num of the source
5704 * drive. Therefore look it up first. At the end, patch the device
5705 * pointer to the one of the target drive.
5706 */
5707 for (i = 0; i < num_stripes; i++) {
5708 if (bbio->stripes[i].dev->devid != srcdev_devid)
5709 continue;
5710
5711 /*
5712 * In case of DUP, in order to keep it simple, only add the
5713 * mirror with the lowest physical address
5714 */
5715 if (found &&
5716 physical_of_found <= bbio->stripes[i].physical)
5717 continue;
5718
5719 index_srcdev = i;
5720 found = 1;
5721 physical_of_found = bbio->stripes[i].physical;
5722 }
5723
5724 btrfs_put_bbio(bbio);
5725
5726 ASSERT(found);
5727 if (!found)
5728 return -EIO;
5729
5730 *mirror_num = index_srcdev + 1;
5731 *physical = physical_of_found;
5732 return ret;
5733 }
5734
5735 static void handle_ops_on_dev_replace(enum btrfs_map_op op,
5736 struct btrfs_bio **bbio_ret,
5737 struct btrfs_dev_replace *dev_replace,
5738 int *num_stripes_ret, int *max_errors_ret)
5739 {
5740 struct btrfs_bio *bbio = *bbio_ret;
5741 u64 srcdev_devid = dev_replace->srcdev->devid;
5742 int tgtdev_indexes = 0;
5743 int num_stripes = *num_stripes_ret;
5744 int max_errors = *max_errors_ret;
5745 int i;
5746
5747 if (op == BTRFS_MAP_WRITE) {
5748 int index_where_to_add;
5749
5750 /*
5751 * duplicate the write operations while the dev replace
5752 * procedure is running. Since the copying of the old disk to
5753 * the new disk takes place at run time while the filesystem is
5754 * mounted writable, the regular write operations to the old
5755 * disk have to be duplicated to go to the new disk as well.
5756 *
5757 * Note that device->missing is handled by the caller, and that
5758 * the write to the old disk is already set up in the stripes
5759 * array.
5760 */
5761 index_where_to_add = num_stripes;
5762 for (i = 0; i < num_stripes; i++) {
5763 if (bbio->stripes[i].dev->devid == srcdev_devid) {
5764 /* write to new disk, too */
5765 struct btrfs_bio_stripe *new =
5766 bbio->stripes + index_where_to_add;
5767 struct btrfs_bio_stripe *old =
5768 bbio->stripes + i;
5769
5770 new->physical = old->physical;
5771 new->length = old->length;
5772 new->dev = dev_replace->tgtdev;
5773 bbio->tgtdev_map[i] = index_where_to_add;
5774 index_where_to_add++;
5775 max_errors++;
5776 tgtdev_indexes++;
5777 }
5778 }
5779 num_stripes = index_where_to_add;
5780 } else if (op == BTRFS_MAP_GET_READ_MIRRORS) {
5781 int index_srcdev = 0;
5782 int found = 0;
5783 u64 physical_of_found = 0;
5784
5785 /*
5786 * During the dev-replace procedure, the target drive can also
5787 * be used to read data in case it is needed to repair a corrupt
5788 * block elsewhere. This is possible if the requested area is
5789 * left of the left cursor. In this area, the target drive is a
5790 * full copy of the source drive.
5791 */
5792 for (i = 0; i < num_stripes; i++) {
5793 if (bbio->stripes[i].dev->devid == srcdev_devid) {
5794 /*
5795 * In case of DUP, in order to keep it simple,
5796 * only add the mirror with the lowest physical
5797 * address
5798 */
5799 if (found &&
5800 physical_of_found <=
5801 bbio->stripes[i].physical)
5802 continue;
5803 index_srcdev = i;
5804 found = 1;
5805 physical_of_found = bbio->stripes[i].physical;
5806 }
5807 }
5808 if (found) {
5809 struct btrfs_bio_stripe *tgtdev_stripe =
5810 bbio->stripes + num_stripes;
5811
5812 tgtdev_stripe->physical = physical_of_found;
5813 tgtdev_stripe->length =
5814 bbio->stripes[index_srcdev].length;
5815 tgtdev_stripe->dev = dev_replace->tgtdev;
5816 bbio->tgtdev_map[index_srcdev] = num_stripes;
5817
5818 tgtdev_indexes++;
5819 num_stripes++;
5820 }
5821 }
5822
5823 *num_stripes_ret = num_stripes;
5824 *max_errors_ret = max_errors;
5825 bbio->num_tgtdevs = tgtdev_indexes;
5826 *bbio_ret = bbio;
5827 }
5828
5829 static bool need_full_stripe(enum btrfs_map_op op)
5830 {
5831 return (op == BTRFS_MAP_WRITE || op == BTRFS_MAP_GET_READ_MIRRORS);
5832 }
5833
5834 static int __btrfs_map_block(struct btrfs_fs_info *fs_info,
5835 enum btrfs_map_op op,
5836 u64 logical, u64 *length,
5837 struct btrfs_bio **bbio_ret,
5838 int mirror_num, int need_raid_map)
5839 {
5840 struct extent_map *em;
5841 struct map_lookup *map;
5842 u64 offset;
5843 u64 stripe_offset;
5844 u64 stripe_nr;
5845 u64 stripe_len;
5846 u32 stripe_index;
5847 int i;
5848 int ret = 0;
5849 int num_stripes;
5850 int max_errors = 0;
5851 int tgtdev_indexes = 0;
5852 struct btrfs_bio *bbio = NULL;
5853 struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
5854 int dev_replace_is_ongoing = 0;
5855 int num_alloc_stripes;
5856 int patch_the_first_stripe_for_dev_replace = 0;
5857 u64 physical_to_patch_in_first_stripe = 0;
5858 u64 raid56_full_stripe_start = (u64)-1;
5859
5860 if (op == BTRFS_MAP_DISCARD)
5861 return __btrfs_map_block_for_discard(fs_info, logical,
5862 *length, bbio_ret);
5863
5864 em = btrfs_get_chunk_map(fs_info, logical, *length);
5865 if (IS_ERR(em))
5866 return PTR_ERR(em);
5867
5868 map = em->map_lookup;
5869 offset = logical - em->start;
5870
5871 stripe_len = map->stripe_len;
5872 stripe_nr = offset;
5873 /*
5874 * stripe_nr counts the total number of stripes we have to stride
5875 * to get to this block
5876 */
5877 stripe_nr = div64_u64(stripe_nr, stripe_len);
5878
5879 stripe_offset = stripe_nr * stripe_len;
5880 if (offset < stripe_offset) {
5881 btrfs_crit(fs_info,
5882 "stripe math has gone wrong, stripe_offset=%llu, offset=%llu, start=%llu, logical=%llu, stripe_len=%llu",
5883 stripe_offset, offset, em->start, logical,
5884 stripe_len);
5885 free_extent_map(em);
5886 return -EINVAL;
5887 }
5888
5889 /* stripe_offset is the offset of this block in its stripe*/
5890 stripe_offset = offset - stripe_offset;
5891
5892 /* if we're here for raid56, we need to know the stripe aligned start */
5893 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5894 unsigned long full_stripe_len = stripe_len * nr_data_stripes(map);
5895 raid56_full_stripe_start = offset;
5896
5897 /* allow a write of a full stripe, but make sure we don't
5898 * allow straddling of stripes
5899 */
5900 raid56_full_stripe_start = div64_u64(raid56_full_stripe_start,
5901 full_stripe_len);
5902 raid56_full_stripe_start *= full_stripe_len;
5903 }
5904
5905 if (map->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
5906 u64 max_len;
5907 /* For writes to RAID[56], allow a full stripeset across all disks.
5908 For other RAID types and for RAID[56] reads, just allow a single
5909 stripe (on a single disk). */
5910 if ((map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) &&
5911 (op == BTRFS_MAP_WRITE)) {
5912 max_len = stripe_len * nr_data_stripes(map) -
5913 (offset - raid56_full_stripe_start);
5914 } else {
5915 /* we limit the length of each bio to what fits in a stripe */
5916 max_len = stripe_len - stripe_offset;
5917 }
5918 *length = min_t(u64, em->len - offset, max_len);
5919 } else {
5920 *length = em->len - offset;
5921 }
5922
5923 /* This is for when we're called from btrfs_merge_bio_hook() and all
5924 it cares about is the length */
5925 if (!bbio_ret)
5926 goto out;
5927
5928 btrfs_dev_replace_read_lock(dev_replace);
5929 dev_replace_is_ongoing = btrfs_dev_replace_is_ongoing(dev_replace);
5930 if (!dev_replace_is_ongoing)
5931 btrfs_dev_replace_read_unlock(dev_replace);
5932 else
5933 btrfs_dev_replace_set_lock_blocking(dev_replace);
5934
5935 if (dev_replace_is_ongoing && mirror_num == map->num_stripes + 1 &&
5936 !need_full_stripe(op) && dev_replace->tgtdev != NULL) {
5937 ret = get_extra_mirror_from_replace(fs_info, logical, *length,
5938 dev_replace->srcdev->devid,
5939 &mirror_num,
5940 &physical_to_patch_in_first_stripe);
5941 if (ret)
5942 goto out;
5943 else
5944 patch_the_first_stripe_for_dev_replace = 1;
5945 } else if (mirror_num > map->num_stripes) {
5946 mirror_num = 0;
5947 }
5948
5949 num_stripes = 1;
5950 stripe_index = 0;
5951 if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
5952 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
5953 &stripe_index);
5954 if (!need_full_stripe(op))
5955 mirror_num = 1;
5956 } else if (map->type & BTRFS_BLOCK_GROUP_RAID1) {
5957 if (need_full_stripe(op))
5958 num_stripes = map->num_stripes;
5959 else if (mirror_num)
5960 stripe_index = mirror_num - 1;
5961 else {
5962 stripe_index = find_live_mirror(fs_info, map, 0,
5963 dev_replace_is_ongoing);
5964 mirror_num = stripe_index + 1;
5965 }
5966
5967 } else if (map->type & BTRFS_BLOCK_GROUP_DUP) {
5968 if (need_full_stripe(op)) {
5969 num_stripes = map->num_stripes;
5970 } else if (mirror_num) {
5971 stripe_index = mirror_num - 1;
5972 } else {
5973 mirror_num = 1;
5974 }
5975
5976 } else if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
5977 u32 factor = map->num_stripes / map->sub_stripes;
5978
5979 stripe_nr = div_u64_rem(stripe_nr, factor, &stripe_index);
5980 stripe_index *= map->sub_stripes;
5981
5982 if (need_full_stripe(op))
5983 num_stripes = map->sub_stripes;
5984 else if (mirror_num)
5985 stripe_index += mirror_num - 1;
5986 else {
5987 int old_stripe_index = stripe_index;
5988 stripe_index = find_live_mirror(fs_info, map,
5989 stripe_index,
5990 dev_replace_is_ongoing);
5991 mirror_num = stripe_index - old_stripe_index + 1;
5992 }
5993
5994 } else if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5995 if (need_raid_map && (need_full_stripe(op) || mirror_num > 1)) {
5996 /* push stripe_nr back to the start of the full stripe */
5997 stripe_nr = div64_u64(raid56_full_stripe_start,
5998 stripe_len * nr_data_stripes(map));
5999
6000 /* RAID[56] write or recovery. Return all stripes */
6001 num_stripes = map->num_stripes;
6002 max_errors = nr_parity_stripes(map);
6003
6004 *length = map->stripe_len;
6005 stripe_index = 0;
6006 stripe_offset = 0;
6007 } else {
6008 /*
6009 * Mirror #0 or #1 means the original data block.
6010 * Mirror #2 is RAID5 parity block.
6011 * Mirror #3 is RAID6 Q block.
6012 */
6013 stripe_nr = div_u64_rem(stripe_nr,
6014 nr_data_stripes(map), &stripe_index);
6015 if (mirror_num > 1)
6016 stripe_index = nr_data_stripes(map) +
6017 mirror_num - 2;
6018
6019 /* We distribute the parity blocks across stripes */
6020 div_u64_rem(stripe_nr + stripe_index, map->num_stripes,
6021 &stripe_index);
6022 if (!need_full_stripe(op) && mirror_num <= 1)
6023 mirror_num = 1;
6024 }
6025 } else {
6026 /*
6027 * after this, stripe_nr is the number of stripes on this
6028 * device we have to walk to find the data, and stripe_index is
6029 * the number of our device in the stripe array
6030 */
6031 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
6032 &stripe_index);
6033 mirror_num = stripe_index + 1;
6034 }
6035 if (stripe_index >= map->num_stripes) {
6036 btrfs_crit(fs_info,
6037 "stripe index math went horribly wrong, got stripe_index=%u, num_stripes=%u",
6038 stripe_index, map->num_stripes);
6039 ret = -EINVAL;
6040 goto out;
6041 }
6042
6043 num_alloc_stripes = num_stripes;
6044 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL) {
6045 if (op == BTRFS_MAP_WRITE)
6046 num_alloc_stripes <<= 1;
6047 if (op == BTRFS_MAP_GET_READ_MIRRORS)
6048 num_alloc_stripes++;
6049 tgtdev_indexes = num_stripes;
6050 }
6051
6052 bbio = alloc_btrfs_bio(num_alloc_stripes, tgtdev_indexes);
6053 if (!bbio) {
6054 ret = -ENOMEM;
6055 goto out;
6056 }
6057 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL)
6058 bbio->tgtdev_map = (int *)(bbio->stripes + num_alloc_stripes);
6059
6060 /* build raid_map */
6061 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK && need_raid_map &&
6062 (need_full_stripe(op) || mirror_num > 1)) {
6063 u64 tmp;
6064 unsigned rot;
6065
6066 bbio->raid_map = (u64 *)((void *)bbio->stripes +
6067 sizeof(struct btrfs_bio_stripe) *
6068 num_alloc_stripes +
6069 sizeof(int) * tgtdev_indexes);
6070
6071 /* Work out the disk rotation on this stripe-set */
6072 div_u64_rem(stripe_nr, num_stripes, &rot);
6073
6074 /* Fill in the logical address of each stripe */
6075 tmp = stripe_nr * nr_data_stripes(map);
6076 for (i = 0; i < nr_data_stripes(map); i++)
6077 bbio->raid_map[(i+rot) % num_stripes] =
6078 em->start + (tmp + i) * map->stripe_len;
6079
6080 bbio->raid_map[(i+rot) % map->num_stripes] = RAID5_P_STRIPE;
6081 if (map->type & BTRFS_BLOCK_GROUP_RAID6)
6082 bbio->raid_map[(i+rot+1) % num_stripes] =
6083 RAID6_Q_STRIPE;
6084 }
6085
6086
6087 for (i = 0; i < num_stripes; i++) {
6088 bbio->stripes[i].physical =
6089 map->stripes[stripe_index].physical +
6090 stripe_offset +
6091 stripe_nr * map->stripe_len;
6092 bbio->stripes[i].dev =
6093 map->stripes[stripe_index].dev;
6094 stripe_index++;
6095 }
6096
6097 if (need_full_stripe(op))
6098 max_errors = btrfs_chunk_max_errors(map);
6099
6100 if (bbio->raid_map)
6101 sort_parity_stripes(bbio, num_stripes);
6102
6103 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL &&
6104 need_full_stripe(op)) {
6105 handle_ops_on_dev_replace(op, &bbio, dev_replace, &num_stripes,
6106 &max_errors);
6107 }
6108
6109 *bbio_ret = bbio;
6110 bbio->map_type = map->type;
6111 bbio->num_stripes = num_stripes;
6112 bbio->max_errors = max_errors;
6113 bbio->mirror_num = mirror_num;
6114
6115 /*
6116 * this is the case that REQ_READ && dev_replace_is_ongoing &&
6117 * mirror_num == num_stripes + 1 && dev_replace target drive is
6118 * available as a mirror
6119 */
6120 if (patch_the_first_stripe_for_dev_replace && num_stripes > 0) {
6121 WARN_ON(num_stripes > 1);
6122 bbio->stripes[0].dev = dev_replace->tgtdev;
6123 bbio->stripes[0].physical = physical_to_patch_in_first_stripe;
6124 bbio->mirror_num = map->num_stripes + 1;
6125 }
6126 out:
6127 if (dev_replace_is_ongoing) {
6128 ASSERT(atomic_read(&dev_replace->blocking_readers) > 0);
6129 btrfs_dev_replace_read_lock(dev_replace);
6130 /* Barrier implied by atomic_dec_and_test */
6131 if (atomic_dec_and_test(&dev_replace->blocking_readers))
6132 cond_wake_up_nomb(&dev_replace->read_lock_wq);
6133 btrfs_dev_replace_read_unlock(dev_replace);
6134 }
6135 free_extent_map(em);
6136 return ret;
6137 }
6138
6139 int btrfs_map_block(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
6140 u64 logical, u64 *length,
6141 struct btrfs_bio **bbio_ret, int mirror_num)
6142 {
6143 return __btrfs_map_block(fs_info, op, logical, length, bbio_ret,
6144 mirror_num, 0);
6145 }
6146
6147 /* For Scrub/replace */
6148 int btrfs_map_sblock(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
6149 u64 logical, u64 *length,
6150 struct btrfs_bio **bbio_ret)
6151 {
6152 return __btrfs_map_block(fs_info, op, logical, length, bbio_ret, 0, 1);
6153 }
6154
6155 int btrfs_rmap_block(struct btrfs_fs_info *fs_info, u64 chunk_start,
6156 u64 physical, u64 **logical, int *naddrs, int *stripe_len)
6157 {
6158 struct extent_map *em;
6159 struct map_lookup *map;
6160 u64 *buf;
6161 u64 bytenr;
6162 u64 length;
6163 u64 stripe_nr;
6164 u64 rmap_len;
6165 int i, j, nr = 0;
6166
6167 em = btrfs_get_chunk_map(fs_info, chunk_start, 1);
6168 if (IS_ERR(em))
6169 return -EIO;
6170
6171 map = em->map_lookup;
6172 length = em->len;
6173 rmap_len = map->stripe_len;
6174
6175 if (map->type & BTRFS_BLOCK_GROUP_RAID10)
6176 length = div_u64(length, map->num_stripes / map->sub_stripes);
6177 else if (map->type & BTRFS_BLOCK_GROUP_RAID0)
6178 length = div_u64(length, map->num_stripes);
6179 else if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
6180 length = div_u64(length, nr_data_stripes(map));
6181 rmap_len = map->stripe_len * nr_data_stripes(map);
6182 }
6183
6184 buf = kcalloc(map->num_stripes, sizeof(u64), GFP_NOFS);
6185 BUG_ON(!buf); /* -ENOMEM */
6186
6187 for (i = 0; i < map->num_stripes; i++) {
6188 if (map->stripes[i].physical > physical ||
6189 map->stripes[i].physical + length <= physical)
6190 continue;
6191
6192 stripe_nr = physical - map->stripes[i].physical;
6193 stripe_nr = div64_u64(stripe_nr, map->stripe_len);
6194
6195 if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
6196 stripe_nr = stripe_nr * map->num_stripes + i;
6197 stripe_nr = div_u64(stripe_nr, map->sub_stripes);
6198 } else if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
6199 stripe_nr = stripe_nr * map->num_stripes + i;
6200 } /* else if RAID[56], multiply by nr_data_stripes().
6201 * Alternatively, just use rmap_len below instead of
6202 * map->stripe_len */
6203
6204 bytenr = chunk_start + stripe_nr * rmap_len;
6205 WARN_ON(nr >= map->num_stripes);
6206 for (j = 0; j < nr; j++) {
6207 if (buf[j] == bytenr)
6208 break;
6209 }
6210 if (j == nr) {
6211 WARN_ON(nr >= map->num_stripes);
6212 buf[nr++] = bytenr;
6213 }
6214 }
6215
6216 *logical = buf;
6217 *naddrs = nr;
6218 *stripe_len = rmap_len;
6219
6220 free_extent_map(em);
6221 return 0;
6222 }
6223
6224 static inline void btrfs_end_bbio(struct btrfs_bio *bbio, struct bio *bio)
6225 {
6226 bio->bi_private = bbio->private;
6227 bio->bi_end_io = bbio->end_io;
6228 bio_endio(bio);
6229
6230 btrfs_put_bbio(bbio);
6231 }
6232
6233 static void btrfs_end_bio(struct bio *bio)
6234 {
6235 struct btrfs_bio *bbio = bio->bi_private;
6236 int is_orig_bio = 0;
6237
6238 if (bio->bi_status) {
6239 atomic_inc(&bbio->error);
6240 if (bio->bi_status == BLK_STS_IOERR ||
6241 bio->bi_status == BLK_STS_TARGET) {
6242 unsigned int stripe_index =
6243 btrfs_io_bio(bio)->stripe_index;
6244 struct btrfs_device *dev;
6245
6246 BUG_ON(stripe_index >= bbio->num_stripes);
6247 dev = bbio->stripes[stripe_index].dev;
6248 if (dev->bdev) {
6249 if (bio_op(bio) == REQ_OP_WRITE)
6250 btrfs_dev_stat_inc_and_print(dev,
6251 BTRFS_DEV_STAT_WRITE_ERRS);
6252 else
6253 btrfs_dev_stat_inc_and_print(dev,
6254 BTRFS_DEV_STAT_READ_ERRS);
6255 if (bio->bi_opf & REQ_PREFLUSH)
6256 btrfs_dev_stat_inc_and_print(dev,
6257 BTRFS_DEV_STAT_FLUSH_ERRS);
6258 }
6259 }
6260 }
6261
6262 if (bio == bbio->orig_bio)
6263 is_orig_bio = 1;
6264
6265 btrfs_bio_counter_dec(bbio->fs_info);
6266
6267 if (atomic_dec_and_test(&bbio->stripes_pending)) {
6268 if (!is_orig_bio) {
6269 bio_put(bio);
6270 bio = bbio->orig_bio;
6271 }
6272
6273 btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
6274 /* only send an error to the higher layers if it is
6275 * beyond the tolerance of the btrfs bio
6276 */
6277 if (atomic_read(&bbio->error) > bbio->max_errors) {
6278 bio->bi_status = BLK_STS_IOERR;
6279 } else {
6280 /*
6281 * this bio is actually up to date, we didn't
6282 * go over the max number of errors
6283 */
6284 bio->bi_status = BLK_STS_OK;
6285 }
6286
6287 btrfs_end_bbio(bbio, bio);
6288 } else if (!is_orig_bio) {
6289 bio_put(bio);
6290 }
6291 }
6292
6293 /*
6294 * see run_scheduled_bios for a description of why bios are collected for
6295 * async submit.
6296 *
6297 * This will add one bio to the pending list for a device and make sure
6298 * the work struct is scheduled.
6299 */
6300 static noinline void btrfs_schedule_bio(struct btrfs_device *device,
6301 struct bio *bio)
6302 {
6303 struct btrfs_fs_info *fs_info = device->fs_info;
6304 int should_queue = 1;
6305 struct btrfs_pending_bios *pending_bios;
6306
6307 /* don't bother with additional async steps for reads, right now */
6308 if (bio_op(bio) == REQ_OP_READ) {
6309 btrfsic_submit_bio(bio);
6310 return;
6311 }
6312
6313 WARN_ON(bio->bi_next);
6314 bio->bi_next = NULL;
6315
6316 spin_lock(&device->io_lock);
6317 if (op_is_sync(bio->bi_opf))
6318 pending_bios = &device->pending_sync_bios;
6319 else
6320 pending_bios = &device->pending_bios;
6321
6322 if (pending_bios->tail)
6323 pending_bios->tail->bi_next = bio;
6324
6325 pending_bios->tail = bio;
6326 if (!pending_bios->head)
6327 pending_bios->head = bio;
6328 if (device->running_pending)
6329 should_queue = 0;
6330
6331 spin_unlock(&device->io_lock);
6332
6333 if (should_queue)
6334 btrfs_queue_work(fs_info->submit_workers, &device->work);
6335 }
6336
6337 static void submit_stripe_bio(struct btrfs_bio *bbio, struct bio *bio,
6338 u64 physical, int dev_nr, int async)
6339 {
6340 struct btrfs_device *dev = bbio->stripes[dev_nr].dev;
6341 struct btrfs_fs_info *fs_info = bbio->fs_info;
6342
6343 bio->bi_private = bbio;
6344 btrfs_io_bio(bio)->stripe_index = dev_nr;
6345 bio->bi_end_io = btrfs_end_bio;
6346 bio->bi_iter.bi_sector = physical >> 9;
6347 btrfs_debug_in_rcu(fs_info,
6348 "btrfs_map_bio: rw %d 0x%x, sector=%llu, dev=%lu (%s id %llu), size=%u",
6349 bio_op(bio), bio->bi_opf, (u64)bio->bi_iter.bi_sector,
6350 (u_long)dev->bdev->bd_dev, rcu_str_deref(dev->name), dev->devid,
6351 bio->bi_iter.bi_size);
6352 bio_set_dev(bio, dev->bdev);
6353
6354 btrfs_bio_counter_inc_noblocked(fs_info);
6355
6356 if (async)
6357 btrfs_schedule_bio(dev, bio);
6358 else
6359 btrfsic_submit_bio(bio);
6360 }
6361
6362 static void bbio_error(struct btrfs_bio *bbio, struct bio *bio, u64 logical)
6363 {
6364 atomic_inc(&bbio->error);
6365 if (atomic_dec_and_test(&bbio->stripes_pending)) {
6366 /* Should be the original bio. */
6367 WARN_ON(bio != bbio->orig_bio);
6368
6369 btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
6370 bio->bi_iter.bi_sector = logical >> 9;
6371 if (atomic_read(&bbio->error) > bbio->max_errors)
6372 bio->bi_status = BLK_STS_IOERR;
6373 else
6374 bio->bi_status = BLK_STS_OK;
6375 btrfs_end_bbio(bbio, bio);
6376 }
6377 }
6378
6379 blk_status_t btrfs_map_bio(struct btrfs_fs_info *fs_info, struct bio *bio,
6380 int mirror_num, int async_submit)
6381 {
6382 struct btrfs_device *dev;
6383 struct bio *first_bio = bio;
6384 u64 logical = (u64)bio->bi_iter.bi_sector << 9;
6385 u64 length = 0;
6386 u64 map_length;
6387 int ret;
6388 int dev_nr;
6389 int total_devs;
6390 struct btrfs_bio *bbio = NULL;
6391
6392 length = bio->bi_iter.bi_size;
6393 map_length = length;
6394
6395 btrfs_bio_counter_inc_blocked(fs_info);
6396 ret = __btrfs_map_block(fs_info, btrfs_op(bio), logical,
6397 &map_length, &bbio, mirror_num, 1);
6398 if (ret) {
6399 btrfs_bio_counter_dec(fs_info);
6400 return errno_to_blk_status(ret);
6401 }
6402
6403 total_devs = bbio->num_stripes;
6404 bbio->orig_bio = first_bio;
6405 bbio->private = first_bio->bi_private;
6406 bbio->end_io = first_bio->bi_end_io;
6407 bbio->fs_info = fs_info;
6408 atomic_set(&bbio->stripes_pending, bbio->num_stripes);
6409
6410 if ((bbio->map_type & BTRFS_BLOCK_GROUP_RAID56_MASK) &&
6411 ((bio_op(bio) == REQ_OP_WRITE) || (mirror_num > 1))) {
6412 /* In this case, map_length has been set to the length of
6413 a single stripe; not the whole write */
6414 if (bio_op(bio) == REQ_OP_WRITE) {
6415 ret = raid56_parity_write(fs_info, bio, bbio,
6416 map_length);
6417 } else {
6418 ret = raid56_parity_recover(fs_info, bio, bbio,
6419 map_length, mirror_num, 1);
6420 }
6421
6422 btrfs_bio_counter_dec(fs_info);
6423 return errno_to_blk_status(ret);
6424 }
6425
6426 if (map_length < length) {
6427 btrfs_crit(fs_info,
6428 "mapping failed logical %llu bio len %llu len %llu",
6429 logical, length, map_length);
6430 BUG();
6431 }
6432
6433 for (dev_nr = 0; dev_nr < total_devs; dev_nr++) {
6434 dev = bbio->stripes[dev_nr].dev;
6435 if (!dev || !dev->bdev || test_bit(BTRFS_DEV_STATE_MISSING,
6436 &dev->dev_state) ||
6437 (bio_op(first_bio) == REQ_OP_WRITE &&
6438 !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))) {
6439 bbio_error(bbio, first_bio, logical);
6440 continue;
6441 }
6442
6443 if (dev_nr < total_devs - 1)
6444 bio = btrfs_bio_clone(first_bio);
6445 else
6446 bio = first_bio;
6447
6448 submit_stripe_bio(bbio, bio, bbio->stripes[dev_nr].physical,
6449 dev_nr, async_submit);
6450 }
6451 btrfs_bio_counter_dec(fs_info);
6452 return BLK_STS_OK;
6453 }
6454
6455 struct btrfs_device *btrfs_find_device(struct btrfs_fs_info *fs_info, u64 devid,
6456 u8 *uuid, u8 *fsid)
6457 {
6458 struct btrfs_device *device;
6459 struct btrfs_fs_devices *cur_devices;
6460
6461 cur_devices = fs_info->fs_devices;
6462 while (cur_devices) {
6463 if (!fsid ||
6464 !memcmp(cur_devices->metadata_uuid, fsid, BTRFS_FSID_SIZE)) {
6465 device = find_device(cur_devices, devid, uuid);
6466 if (device)
6467 return device;
6468 }
6469 cur_devices = cur_devices->seed;
6470 }
6471 return NULL;
6472 }
6473
6474 static struct btrfs_device *add_missing_dev(struct btrfs_fs_devices *fs_devices,
6475 u64 devid, u8 *dev_uuid)
6476 {
6477 struct btrfs_device *device;
6478
6479 device = btrfs_alloc_device(NULL, &devid, dev_uuid);
6480 if (IS_ERR(device))
6481 return device;
6482
6483 list_add(&device->dev_list, &fs_devices->devices);
6484 device->fs_devices = fs_devices;
6485 fs_devices->num_devices++;
6486
6487 set_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
6488 fs_devices->missing_devices++;
6489
6490 return device;
6491 }
6492
6493 /**
6494 * btrfs_alloc_device - allocate struct btrfs_device
6495 * @fs_info: used only for generating a new devid, can be NULL if
6496 * devid is provided (i.e. @devid != NULL).
6497 * @devid: a pointer to devid for this device. If NULL a new devid
6498 * is generated.
6499 * @uuid: a pointer to UUID for this device. If NULL a new UUID
6500 * is generated.
6501 *
6502 * Return: a pointer to a new &struct btrfs_device on success; ERR_PTR()
6503 * on error. Returned struct is not linked onto any lists and must be
6504 * destroyed with btrfs_free_device.
6505 */
6506 struct btrfs_device *btrfs_alloc_device(struct btrfs_fs_info *fs_info,
6507 const u64 *devid,
6508 const u8 *uuid)
6509 {
6510 struct btrfs_device *dev;
6511 u64 tmp;
6512
6513 if (WARN_ON(!devid && !fs_info))
6514 return ERR_PTR(-EINVAL);
6515
6516 dev = __alloc_device();
6517 if (IS_ERR(dev))
6518 return dev;
6519
6520 if (devid)
6521 tmp = *devid;
6522 else {
6523 int ret;
6524
6525 ret = find_next_devid(fs_info, &tmp);
6526 if (ret) {
6527 btrfs_free_device(dev);
6528 return ERR_PTR(ret);
6529 }
6530 }
6531 dev->devid = tmp;
6532
6533 if (uuid)
6534 memcpy(dev->uuid, uuid, BTRFS_UUID_SIZE);
6535 else
6536 generate_random_uuid(dev->uuid);
6537
6538 btrfs_init_work(&dev->work, btrfs_submit_helper,
6539 pending_bios_fn, NULL, NULL);
6540
6541 return dev;
6542 }
6543
6544 /* Return -EIO if any error, otherwise return 0. */
6545 static int btrfs_check_chunk_valid(struct btrfs_fs_info *fs_info,
6546 struct extent_buffer *leaf,
6547 struct btrfs_chunk *chunk, u64 logical)
6548 {
6549 u64 length;
6550 u64 stripe_len;
6551 u16 num_stripes;
6552 u16 sub_stripes;
6553 u64 type;
6554 u64 features;
6555 bool mixed = false;
6556
6557 length = btrfs_chunk_length(leaf, chunk);
6558 stripe_len = btrfs_chunk_stripe_len(leaf, chunk);
6559 num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
6560 sub_stripes = btrfs_chunk_sub_stripes(leaf, chunk);
6561 type = btrfs_chunk_type(leaf, chunk);
6562
6563 if (!num_stripes) {
6564 btrfs_err(fs_info, "invalid chunk num_stripes: %u",
6565 num_stripes);
6566 return -EIO;
6567 }
6568 if (!IS_ALIGNED(logical, fs_info->sectorsize)) {
6569 btrfs_err(fs_info, "invalid chunk logical %llu", logical);
6570 return -EIO;
6571 }
6572 if (btrfs_chunk_sector_size(leaf, chunk) != fs_info->sectorsize) {
6573 btrfs_err(fs_info, "invalid chunk sectorsize %u",
6574 btrfs_chunk_sector_size(leaf, chunk));
6575 return -EIO;
6576 }
6577 if (!length || !IS_ALIGNED(length, fs_info->sectorsize)) {
6578 btrfs_err(fs_info, "invalid chunk length %llu", length);
6579 return -EIO;
6580 }
6581 if (!is_power_of_2(stripe_len) || stripe_len != BTRFS_STRIPE_LEN) {
6582 btrfs_err(fs_info, "invalid chunk stripe length: %llu",
6583 stripe_len);
6584 return -EIO;
6585 }
6586 if (~(BTRFS_BLOCK_GROUP_TYPE_MASK | BTRFS_BLOCK_GROUP_PROFILE_MASK) &
6587 type) {
6588 btrfs_err(fs_info, "unrecognized chunk type: %llu",
6589 ~(BTRFS_BLOCK_GROUP_TYPE_MASK |
6590 BTRFS_BLOCK_GROUP_PROFILE_MASK) &
6591 btrfs_chunk_type(leaf, chunk));
6592 return -EIO;
6593 }
6594
6595 if ((type & BTRFS_BLOCK_GROUP_TYPE_MASK) == 0) {
6596 btrfs_err(fs_info, "missing chunk type flag: 0x%llx", type);
6597 return -EIO;
6598 }
6599
6600 if ((type & BTRFS_BLOCK_GROUP_SYSTEM) &&
6601 (type & (BTRFS_BLOCK_GROUP_METADATA | BTRFS_BLOCK_GROUP_DATA))) {
6602 btrfs_err(fs_info,
6603 "system chunk with data or metadata type: 0x%llx", type);
6604 return -EIO;
6605 }
6606
6607 features = btrfs_super_incompat_flags(fs_info->super_copy);
6608 if (features & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
6609 mixed = true;
6610
6611 if (!mixed) {
6612 if ((type & BTRFS_BLOCK_GROUP_METADATA) &&
6613 (type & BTRFS_BLOCK_GROUP_DATA)) {
6614 btrfs_err(fs_info,
6615 "mixed chunk type in non-mixed mode: 0x%llx", type);
6616 return -EIO;
6617 }
6618 }
6619
6620 if ((type & BTRFS_BLOCK_GROUP_RAID10 && sub_stripes != 2) ||
6621 (type & BTRFS_BLOCK_GROUP_RAID1 && num_stripes < 1) ||
6622 (type & BTRFS_BLOCK_GROUP_RAID5 && num_stripes < 2) ||
6623 (type & BTRFS_BLOCK_GROUP_RAID6 && num_stripes < 3) ||
6624 (type & BTRFS_BLOCK_GROUP_DUP && num_stripes > 2) ||
6625 ((type & BTRFS_BLOCK_GROUP_PROFILE_MASK) == 0 &&
6626 num_stripes != 1)) {
6627 btrfs_err(fs_info,
6628 "invalid num_stripes:sub_stripes %u:%u for profile %llu",
6629 num_stripes, sub_stripes,
6630 type & BTRFS_BLOCK_GROUP_PROFILE_MASK);
6631 return -EIO;
6632 }
6633
6634 return 0;
6635 }
6636
6637 static void btrfs_report_missing_device(struct btrfs_fs_info *fs_info,
6638 u64 devid, u8 *uuid, bool error)
6639 {
6640 if (error)
6641 btrfs_err_rl(fs_info, "devid %llu uuid %pU is missing",
6642 devid, uuid);
6643 else
6644 btrfs_warn_rl(fs_info, "devid %llu uuid %pU is missing",
6645 devid, uuid);
6646 }
6647
6648 static int read_one_chunk(struct btrfs_fs_info *fs_info, struct btrfs_key *key,
6649 struct extent_buffer *leaf,
6650 struct btrfs_chunk *chunk)
6651 {
6652 struct btrfs_mapping_tree *map_tree = &fs_info->mapping_tree;
6653 struct map_lookup *map;
6654 struct extent_map *em;
6655 u64 logical;
6656 u64 length;
6657 u64 devid;
6658 u8 uuid[BTRFS_UUID_SIZE];
6659 int num_stripes;
6660 int ret;
6661 int i;
6662
6663 logical = key->offset;
6664 length = btrfs_chunk_length(leaf, chunk);
6665 num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
6666
6667 ret = btrfs_check_chunk_valid(fs_info, leaf, chunk, logical);
6668 if (ret)
6669 return ret;
6670
6671 read_lock(&map_tree->map_tree.lock);
6672 em = lookup_extent_mapping(&map_tree->map_tree, logical, 1);
6673 read_unlock(&map_tree->map_tree.lock);
6674
6675 /* already mapped? */
6676 if (em && em->start <= logical && em->start + em->len > logical) {
6677 free_extent_map(em);
6678 return 0;
6679 } else if (em) {
6680 free_extent_map(em);
6681 }
6682
6683 em = alloc_extent_map();
6684 if (!em)
6685 return -ENOMEM;
6686 map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
6687 if (!map) {
6688 free_extent_map(em);
6689 return -ENOMEM;
6690 }
6691
6692 set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
6693 em->map_lookup = map;
6694 em->start = logical;
6695 em->len = length;
6696 em->orig_start = 0;
6697 em->block_start = 0;
6698 em->block_len = em->len;
6699
6700 map->num_stripes = num_stripes;
6701 map->io_width = btrfs_chunk_io_width(leaf, chunk);
6702 map->io_align = btrfs_chunk_io_align(leaf, chunk);
6703 map->stripe_len = btrfs_chunk_stripe_len(leaf, chunk);
6704 map->type = btrfs_chunk_type(leaf, chunk);
6705 map->sub_stripes = btrfs_chunk_sub_stripes(leaf, chunk);
6706 map->verified_stripes = 0;
6707 for (i = 0; i < num_stripes; i++) {
6708 map->stripes[i].physical =
6709 btrfs_stripe_offset_nr(leaf, chunk, i);
6710 devid = btrfs_stripe_devid_nr(leaf, chunk, i);
6711 read_extent_buffer(leaf, uuid, (unsigned long)
6712 btrfs_stripe_dev_uuid_nr(chunk, i),
6713 BTRFS_UUID_SIZE);
6714 map->stripes[i].dev = btrfs_find_device(fs_info, devid,
6715 uuid, NULL);
6716 if (!map->stripes[i].dev &&
6717 !btrfs_test_opt(fs_info, DEGRADED)) {
6718 free_extent_map(em);
6719 btrfs_report_missing_device(fs_info, devid, uuid, true);
6720 return -ENOENT;
6721 }
6722 if (!map->stripes[i].dev) {
6723 map->stripes[i].dev =
6724 add_missing_dev(fs_info->fs_devices, devid,
6725 uuid);
6726 if (IS_ERR(map->stripes[i].dev)) {
6727 free_extent_map(em);
6728 btrfs_err(fs_info,
6729 "failed to init missing dev %llu: %ld",
6730 devid, PTR_ERR(map->stripes[i].dev));
6731 return PTR_ERR(map->stripes[i].dev);
6732 }
6733 btrfs_report_missing_device(fs_info, devid, uuid, false);
6734 }
6735 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
6736 &(map->stripes[i].dev->dev_state));
6737
6738 }
6739
6740 write_lock(&map_tree->map_tree.lock);
6741 ret = add_extent_mapping(&map_tree->map_tree, em, 0);
6742 write_unlock(&map_tree->map_tree.lock);
6743 if (ret < 0) {
6744 btrfs_err(fs_info,
6745 "failed to add chunk map, start=%llu len=%llu: %d",
6746 em->start, em->len, ret);
6747 }
6748 free_extent_map(em);
6749
6750 return ret;
6751 }
6752
6753 static void fill_device_from_item(struct extent_buffer *leaf,
6754 struct btrfs_dev_item *dev_item,
6755 struct btrfs_device *device)
6756 {
6757 unsigned long ptr;
6758
6759 device->devid = btrfs_device_id(leaf, dev_item);
6760 device->disk_total_bytes = btrfs_device_total_bytes(leaf, dev_item);
6761 device->total_bytes = device->disk_total_bytes;
6762 device->commit_total_bytes = device->disk_total_bytes;
6763 device->bytes_used = btrfs_device_bytes_used(leaf, dev_item);
6764 device->commit_bytes_used = device->bytes_used;
6765 device->type = btrfs_device_type(leaf, dev_item);
6766 device->io_align = btrfs_device_io_align(leaf, dev_item);
6767 device->io_width = btrfs_device_io_width(leaf, dev_item);
6768 device->sector_size = btrfs_device_sector_size(leaf, dev_item);
6769 WARN_ON(device->devid == BTRFS_DEV_REPLACE_DEVID);
6770 clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
6771
6772 ptr = btrfs_device_uuid(dev_item);
6773 read_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
6774 }
6775
6776 static struct btrfs_fs_devices *open_seed_devices(struct btrfs_fs_info *fs_info,
6777 u8 *fsid)
6778 {
6779 struct btrfs_fs_devices *fs_devices;
6780 int ret;
6781
6782 lockdep_assert_held(&uuid_mutex);
6783 ASSERT(fsid);
6784
6785 fs_devices = fs_info->fs_devices->seed;
6786 while (fs_devices) {
6787 if (!memcmp(fs_devices->fsid, fsid, BTRFS_FSID_SIZE))
6788 return fs_devices;
6789
6790 fs_devices = fs_devices->seed;
6791 }
6792
6793 fs_devices = find_fsid(fsid, NULL);
6794 if (!fs_devices) {
6795 if (!btrfs_test_opt(fs_info, DEGRADED))
6796 return ERR_PTR(-ENOENT);
6797
6798 fs_devices = alloc_fs_devices(fsid, NULL);
6799 if (IS_ERR(fs_devices))
6800 return fs_devices;
6801
6802 fs_devices->seeding = 1;
6803 fs_devices->opened = 1;
6804 return fs_devices;
6805 }
6806
6807 fs_devices = clone_fs_devices(fs_devices);
6808 if (IS_ERR(fs_devices))
6809 return fs_devices;
6810
6811 ret = open_fs_devices(fs_devices, FMODE_READ, fs_info->bdev_holder);
6812 if (ret) {
6813 free_fs_devices(fs_devices);
6814 fs_devices = ERR_PTR(ret);
6815 goto out;
6816 }
6817
6818 if (!fs_devices->seeding) {
6819 close_fs_devices(fs_devices);
6820 free_fs_devices(fs_devices);
6821 fs_devices = ERR_PTR(-EINVAL);
6822 goto out;
6823 }
6824
6825 fs_devices->seed = fs_info->fs_devices->seed;
6826 fs_info->fs_devices->seed = fs_devices;
6827 out:
6828 return fs_devices;
6829 }
6830
6831 static int read_one_dev(struct btrfs_fs_info *fs_info,
6832 struct extent_buffer *leaf,
6833 struct btrfs_dev_item *dev_item)
6834 {
6835 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
6836 struct btrfs_device *device;
6837 u64 devid;
6838 int ret;
6839 u8 fs_uuid[BTRFS_FSID_SIZE];
6840 u8 dev_uuid[BTRFS_UUID_SIZE];
6841
6842 devid = btrfs_device_id(leaf, dev_item);
6843 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
6844 BTRFS_UUID_SIZE);
6845 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
6846 BTRFS_FSID_SIZE);
6847
6848 if (memcmp(fs_uuid, fs_devices->metadata_uuid, BTRFS_FSID_SIZE)) {
6849 fs_devices = open_seed_devices(fs_info, fs_uuid);
6850 if (IS_ERR(fs_devices))
6851 return PTR_ERR(fs_devices);
6852 }
6853
6854 device = btrfs_find_device(fs_info, devid, dev_uuid, fs_uuid);
6855 if (!device) {
6856 if (!btrfs_test_opt(fs_info, DEGRADED)) {
6857 btrfs_report_missing_device(fs_info, devid,
6858 dev_uuid, true);
6859 return -ENOENT;
6860 }
6861
6862 device = add_missing_dev(fs_devices, devid, dev_uuid);
6863 if (IS_ERR(device)) {
6864 btrfs_err(fs_info,
6865 "failed to add missing dev %llu: %ld",
6866 devid, PTR_ERR(device));
6867 return PTR_ERR(device);
6868 }
6869 btrfs_report_missing_device(fs_info, devid, dev_uuid, false);
6870 } else {
6871 if (!device->bdev) {
6872 if (!btrfs_test_opt(fs_info, DEGRADED)) {
6873 btrfs_report_missing_device(fs_info,
6874 devid, dev_uuid, true);
6875 return -ENOENT;
6876 }
6877 btrfs_report_missing_device(fs_info, devid,
6878 dev_uuid, false);
6879 }
6880
6881 if (!device->bdev &&
6882 !test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
6883 /*
6884 * this happens when a device that was properly setup
6885 * in the device info lists suddenly goes bad.
6886 * device->bdev is NULL, and so we have to set
6887 * device->missing to one here
6888 */
6889 device->fs_devices->missing_devices++;
6890 set_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
6891 }
6892
6893 /* Move the device to its own fs_devices */
6894 if (device->fs_devices != fs_devices) {
6895 ASSERT(test_bit(BTRFS_DEV_STATE_MISSING,
6896 &device->dev_state));
6897
6898 list_move(&device->dev_list, &fs_devices->devices);
6899 device->fs_devices->num_devices--;
6900 fs_devices->num_devices++;
6901
6902 device->fs_devices->missing_devices--;
6903 fs_devices->missing_devices++;
6904
6905 device->fs_devices = fs_devices;
6906 }
6907 }
6908
6909 if (device->fs_devices != fs_info->fs_devices) {
6910 BUG_ON(test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state));
6911 if (device->generation !=
6912 btrfs_device_generation(leaf, dev_item))
6913 return -EINVAL;
6914 }
6915
6916 fill_device_from_item(leaf, dev_item, device);
6917 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
6918 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
6919 !test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
6920 device->fs_devices->total_rw_bytes += device->total_bytes;
6921 atomic64_add(device->total_bytes - device->bytes_used,
6922 &fs_info->free_chunk_space);
6923 }
6924 ret = 0;
6925 return ret;
6926 }
6927
6928 int btrfs_read_sys_array(struct btrfs_fs_info *fs_info)
6929 {
6930 struct btrfs_root *root = fs_info->tree_root;
6931 struct btrfs_super_block *super_copy = fs_info->super_copy;
6932 struct extent_buffer *sb;
6933 struct btrfs_disk_key *disk_key;
6934 struct btrfs_chunk *chunk;
6935 u8 *array_ptr;
6936 unsigned long sb_array_offset;
6937 int ret = 0;
6938 u32 num_stripes;
6939 u32 array_size;
6940 u32 len = 0;
6941 u32 cur_offset;
6942 u64 type;
6943 struct btrfs_key key;
6944
6945 ASSERT(BTRFS_SUPER_INFO_SIZE <= fs_info->nodesize);
6946 /*
6947 * This will create extent buffer of nodesize, superblock size is
6948 * fixed to BTRFS_SUPER_INFO_SIZE. If nodesize > sb size, this will
6949 * overallocate but we can keep it as-is, only the first page is used.
6950 */
6951 sb = btrfs_find_create_tree_block(fs_info, BTRFS_SUPER_INFO_OFFSET);
6952 if (IS_ERR(sb))
6953 return PTR_ERR(sb);
6954 set_extent_buffer_uptodate(sb);
6955 btrfs_set_buffer_lockdep_class(root->root_key.objectid, sb, 0);
6956 /*
6957 * The sb extent buffer is artificial and just used to read the system array.
6958 * set_extent_buffer_uptodate() call does not properly mark all it's
6959 * pages up-to-date when the page is larger: extent does not cover the
6960 * whole page and consequently check_page_uptodate does not find all
6961 * the page's extents up-to-date (the hole beyond sb),
6962 * write_extent_buffer then triggers a WARN_ON.
6963 *
6964 * Regular short extents go through mark_extent_buffer_dirty/writeback cycle,
6965 * but sb spans only this function. Add an explicit SetPageUptodate call
6966 * to silence the warning eg. on PowerPC 64.
6967 */
6968 if (PAGE_SIZE > BTRFS_SUPER_INFO_SIZE)
6969 SetPageUptodate(sb->pages[0]);
6970
6971 write_extent_buffer(sb, super_copy, 0, BTRFS_SUPER_INFO_SIZE);
6972 array_size = btrfs_super_sys_array_size(super_copy);
6973
6974 array_ptr = super_copy->sys_chunk_array;
6975 sb_array_offset = offsetof(struct btrfs_super_block, sys_chunk_array);
6976 cur_offset = 0;
6977
6978 while (cur_offset < array_size) {
6979 disk_key = (struct btrfs_disk_key *)array_ptr;
6980 len = sizeof(*disk_key);
6981 if (cur_offset + len > array_size)
6982 goto out_short_read;
6983
6984 btrfs_disk_key_to_cpu(&key, disk_key);
6985
6986 array_ptr += len;
6987 sb_array_offset += len;
6988 cur_offset += len;
6989
6990 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
6991 chunk = (struct btrfs_chunk *)sb_array_offset;
6992 /*
6993 * At least one btrfs_chunk with one stripe must be
6994 * present, exact stripe count check comes afterwards
6995 */
6996 len = btrfs_chunk_item_size(1);
6997 if (cur_offset + len > array_size)
6998 goto out_short_read;
6999
7000 num_stripes = btrfs_chunk_num_stripes(sb, chunk);
7001 if (!num_stripes) {
7002 btrfs_err(fs_info,
7003 "invalid number of stripes %u in sys_array at offset %u",
7004 num_stripes, cur_offset);
7005 ret = -EIO;
7006 break;
7007 }
7008
7009 type = btrfs_chunk_type(sb, chunk);
7010 if ((type & BTRFS_BLOCK_GROUP_SYSTEM) == 0) {
7011 btrfs_err(fs_info,
7012 "invalid chunk type %llu in sys_array at offset %u",
7013 type, cur_offset);
7014 ret = -EIO;
7015 break;
7016 }
7017
7018 len = btrfs_chunk_item_size(num_stripes);
7019 if (cur_offset + len > array_size)
7020 goto out_short_read;
7021
7022 ret = read_one_chunk(fs_info, &key, sb, chunk);
7023 if (ret)
7024 break;
7025 } else {
7026 btrfs_err(fs_info,
7027 "unexpected item type %u in sys_array at offset %u",
7028 (u32)key.type, cur_offset);
7029 ret = -EIO;
7030 break;
7031 }
7032 array_ptr += len;
7033 sb_array_offset += len;
7034 cur_offset += len;
7035 }
7036 clear_extent_buffer_uptodate(sb);
7037 free_extent_buffer_stale(sb);
7038 return ret;
7039
7040 out_short_read:
7041 btrfs_err(fs_info, "sys_array too short to read %u bytes at offset %u",
7042 len, cur_offset);
7043 clear_extent_buffer_uptodate(sb);
7044 free_extent_buffer_stale(sb);
7045 return -EIO;
7046 }
7047
7048 /*
7049 * Check if all chunks in the fs are OK for read-write degraded mount
7050 *
7051 * If the @failing_dev is specified, it's accounted as missing.
7052 *
7053 * Return true if all chunks meet the minimal RW mount requirements.
7054 * Return false if any chunk doesn't meet the minimal RW mount requirements.
7055 */
7056 bool btrfs_check_rw_degradable(struct btrfs_fs_info *fs_info,
7057 struct btrfs_device *failing_dev)
7058 {
7059 struct btrfs_mapping_tree *map_tree = &fs_info->mapping_tree;
7060 struct extent_map *em;
7061 u64 next_start = 0;
7062 bool ret = true;
7063
7064 read_lock(&map_tree->map_tree.lock);
7065 em = lookup_extent_mapping(&map_tree->map_tree, 0, (u64)-1);
7066 read_unlock(&map_tree->map_tree.lock);
7067 /* No chunk at all? Return false anyway */
7068 if (!em) {
7069 ret = false;
7070 goto out;
7071 }
7072 while (em) {
7073 struct map_lookup *map;
7074 int missing = 0;
7075 int max_tolerated;
7076 int i;
7077
7078 map = em->map_lookup;
7079 max_tolerated =
7080 btrfs_get_num_tolerated_disk_barrier_failures(
7081 map->type);
7082 for (i = 0; i < map->num_stripes; i++) {
7083 struct btrfs_device *dev = map->stripes[i].dev;
7084
7085 if (!dev || !dev->bdev ||
7086 test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state) ||
7087 dev->last_flush_error)
7088 missing++;
7089 else if (failing_dev && failing_dev == dev)
7090 missing++;
7091 }
7092 if (missing > max_tolerated) {
7093 if (!failing_dev)
7094 btrfs_warn(fs_info,
7095 "chunk %llu missing %d devices, max tolerance is %d for writeable mount",
7096 em->start, missing, max_tolerated);
7097 free_extent_map(em);
7098 ret = false;
7099 goto out;
7100 }
7101 next_start = extent_map_end(em);
7102 free_extent_map(em);
7103
7104 read_lock(&map_tree->map_tree.lock);
7105 em = lookup_extent_mapping(&map_tree->map_tree, next_start,
7106 (u64)(-1) - next_start);
7107 read_unlock(&map_tree->map_tree.lock);
7108 }
7109 out:
7110 return ret;
7111 }
7112
7113 int btrfs_read_chunk_tree(struct btrfs_fs_info *fs_info)
7114 {
7115 struct btrfs_root *root = fs_info->chunk_root;
7116 struct btrfs_path *path;
7117 struct extent_buffer *leaf;
7118 struct btrfs_key key;
7119 struct btrfs_key found_key;
7120 int ret;
7121 int slot;
7122 u64 total_dev = 0;
7123
7124 path = btrfs_alloc_path();
7125 if (!path)
7126 return -ENOMEM;
7127
7128 /*
7129 * uuid_mutex is needed only if we are mounting a sprout FS
7130 * otherwise we don't need it.
7131 */
7132 mutex_lock(&uuid_mutex);
7133 mutex_lock(&fs_info->chunk_mutex);
7134
7135 /*
7136 * Read all device items, and then all the chunk items. All
7137 * device items are found before any chunk item (their object id
7138 * is smaller than the lowest possible object id for a chunk
7139 * item - BTRFS_FIRST_CHUNK_TREE_OBJECTID).
7140 */
7141 key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
7142 key.offset = 0;
7143 key.type = 0;
7144 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
7145 if (ret < 0)
7146 goto error;
7147 while (1) {
7148 leaf = path->nodes[0];
7149 slot = path->slots[0];
7150 if (slot >= btrfs_header_nritems(leaf)) {
7151 ret = btrfs_next_leaf(root, path);
7152 if (ret == 0)
7153 continue;
7154 if (ret < 0)
7155 goto error;
7156 break;
7157 }
7158 btrfs_item_key_to_cpu(leaf, &found_key, slot);
7159 if (found_key.type == BTRFS_DEV_ITEM_KEY) {
7160 struct btrfs_dev_item *dev_item;
7161 dev_item = btrfs_item_ptr(leaf, slot,
7162 struct btrfs_dev_item);
7163 ret = read_one_dev(fs_info, leaf, dev_item);
7164 if (ret)
7165 goto error;
7166 total_dev++;
7167 } else if (found_key.type == BTRFS_CHUNK_ITEM_KEY) {
7168 struct btrfs_chunk *chunk;
7169 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
7170 ret = read_one_chunk(fs_info, &found_key, leaf, chunk);
7171 if (ret)
7172 goto error;
7173 }
7174 path->slots[0]++;
7175 }
7176
7177 /*
7178 * After loading chunk tree, we've got all device information,
7179 * do another round of validation checks.
7180 */
7181 if (total_dev != fs_info->fs_devices->total_devices) {
7182 btrfs_err(fs_info,
7183 "super_num_devices %llu mismatch with num_devices %llu found here",
7184 btrfs_super_num_devices(fs_info->super_copy),
7185 total_dev);
7186 ret = -EINVAL;
7187 goto error;
7188 }
7189 if (btrfs_super_total_bytes(fs_info->super_copy) <
7190 fs_info->fs_devices->total_rw_bytes) {
7191 btrfs_err(fs_info,
7192 "super_total_bytes %llu mismatch with fs_devices total_rw_bytes %llu",
7193 btrfs_super_total_bytes(fs_info->super_copy),
7194 fs_info->fs_devices->total_rw_bytes);
7195 ret = -EINVAL;
7196 goto error;
7197 }
7198 ret = 0;
7199 error:
7200 mutex_unlock(&fs_info->chunk_mutex);
7201 mutex_unlock(&uuid_mutex);
7202
7203 btrfs_free_path(path);
7204 return ret;
7205 }
7206
7207 void btrfs_init_devices_late(struct btrfs_fs_info *fs_info)
7208 {
7209 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7210 struct btrfs_device *device;
7211
7212 while (fs_devices) {
7213 mutex_lock(&fs_devices->device_list_mutex);
7214 list_for_each_entry(device, &fs_devices->devices, dev_list)
7215 device->fs_info = fs_info;
7216 mutex_unlock(&fs_devices->device_list_mutex);
7217
7218 fs_devices = fs_devices->seed;
7219 }
7220 }
7221
7222 static void __btrfs_reset_dev_stats(struct btrfs_device *dev)
7223 {
7224 int i;
7225
7226 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7227 btrfs_dev_stat_reset(dev, i);
7228 }
7229
7230 int btrfs_init_dev_stats(struct btrfs_fs_info *fs_info)
7231 {
7232 struct btrfs_key key;
7233 struct btrfs_key found_key;
7234 struct btrfs_root *dev_root = fs_info->dev_root;
7235 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7236 struct extent_buffer *eb;
7237 int slot;
7238 int ret = 0;
7239 struct btrfs_device *device;
7240 struct btrfs_path *path = NULL;
7241 int i;
7242
7243 path = btrfs_alloc_path();
7244 if (!path) {
7245 ret = -ENOMEM;
7246 goto out;
7247 }
7248
7249 mutex_lock(&fs_devices->device_list_mutex);
7250 list_for_each_entry(device, &fs_devices->devices, dev_list) {
7251 int item_size;
7252 struct btrfs_dev_stats_item *ptr;
7253
7254 key.objectid = BTRFS_DEV_STATS_OBJECTID;
7255 key.type = BTRFS_PERSISTENT_ITEM_KEY;
7256 key.offset = device->devid;
7257 ret = btrfs_search_slot(NULL, dev_root, &key, path, 0, 0);
7258 if (ret) {
7259 __btrfs_reset_dev_stats(device);
7260 device->dev_stats_valid = 1;
7261 btrfs_release_path(path);
7262 continue;
7263 }
7264 slot = path->slots[0];
7265 eb = path->nodes[0];
7266 btrfs_item_key_to_cpu(eb, &found_key, slot);
7267 item_size = btrfs_item_size_nr(eb, slot);
7268
7269 ptr = btrfs_item_ptr(eb, slot,
7270 struct btrfs_dev_stats_item);
7271
7272 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
7273 if (item_size >= (1 + i) * sizeof(__le64))
7274 btrfs_dev_stat_set(device, i,
7275 btrfs_dev_stats_value(eb, ptr, i));
7276 else
7277 btrfs_dev_stat_reset(device, i);
7278 }
7279
7280 device->dev_stats_valid = 1;
7281 btrfs_dev_stat_print_on_load(device);
7282 btrfs_release_path(path);
7283 }
7284 mutex_unlock(&fs_devices->device_list_mutex);
7285
7286 out:
7287 btrfs_free_path(path);
7288 return ret < 0 ? ret : 0;
7289 }
7290
7291 static int update_dev_stat_item(struct btrfs_trans_handle *trans,
7292 struct btrfs_device *device)
7293 {
7294 struct btrfs_fs_info *fs_info = trans->fs_info;
7295 struct btrfs_root *dev_root = fs_info->dev_root;
7296 struct btrfs_path *path;
7297 struct btrfs_key key;
7298 struct extent_buffer *eb;
7299 struct btrfs_dev_stats_item *ptr;
7300 int ret;
7301 int i;
7302
7303 key.objectid = BTRFS_DEV_STATS_OBJECTID;
7304 key.type = BTRFS_PERSISTENT_ITEM_KEY;
7305 key.offset = device->devid;
7306
7307 path = btrfs_alloc_path();
7308 if (!path)
7309 return -ENOMEM;
7310 ret = btrfs_search_slot(trans, dev_root, &key, path, -1, 1);
7311 if (ret < 0) {
7312 btrfs_warn_in_rcu(fs_info,
7313 "error %d while searching for dev_stats item for device %s",
7314 ret, rcu_str_deref(device->name));
7315 goto out;
7316 }
7317
7318 if (ret == 0 &&
7319 btrfs_item_size_nr(path->nodes[0], path->slots[0]) < sizeof(*ptr)) {
7320 /* need to delete old one and insert a new one */
7321 ret = btrfs_del_item(trans, dev_root, path);
7322 if (ret != 0) {
7323 btrfs_warn_in_rcu(fs_info,
7324 "delete too small dev_stats item for device %s failed %d",
7325 rcu_str_deref(device->name), ret);
7326 goto out;
7327 }
7328 ret = 1;
7329 }
7330
7331 if (ret == 1) {
7332 /* need to insert a new item */
7333 btrfs_release_path(path);
7334 ret = btrfs_insert_empty_item(trans, dev_root, path,
7335 &key, sizeof(*ptr));
7336 if (ret < 0) {
7337 btrfs_warn_in_rcu(fs_info,
7338 "insert dev_stats item for device %s failed %d",
7339 rcu_str_deref(device->name), ret);
7340 goto out;
7341 }
7342 }
7343
7344 eb = path->nodes[0];
7345 ptr = btrfs_item_ptr(eb, path->slots[0], struct btrfs_dev_stats_item);
7346 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7347 btrfs_set_dev_stats_value(eb, ptr, i,
7348 btrfs_dev_stat_read(device, i));
7349 btrfs_mark_buffer_dirty(eb);
7350
7351 out:
7352 btrfs_free_path(path);
7353 return ret;
7354 }
7355
7356 /*
7357 * called from commit_transaction. Writes all changed device stats to disk.
7358 */
7359 int btrfs_run_dev_stats(struct btrfs_trans_handle *trans,
7360 struct btrfs_fs_info *fs_info)
7361 {
7362 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7363 struct btrfs_device *device;
7364 int stats_cnt;
7365 int ret = 0;
7366
7367 mutex_lock(&fs_devices->device_list_mutex);
7368 list_for_each_entry(device, &fs_devices->devices, dev_list) {
7369 stats_cnt = atomic_read(&device->dev_stats_ccnt);
7370 if (!device->dev_stats_valid || stats_cnt == 0)
7371 continue;
7372
7373
7374 /*
7375 * There is a LOAD-LOAD control dependency between the value of
7376 * dev_stats_ccnt and updating the on-disk values which requires
7377 * reading the in-memory counters. Such control dependencies
7378 * require explicit read memory barriers.
7379 *
7380 * This memory barriers pairs with smp_mb__before_atomic in
7381 * btrfs_dev_stat_inc/btrfs_dev_stat_set and with the full
7382 * barrier implied by atomic_xchg in
7383 * btrfs_dev_stats_read_and_reset
7384 */
7385 smp_rmb();
7386
7387 ret = update_dev_stat_item(trans, device);
7388 if (!ret)
7389 atomic_sub(stats_cnt, &device->dev_stats_ccnt);
7390 }
7391 mutex_unlock(&fs_devices->device_list_mutex);
7392
7393 return ret;
7394 }
7395
7396 void btrfs_dev_stat_inc_and_print(struct btrfs_device *dev, int index)
7397 {
7398 btrfs_dev_stat_inc(dev, index);
7399 btrfs_dev_stat_print_on_error(dev);
7400 }
7401
7402 static void btrfs_dev_stat_print_on_error(struct btrfs_device *dev)
7403 {
7404 if (!dev->dev_stats_valid)
7405 return;
7406 btrfs_err_rl_in_rcu(dev->fs_info,
7407 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
7408 rcu_str_deref(dev->name),
7409 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
7410 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
7411 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
7412 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
7413 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
7414 }
7415
7416 static void btrfs_dev_stat_print_on_load(struct btrfs_device *dev)
7417 {
7418 int i;
7419
7420 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7421 if (btrfs_dev_stat_read(dev, i) != 0)
7422 break;
7423 if (i == BTRFS_DEV_STAT_VALUES_MAX)
7424 return; /* all values == 0, suppress message */
7425
7426 btrfs_info_in_rcu(dev->fs_info,
7427 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
7428 rcu_str_deref(dev->name),
7429 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
7430 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
7431 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
7432 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
7433 btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
7434 }
7435
7436 int btrfs_get_dev_stats(struct btrfs_fs_info *fs_info,
7437 struct btrfs_ioctl_get_dev_stats *stats)
7438 {
7439 struct btrfs_device *dev;
7440 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7441 int i;
7442
7443 mutex_lock(&fs_devices->device_list_mutex);
7444 dev = btrfs_find_device(fs_info, stats->devid, NULL, NULL);
7445 mutex_unlock(&fs_devices->device_list_mutex);
7446
7447 if (!dev) {
7448 btrfs_warn(fs_info, "get dev_stats failed, device not found");
7449 return -ENODEV;
7450 } else if (!dev->dev_stats_valid) {
7451 btrfs_warn(fs_info, "get dev_stats failed, not yet valid");
7452 return -ENODEV;
7453 } else if (stats->flags & BTRFS_DEV_STATS_RESET) {
7454 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
7455 if (stats->nr_items > i)
7456 stats->values[i] =
7457 btrfs_dev_stat_read_and_reset(dev, i);
7458 else
7459 btrfs_dev_stat_reset(dev, i);
7460 }
7461 } else {
7462 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7463 if (stats->nr_items > i)
7464 stats->values[i] = btrfs_dev_stat_read(dev, i);
7465 }
7466 if (stats->nr_items > BTRFS_DEV_STAT_VALUES_MAX)
7467 stats->nr_items = BTRFS_DEV_STAT_VALUES_MAX;
7468 return 0;
7469 }
7470
7471 void btrfs_scratch_superblocks(struct block_device *bdev, const char *device_path)
7472 {
7473 struct buffer_head *bh;
7474 struct btrfs_super_block *disk_super;
7475 int copy_num;
7476
7477 if (!bdev)
7478 return;
7479
7480 for (copy_num = 0; copy_num < BTRFS_SUPER_MIRROR_MAX;
7481 copy_num++) {
7482
7483 if (btrfs_read_dev_one_super(bdev, copy_num, &bh))
7484 continue;
7485
7486 disk_super = (struct btrfs_super_block *)bh->b_data;
7487
7488 memset(&disk_super->magic, 0, sizeof(disk_super->magic));
7489 set_buffer_dirty(bh);
7490 sync_dirty_buffer(bh);
7491 brelse(bh);
7492 }
7493
7494 /* Notify udev that device has changed */
7495 btrfs_kobject_uevent(bdev, KOBJ_CHANGE);
7496
7497 /* Update ctime/mtime for device path for libblkid */
7498 update_dev_time(device_path);
7499 }
7500
7501 /*
7502 * Update the size of all devices, which is used for writing out the
7503 * super blocks.
7504 */
7505 void btrfs_update_commit_device_size(struct btrfs_fs_info *fs_info)
7506 {
7507 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7508 struct btrfs_device *curr, *next;
7509
7510 if (list_empty(&fs_devices->resized_devices))
7511 return;
7512
7513 mutex_lock(&fs_devices->device_list_mutex);
7514 mutex_lock(&fs_info->chunk_mutex);
7515 list_for_each_entry_safe(curr, next, &fs_devices->resized_devices,
7516 resized_list) {
7517 list_del_init(&curr->resized_list);
7518 curr->commit_total_bytes = curr->disk_total_bytes;
7519 }
7520 mutex_unlock(&fs_info->chunk_mutex);
7521 mutex_unlock(&fs_devices->device_list_mutex);
7522 }
7523
7524 /* Must be invoked during the transaction commit */
7525 void btrfs_update_commit_device_bytes_used(struct btrfs_transaction *trans)
7526 {
7527 struct btrfs_fs_info *fs_info = trans->fs_info;
7528 struct extent_map *em;
7529 struct map_lookup *map;
7530 struct btrfs_device *dev;
7531 int i;
7532
7533 if (list_empty(&trans->pending_chunks))
7534 return;
7535
7536 /* In order to kick the device replace finish process */
7537 mutex_lock(&fs_info->chunk_mutex);
7538 list_for_each_entry(em, &trans->pending_chunks, list) {
7539 map = em->map_lookup;
7540
7541 for (i = 0; i < map->num_stripes; i++) {
7542 dev = map->stripes[i].dev;
7543 dev->commit_bytes_used = dev->bytes_used;
7544 }
7545 }
7546 mutex_unlock(&fs_info->chunk_mutex);
7547 }
7548
7549 void btrfs_set_fs_info_ptr(struct btrfs_fs_info *fs_info)
7550 {
7551 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7552 while (fs_devices) {
7553 fs_devices->fs_info = fs_info;
7554 fs_devices = fs_devices->seed;
7555 }
7556 }
7557
7558 void btrfs_reset_fs_info_ptr(struct btrfs_fs_info *fs_info)
7559 {
7560 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7561 while (fs_devices) {
7562 fs_devices->fs_info = NULL;
7563 fs_devices = fs_devices->seed;
7564 }
7565 }
7566
7567 /*
7568 * Multiplicity factor for simple profiles: DUP, RAID1-like and RAID10.
7569 */
7570 int btrfs_bg_type_to_factor(u64 flags)
7571 {
7572 if (flags & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1 |
7573 BTRFS_BLOCK_GROUP_RAID10))
7574 return 2;
7575 return 1;
7576 }
7577
7578
7579 static u64 calc_stripe_length(u64 type, u64 chunk_len, int num_stripes)
7580 {
7581 int index = btrfs_bg_flags_to_raid_index(type);
7582 int ncopies = btrfs_raid_array[index].ncopies;
7583 int data_stripes;
7584
7585 switch (type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
7586 case BTRFS_BLOCK_GROUP_RAID5:
7587 data_stripes = num_stripes - 1;
7588 break;
7589 case BTRFS_BLOCK_GROUP_RAID6:
7590 data_stripes = num_stripes - 2;
7591 break;
7592 default:
7593 data_stripes = num_stripes / ncopies;
7594 break;
7595 }
7596 return div_u64(chunk_len, data_stripes);
7597 }
7598
7599 static int verify_one_dev_extent(struct btrfs_fs_info *fs_info,
7600 u64 chunk_offset, u64 devid,
7601 u64 physical_offset, u64 physical_len)
7602 {
7603 struct extent_map_tree *em_tree = &fs_info->mapping_tree.map_tree;
7604 struct extent_map *em;
7605 struct map_lookup *map;
7606 struct btrfs_device *dev;
7607 u64 stripe_len;
7608 bool found = false;
7609 int ret = 0;
7610 int i;
7611
7612 read_lock(&em_tree->lock);
7613 em = lookup_extent_mapping(em_tree, chunk_offset, 1);
7614 read_unlock(&em_tree->lock);
7615
7616 if (!em) {
7617 btrfs_err(fs_info,
7618 "dev extent physical offset %llu on devid %llu doesn't have corresponding chunk",
7619 physical_offset, devid);
7620 ret = -EUCLEAN;
7621 goto out;
7622 }
7623
7624 map = em->map_lookup;
7625 stripe_len = calc_stripe_length(map->type, em->len, map->num_stripes);
7626 if (physical_len != stripe_len) {
7627 btrfs_err(fs_info,
7628 "dev extent physical offset %llu on devid %llu length doesn't match chunk %llu, have %llu expect %llu",
7629 physical_offset, devid, em->start, physical_len,
7630 stripe_len);
7631 ret = -EUCLEAN;
7632 goto out;
7633 }
7634
7635 for (i = 0; i < map->num_stripes; i++) {
7636 if (map->stripes[i].dev->devid == devid &&
7637 map->stripes[i].physical == physical_offset) {
7638 found = true;
7639 if (map->verified_stripes >= map->num_stripes) {
7640 btrfs_err(fs_info,
7641 "too many dev extents for chunk %llu found",
7642 em->start);
7643 ret = -EUCLEAN;
7644 goto out;
7645 }
7646 map->verified_stripes++;
7647 break;
7648 }
7649 }
7650 if (!found) {
7651 btrfs_err(fs_info,
7652 "dev extent physical offset %llu devid %llu has no corresponding chunk",
7653 physical_offset, devid);
7654 ret = -EUCLEAN;
7655 }
7656
7657 /* Make sure no dev extent is beyond device bondary */
7658 dev = btrfs_find_device(fs_info, devid, NULL, NULL);
7659 if (!dev) {
7660 btrfs_err(fs_info, "failed to find devid %llu", devid);
7661 ret = -EUCLEAN;
7662 goto out;
7663 }
7664 if (physical_offset + physical_len > dev->disk_total_bytes) {
7665 btrfs_err(fs_info,
7666 "dev extent devid %llu physical offset %llu len %llu is beyond device boundary %llu",
7667 devid, physical_offset, physical_len,
7668 dev->disk_total_bytes);
7669 ret = -EUCLEAN;
7670 goto out;
7671 }
7672 out:
7673 free_extent_map(em);
7674 return ret;
7675 }
7676
7677 static int verify_chunk_dev_extent_mapping(struct btrfs_fs_info *fs_info)
7678 {
7679 struct extent_map_tree *em_tree = &fs_info->mapping_tree.map_tree;
7680 struct extent_map *em;
7681 struct rb_node *node;
7682 int ret = 0;
7683
7684 read_lock(&em_tree->lock);
7685 for (node = rb_first_cached(&em_tree->map); node; node = rb_next(node)) {
7686 em = rb_entry(node, struct extent_map, rb_node);
7687 if (em->map_lookup->num_stripes !=
7688 em->map_lookup->verified_stripes) {
7689 btrfs_err(fs_info,
7690 "chunk %llu has missing dev extent, have %d expect %d",
7691 em->start, em->map_lookup->verified_stripes,
7692 em->map_lookup->num_stripes);
7693 ret = -EUCLEAN;
7694 goto out;
7695 }
7696 }
7697 out:
7698 read_unlock(&em_tree->lock);
7699 return ret;
7700 }
7701
7702 /*
7703 * Ensure that all dev extents are mapped to correct chunk, otherwise
7704 * later chunk allocation/free would cause unexpected behavior.
7705 *
7706 * NOTE: This will iterate through the whole device tree, which should be of
7707 * the same size level as the chunk tree. This slightly increases mount time.
7708 */
7709 int btrfs_verify_dev_extents(struct btrfs_fs_info *fs_info)
7710 {
7711 struct btrfs_path *path;
7712 struct btrfs_root *root = fs_info->dev_root;
7713 struct btrfs_key key;
7714 u64 prev_devid = 0;
7715 u64 prev_dev_ext_end = 0;
7716 int ret = 0;
7717
7718 key.objectid = 1;
7719 key.type = BTRFS_DEV_EXTENT_KEY;
7720 key.offset = 0;
7721
7722 path = btrfs_alloc_path();
7723 if (!path)
7724 return -ENOMEM;
7725
7726 path->reada = READA_FORWARD;
7727 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
7728 if (ret < 0)
7729 goto out;
7730
7731 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
7732 ret = btrfs_next_item(root, path);
7733 if (ret < 0)
7734 goto out;
7735 /* No dev extents at all? Not good */
7736 if (ret > 0) {
7737 ret = -EUCLEAN;
7738 goto out;
7739 }
7740 }
7741 while (1) {
7742 struct extent_buffer *leaf = path->nodes[0];
7743 struct btrfs_dev_extent *dext;
7744 int slot = path->slots[0];
7745 u64 chunk_offset;
7746 u64 physical_offset;
7747 u64 physical_len;
7748 u64 devid;
7749
7750 btrfs_item_key_to_cpu(leaf, &key, slot);
7751 if (key.type != BTRFS_DEV_EXTENT_KEY)
7752 break;
7753 devid = key.objectid;
7754 physical_offset = key.offset;
7755
7756 dext = btrfs_item_ptr(leaf, slot, struct btrfs_dev_extent);
7757 chunk_offset = btrfs_dev_extent_chunk_offset(leaf, dext);
7758 physical_len = btrfs_dev_extent_length(leaf, dext);
7759
7760 /* Check if this dev extent overlaps with the previous one */
7761 if (devid == prev_devid && physical_offset < prev_dev_ext_end) {
7762 btrfs_err(fs_info,
7763 "dev extent devid %llu physical offset %llu overlap with previous dev extent end %llu",
7764 devid, physical_offset, prev_dev_ext_end);
7765 ret = -EUCLEAN;
7766 goto out;
7767 }
7768
7769 ret = verify_one_dev_extent(fs_info, chunk_offset, devid,
7770 physical_offset, physical_len);
7771 if (ret < 0)
7772 goto out;
7773 prev_devid = devid;
7774 prev_dev_ext_end = physical_offset + physical_len;
7775
7776 ret = btrfs_next_item(root, path);
7777 if (ret < 0)
7778 goto out;
7779 if (ret > 0) {
7780 ret = 0;
7781 break;
7782 }
7783 }
7784
7785 /* Ensure all chunks have corresponding dev extents */
7786 ret = verify_chunk_dev_extent_mapping(fs_info);
7787 out:
7788 btrfs_free_path(path);
7789 return ret;
7790 }
7791
7792 /*
7793 * Check whether the given block group or device is pinned by any inode being
7794 * used as a swapfile.
7795 */
7796 bool btrfs_pinned_by_swapfile(struct btrfs_fs_info *fs_info, void *ptr)
7797 {
7798 struct btrfs_swapfile_pin *sp;
7799 struct rb_node *node;
7800
7801 spin_lock(&fs_info->swapfile_pins_lock);
7802 node = fs_info->swapfile_pins.rb_node;
7803 while (node) {
7804 sp = rb_entry(node, struct btrfs_swapfile_pin, node);
7805 if (ptr < sp->ptr)
7806 node = node->rb_left;
7807 else if (ptr > sp->ptr)
7808 node = node->rb_right;
7809 else
7810 break;
7811 }
7812 spin_unlock(&fs_info->swapfile_pins_lock);
7813 return node != NULL;
7814 }