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