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