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