xref: /linux/fs/btrfs/tree-checker.c (revision f3827213abae9291b7525b05e6fd29b1f0536ce6)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (C) Qu Wenruo 2017.  All rights reserved.
4  */
5 
6 /*
7  * The module is used to catch unexpected/corrupted tree block data.
8  * Such behavior can be caused either by a fuzzed image or bugs.
9  *
10  * The objective is to do leaf/node validation checks when tree block is read
11  * from disk, and check *every* possible member, so other code won't
12  * need to checking them again.
13  *
14  * Due to the potential and unwanted damage, every checker needs to be
15  * carefully reviewed otherwise so it does not prevent mount of valid images.
16  */
17 
18 #include <linux/types.h>
19 #include <linux/stddef.h>
20 #include <linux/error-injection.h>
21 #include "messages.h"
22 #include "ctree.h"
23 #include "tree-checker.h"
24 #include "compression.h"
25 #include "volumes.h"
26 #include "misc.h"
27 #include "fs.h"
28 #include "accessors.h"
29 #include "file-item.h"
30 #include "inode-item.h"
31 #include "dir-item.h"
32 #include "extent-tree.h"
33 
34 /*
35  * Error message should follow the following format:
36  * corrupt <type>: <identifier>, <reason>[, <bad_value>]
37  *
38  * @type:	leaf or node
39  * @identifier:	the necessary info to locate the leaf/node.
40  * 		It's recommended to decode key.objecitd/offset if it's
41  * 		meaningful.
42  * @reason:	describe the error
43  * @bad_value:	optional, it's recommended to output bad value and its
44  *		expected value (range).
45  *
46  * Since comma is used to separate the components, only space is allowed
47  * inside each component.
48  */
49 
50 /*
51  * Append generic "corrupt leaf/node root=%llu block=%llu slot=%d: " to @fmt.
52  * Allows callers to customize the output.
53  */
54 __printf(3, 4)
55 __cold
generic_err(const struct extent_buffer * eb,int slot,const char * fmt,...)56 static void generic_err(const struct extent_buffer *eb, int slot,
57 			const char *fmt, ...)
58 {
59 	const struct btrfs_fs_info *fs_info = eb->fs_info;
60 	struct va_format vaf;
61 	va_list args;
62 
63 	va_start(args, fmt);
64 
65 	vaf.fmt = fmt;
66 	vaf.va = &args;
67 
68 	dump_page(folio_page(eb->folios[0], 0), "eb page dump");
69 	btrfs_crit(fs_info,
70 		"corrupt %s: root=%llu block=%llu slot=%d, %pV",
71 		btrfs_header_level(eb) == 0 ? "leaf" : "node",
72 		btrfs_header_owner(eb), btrfs_header_bytenr(eb), slot, &vaf);
73 	va_end(args);
74 }
75 
76 /*
77  * Customized reporter for extent data item, since its key objectid and
78  * offset has its own meaning.
79  */
80 __printf(3, 4)
81 __cold
file_extent_err(const struct extent_buffer * eb,int slot,const char * fmt,...)82 static void file_extent_err(const struct extent_buffer *eb, int slot,
83 			    const char *fmt, ...)
84 {
85 	const struct btrfs_fs_info *fs_info = eb->fs_info;
86 	struct btrfs_key key;
87 	struct va_format vaf;
88 	va_list args;
89 
90 	btrfs_item_key_to_cpu(eb, &key, slot);
91 	va_start(args, fmt);
92 
93 	vaf.fmt = fmt;
94 	vaf.va = &args;
95 
96 	dump_page(folio_page(eb->folios[0], 0), "eb page dump");
97 	btrfs_crit(fs_info,
98 	"corrupt %s: root=%llu block=%llu slot=%d ino=%llu file_offset=%llu, %pV",
99 		btrfs_header_level(eb) == 0 ? "leaf" : "node",
100 		btrfs_header_owner(eb), btrfs_header_bytenr(eb), slot,
101 		key.objectid, key.offset, &vaf);
102 	va_end(args);
103 }
104 
105 /*
106  * Return 0 if the btrfs_file_extent_##name is aligned to @alignment
107  * Else return 1
108  */
109 #define CHECK_FE_ALIGNED(leaf, slot, fi, name, alignment)		      \
110 ({									      \
111 	if (unlikely(!IS_ALIGNED(btrfs_file_extent_##name((leaf), (fi)),      \
112 				 (alignment))))				      \
113 		file_extent_err((leaf), (slot),				      \
114 	"invalid %s for file extent, have %llu, should be aligned to %u",     \
115 			(#name), btrfs_file_extent_##name((leaf), (fi)),      \
116 			(alignment));					      \
117 	(!IS_ALIGNED(btrfs_file_extent_##name((leaf), (fi)), (alignment)));   \
118 })
119 
file_extent_end(struct extent_buffer * leaf,struct btrfs_key * key,struct btrfs_file_extent_item * extent)120 static u64 file_extent_end(struct extent_buffer *leaf,
121 			   struct btrfs_key *key,
122 			   struct btrfs_file_extent_item *extent)
123 {
124 	u64 end;
125 	u64 len;
126 
127 	if (btrfs_file_extent_type(leaf, extent) == BTRFS_FILE_EXTENT_INLINE) {
128 		len = btrfs_file_extent_ram_bytes(leaf, extent);
129 		end = ALIGN(key->offset + len, leaf->fs_info->sectorsize);
130 	} else {
131 		len = btrfs_file_extent_num_bytes(leaf, extent);
132 		end = key->offset + len;
133 	}
134 	return end;
135 }
136 
137 /*
138  * Customized report for dir_item, the only new important information is
139  * key->objectid, which represents inode number
140  */
141 __printf(3, 4)
142 __cold
dir_item_err(const struct extent_buffer * eb,int slot,const char * fmt,...)143 static void dir_item_err(const struct extent_buffer *eb, int slot,
144 			 const char *fmt, ...)
145 {
146 	const struct btrfs_fs_info *fs_info = eb->fs_info;
147 	struct btrfs_key key;
148 	struct va_format vaf;
149 	va_list args;
150 
151 	btrfs_item_key_to_cpu(eb, &key, slot);
152 	va_start(args, fmt);
153 
154 	vaf.fmt = fmt;
155 	vaf.va = &args;
156 
157 	dump_page(folio_page(eb->folios[0], 0), "eb page dump");
158 	btrfs_crit(fs_info,
159 		"corrupt %s: root=%llu block=%llu slot=%d ino=%llu, %pV",
160 		btrfs_header_level(eb) == 0 ? "leaf" : "node",
161 		btrfs_header_owner(eb), btrfs_header_bytenr(eb), slot,
162 		key.objectid, &vaf);
163 	va_end(args);
164 }
165 
166 /*
167  * This functions checks prev_key->objectid, to ensure current key and prev_key
168  * share the same objectid as inode number.
169  *
170  * This is to detect missing INODE_ITEM in subvolume trees.
171  *
172  * Return true if everything is OK or we don't need to check.
173  * Return false if anything is wrong.
174  */
check_prev_ino(struct extent_buffer * leaf,struct btrfs_key * key,int slot,struct btrfs_key * prev_key)175 static bool check_prev_ino(struct extent_buffer *leaf,
176 			   struct btrfs_key *key, int slot,
177 			   struct btrfs_key *prev_key)
178 {
179 	/* No prev key, skip check */
180 	if (slot == 0)
181 		return true;
182 
183 	/* Only these key->types needs to be checked */
184 	ASSERT(key->type == BTRFS_XATTR_ITEM_KEY ||
185 	       key->type == BTRFS_INODE_REF_KEY ||
186 	       key->type == BTRFS_INODE_EXTREF_KEY ||
187 	       key->type == BTRFS_DIR_INDEX_KEY ||
188 	       key->type == BTRFS_DIR_ITEM_KEY ||
189 	       key->type == BTRFS_EXTENT_DATA_KEY);
190 
191 	/*
192 	 * Only subvolume trees along with their reloc trees need this check.
193 	 * Things like log tree doesn't follow this ino requirement.
194 	 */
195 	if (!btrfs_is_fstree(btrfs_header_owner(leaf)))
196 		return true;
197 
198 	if (key->objectid == prev_key->objectid)
199 		return true;
200 
201 	/* Error found */
202 	dir_item_err(leaf, slot,
203 		"invalid previous key objectid, have %llu expect %llu",
204 		prev_key->objectid, key->objectid);
205 	return false;
206 }
check_extent_data_item(struct extent_buffer * leaf,struct btrfs_key * key,int slot,struct btrfs_key * prev_key)207 static int check_extent_data_item(struct extent_buffer *leaf,
208 				  struct btrfs_key *key, int slot,
209 				  struct btrfs_key *prev_key)
210 {
211 	struct btrfs_fs_info *fs_info = leaf->fs_info;
212 	struct btrfs_file_extent_item *fi;
213 	u32 sectorsize = fs_info->sectorsize;
214 	u32 item_size = btrfs_item_size(leaf, slot);
215 	u64 extent_end;
216 
217 	if (unlikely(!IS_ALIGNED(key->offset, sectorsize))) {
218 		file_extent_err(leaf, slot,
219 "unaligned file_offset for file extent, have %llu should be aligned to %u",
220 			key->offset, sectorsize);
221 		return -EUCLEAN;
222 	}
223 
224 	/*
225 	 * Previous key must have the same key->objectid (ino).
226 	 * It can be XATTR_ITEM, INODE_ITEM or just another EXTENT_DATA.
227 	 * But if objectids mismatch, it means we have a missing
228 	 * INODE_ITEM.
229 	 */
230 	if (unlikely(!check_prev_ino(leaf, key, slot, prev_key)))
231 		return -EUCLEAN;
232 
233 	fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
234 
235 	/*
236 	 * Make sure the item contains at least inline header, so the file
237 	 * extent type is not some garbage.
238 	 */
239 	if (unlikely(item_size < BTRFS_FILE_EXTENT_INLINE_DATA_START)) {
240 		file_extent_err(leaf, slot,
241 				"invalid item size, have %u expect [%zu, %u)",
242 				item_size, BTRFS_FILE_EXTENT_INLINE_DATA_START,
243 				SZ_4K);
244 		return -EUCLEAN;
245 	}
246 	if (unlikely(btrfs_file_extent_type(leaf, fi) >=
247 		     BTRFS_NR_FILE_EXTENT_TYPES)) {
248 		file_extent_err(leaf, slot,
249 		"invalid type for file extent, have %u expect range [0, %u]",
250 			btrfs_file_extent_type(leaf, fi),
251 			BTRFS_NR_FILE_EXTENT_TYPES - 1);
252 		return -EUCLEAN;
253 	}
254 
255 	/*
256 	 * Support for new compression/encryption must introduce incompat flag,
257 	 * and must be caught in open_ctree().
258 	 */
259 	if (unlikely(btrfs_file_extent_compression(leaf, fi) >=
260 		     BTRFS_NR_COMPRESS_TYPES)) {
261 		file_extent_err(leaf, slot,
262 	"invalid compression for file extent, have %u expect range [0, %u]",
263 			btrfs_file_extent_compression(leaf, fi),
264 			BTRFS_NR_COMPRESS_TYPES - 1);
265 		return -EUCLEAN;
266 	}
267 	if (unlikely(btrfs_file_extent_encryption(leaf, fi))) {
268 		file_extent_err(leaf, slot,
269 			"invalid encryption for file extent, have %u expect 0",
270 			btrfs_file_extent_encryption(leaf, fi));
271 		return -EUCLEAN;
272 	}
273 	if (btrfs_file_extent_type(leaf, fi) == BTRFS_FILE_EXTENT_INLINE) {
274 		/* Inline extent must have 0 as key offset */
275 		if (unlikely(key->offset)) {
276 			file_extent_err(leaf, slot,
277 		"invalid file_offset for inline file extent, have %llu expect 0",
278 				key->offset);
279 			return -EUCLEAN;
280 		}
281 
282 		/* Compressed inline extent has no on-disk size, skip it */
283 		if (btrfs_file_extent_compression(leaf, fi) !=
284 		    BTRFS_COMPRESS_NONE)
285 			return 0;
286 
287 		/* Uncompressed inline extent size must match item size */
288 		if (unlikely(item_size != BTRFS_FILE_EXTENT_INLINE_DATA_START +
289 					  btrfs_file_extent_ram_bytes(leaf, fi))) {
290 			file_extent_err(leaf, slot,
291 	"invalid ram_bytes for uncompressed inline extent, have %u expect %llu",
292 				item_size, BTRFS_FILE_EXTENT_INLINE_DATA_START +
293 				btrfs_file_extent_ram_bytes(leaf, fi));
294 			return -EUCLEAN;
295 		}
296 		return 0;
297 	}
298 
299 	/* Regular or preallocated extent has fixed item size */
300 	if (unlikely(item_size != sizeof(*fi))) {
301 		file_extent_err(leaf, slot,
302 	"invalid item size for reg/prealloc file extent, have %u expect %zu",
303 			item_size, sizeof(*fi));
304 		return -EUCLEAN;
305 	}
306 	if (unlikely(CHECK_FE_ALIGNED(leaf, slot, fi, ram_bytes, sectorsize) ||
307 		     CHECK_FE_ALIGNED(leaf, slot, fi, disk_bytenr, sectorsize) ||
308 		     CHECK_FE_ALIGNED(leaf, slot, fi, disk_num_bytes, sectorsize) ||
309 		     CHECK_FE_ALIGNED(leaf, slot, fi, offset, sectorsize) ||
310 		     CHECK_FE_ALIGNED(leaf, slot, fi, num_bytes, sectorsize)))
311 		return -EUCLEAN;
312 
313 	/* Catch extent end overflow */
314 	if (unlikely(check_add_overflow(btrfs_file_extent_num_bytes(leaf, fi),
315 					key->offset, &extent_end))) {
316 		file_extent_err(leaf, slot,
317 	"extent end overflow, have file offset %llu extent num bytes %llu",
318 				key->offset,
319 				btrfs_file_extent_num_bytes(leaf, fi));
320 		return -EUCLEAN;
321 	}
322 
323 	/*
324 	 * Check that no two consecutive file extent items, in the same leaf,
325 	 * present ranges that overlap each other.
326 	 */
327 	if (slot > 0 &&
328 	    prev_key->objectid == key->objectid &&
329 	    prev_key->type == BTRFS_EXTENT_DATA_KEY) {
330 		struct btrfs_file_extent_item *prev_fi;
331 		u64 prev_end;
332 
333 		prev_fi = btrfs_item_ptr(leaf, slot - 1,
334 					 struct btrfs_file_extent_item);
335 		prev_end = file_extent_end(leaf, prev_key, prev_fi);
336 		if (unlikely(prev_end > key->offset)) {
337 			file_extent_err(leaf, slot - 1,
338 "file extent end range (%llu) goes beyond start offset (%llu) of the next file extent",
339 					prev_end, key->offset);
340 			return -EUCLEAN;
341 		}
342 	}
343 
344 	/*
345 	 * For non-compressed data extents, ram_bytes should match its
346 	 * disk_num_bytes.
347 	 * However we do not really utilize ram_bytes in this case, so this check
348 	 * is only optional for DEBUG builds for developers to catch the
349 	 * unexpected behaviors.
350 	 */
351 	if (IS_ENABLED(CONFIG_BTRFS_DEBUG) &&
352 	    btrfs_file_extent_compression(leaf, fi) == BTRFS_COMPRESS_NONE &&
353 	    btrfs_file_extent_disk_bytenr(leaf, fi)) {
354 		if (WARN_ON(btrfs_file_extent_ram_bytes(leaf, fi) !=
355 			    btrfs_file_extent_disk_num_bytes(leaf, fi)))
356 			file_extent_err(leaf, slot,
357 "mismatch ram_bytes (%llu) and disk_num_bytes (%llu) for non-compressed extent",
358 					btrfs_file_extent_ram_bytes(leaf, fi),
359 					btrfs_file_extent_disk_num_bytes(leaf, fi));
360 	}
361 
362 	return 0;
363 }
364 
check_csum_item(struct extent_buffer * leaf,struct btrfs_key * key,int slot,struct btrfs_key * prev_key)365 static int check_csum_item(struct extent_buffer *leaf, struct btrfs_key *key,
366 			   int slot, struct btrfs_key *prev_key)
367 {
368 	struct btrfs_fs_info *fs_info = leaf->fs_info;
369 	u32 sectorsize = fs_info->sectorsize;
370 	const u32 csumsize = fs_info->csum_size;
371 
372 	if (unlikely(key->objectid != BTRFS_EXTENT_CSUM_OBJECTID)) {
373 		generic_err(leaf, slot,
374 		"invalid key objectid for csum item, have %llu expect %llu",
375 			key->objectid, BTRFS_EXTENT_CSUM_OBJECTID);
376 		return -EUCLEAN;
377 	}
378 	if (unlikely(!IS_ALIGNED(key->offset, sectorsize))) {
379 		generic_err(leaf, slot,
380 	"unaligned key offset for csum item, have %llu should be aligned to %u",
381 			key->offset, sectorsize);
382 		return -EUCLEAN;
383 	}
384 	if (unlikely(!IS_ALIGNED(btrfs_item_size(leaf, slot), csumsize))) {
385 		generic_err(leaf, slot,
386 	"unaligned item size for csum item, have %u should be aligned to %u",
387 			btrfs_item_size(leaf, slot), csumsize);
388 		return -EUCLEAN;
389 	}
390 	if (slot > 0 && prev_key->type == BTRFS_EXTENT_CSUM_KEY) {
391 		u64 prev_csum_end;
392 		u32 prev_item_size;
393 
394 		prev_item_size = btrfs_item_size(leaf, slot - 1);
395 		prev_csum_end = (prev_item_size / csumsize) * sectorsize;
396 		prev_csum_end += prev_key->offset;
397 		if (unlikely(prev_csum_end > key->offset)) {
398 			generic_err(leaf, slot - 1,
399 "csum end range (%llu) goes beyond the start range (%llu) of the next csum item",
400 				    prev_csum_end, key->offset);
401 			return -EUCLEAN;
402 		}
403 	}
404 	return 0;
405 }
406 
407 /* Inode item error output has the same format as dir_item_err() */
408 #define inode_item_err(eb, slot, fmt, ...)			\
409 	dir_item_err(eb, slot, fmt, __VA_ARGS__)
410 
check_inode_key(struct extent_buffer * leaf,struct btrfs_key * key,int slot)411 static int check_inode_key(struct extent_buffer *leaf, struct btrfs_key *key,
412 			   int slot)
413 {
414 	struct btrfs_key item_key;
415 	bool is_inode_item;
416 
417 	btrfs_item_key_to_cpu(leaf, &item_key, slot);
418 	is_inode_item = (item_key.type == BTRFS_INODE_ITEM_KEY);
419 
420 	/* For XATTR_ITEM, location key should be all 0 */
421 	if (item_key.type == BTRFS_XATTR_ITEM_KEY) {
422 		if (unlikely(key->objectid != 0 || key->type != 0 ||
423 			     key->offset != 0))
424 			return -EUCLEAN;
425 		return 0;
426 	}
427 
428 	if (unlikely((key->objectid < BTRFS_FIRST_FREE_OBJECTID ||
429 		      key->objectid > BTRFS_LAST_FREE_OBJECTID) &&
430 		     key->objectid != BTRFS_ROOT_TREE_DIR_OBJECTID &&
431 		     key->objectid != BTRFS_FREE_INO_OBJECTID)) {
432 		if (is_inode_item) {
433 			generic_err(leaf, slot,
434 	"invalid key objectid: has %llu expect %llu or [%llu, %llu] or %llu",
435 				key->objectid, BTRFS_ROOT_TREE_DIR_OBJECTID,
436 				BTRFS_FIRST_FREE_OBJECTID,
437 				BTRFS_LAST_FREE_OBJECTID,
438 				BTRFS_FREE_INO_OBJECTID);
439 		} else {
440 			dir_item_err(leaf, slot,
441 "invalid location key objectid: has %llu expect %llu or [%llu, %llu] or %llu",
442 				key->objectid, BTRFS_ROOT_TREE_DIR_OBJECTID,
443 				BTRFS_FIRST_FREE_OBJECTID,
444 				BTRFS_LAST_FREE_OBJECTID,
445 				BTRFS_FREE_INO_OBJECTID);
446 		}
447 		return -EUCLEAN;
448 	}
449 	if (unlikely(key->offset != 0)) {
450 		if (is_inode_item)
451 			inode_item_err(leaf, slot,
452 				       "invalid key offset: has %llu expect 0",
453 				       key->offset);
454 		else
455 			dir_item_err(leaf, slot,
456 				"invalid location key offset:has %llu expect 0",
457 				key->offset);
458 		return -EUCLEAN;
459 	}
460 	return 0;
461 }
462 
check_root_key(struct extent_buffer * leaf,struct btrfs_key * key,int slot)463 static int check_root_key(struct extent_buffer *leaf, struct btrfs_key *key,
464 			  int slot)
465 {
466 	struct btrfs_key item_key;
467 	bool is_root_item;
468 
469 	btrfs_item_key_to_cpu(leaf, &item_key, slot);
470 	is_root_item = (item_key.type == BTRFS_ROOT_ITEM_KEY);
471 
472 	/*
473 	 * Bad rootid for reloc trees.
474 	 *
475 	 * Reloc trees are only for subvolume trees, other trees only need
476 	 * to be COWed to be relocated.
477 	 */
478 	if (unlikely(is_root_item && key->objectid == BTRFS_TREE_RELOC_OBJECTID &&
479 		     !btrfs_is_fstree(key->offset))) {
480 		generic_err(leaf, slot,
481 		"invalid reloc tree for root %lld, root id is not a subvolume tree",
482 			    key->offset);
483 		return -EUCLEAN;
484 	}
485 
486 	/* No such tree id */
487 	if (unlikely(key->objectid == 0)) {
488 		if (is_root_item)
489 			generic_err(leaf, slot, "invalid root id 0");
490 		else
491 			dir_item_err(leaf, slot,
492 				     "invalid location key root id 0");
493 		return -EUCLEAN;
494 	}
495 
496 	/* DIR_ITEM/INDEX/INODE_REF is not allowed to point to non-fs trees */
497 	if (unlikely(!btrfs_is_fstree(key->objectid) && !is_root_item)) {
498 		dir_item_err(leaf, slot,
499 		"invalid location key objectid, have %llu expect [%llu, %llu]",
500 				key->objectid, BTRFS_FIRST_FREE_OBJECTID,
501 				BTRFS_LAST_FREE_OBJECTID);
502 		return -EUCLEAN;
503 	}
504 
505 	/*
506 	 * ROOT_ITEM with non-zero offset means this is a snapshot, created at
507 	 * @offset transid.
508 	 * Furthermore, for location key in DIR_ITEM, its offset is always -1.
509 	 *
510 	 * So here we only check offset for reloc tree whose key->offset must
511 	 * be a valid tree.
512 	 */
513 	if (unlikely(key->objectid == BTRFS_TREE_RELOC_OBJECTID &&
514 		     key->offset == 0)) {
515 		generic_err(leaf, slot, "invalid root id 0 for reloc tree");
516 		return -EUCLEAN;
517 	}
518 	return 0;
519 }
520 
check_dir_item(struct extent_buffer * leaf,struct btrfs_key * key,struct btrfs_key * prev_key,int slot)521 static int check_dir_item(struct extent_buffer *leaf,
522 			  struct btrfs_key *key, struct btrfs_key *prev_key,
523 			  int slot)
524 {
525 	struct btrfs_fs_info *fs_info = leaf->fs_info;
526 	struct btrfs_dir_item *di;
527 	u32 item_size = btrfs_item_size(leaf, slot);
528 	u32 cur = 0;
529 
530 	if (unlikely(!check_prev_ino(leaf, key, slot, prev_key)))
531 		return -EUCLEAN;
532 
533 	di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
534 	while (cur < item_size) {
535 		struct btrfs_key location_key;
536 		u32 name_len;
537 		u32 data_len;
538 		u32 max_name_len;
539 		u32 total_size;
540 		u32 name_hash;
541 		u8 dir_type;
542 		int ret;
543 
544 		/* header itself should not cross item boundary */
545 		if (unlikely(cur + sizeof(*di) > item_size)) {
546 			dir_item_err(leaf, slot,
547 		"dir item header crosses item boundary, have %zu boundary %u",
548 				cur + sizeof(*di), item_size);
549 			return -EUCLEAN;
550 		}
551 
552 		/* Location key check */
553 		btrfs_dir_item_key_to_cpu(leaf, di, &location_key);
554 		if (location_key.type == BTRFS_ROOT_ITEM_KEY) {
555 			ret = check_root_key(leaf, &location_key, slot);
556 			if (unlikely(ret < 0))
557 				return ret;
558 		} else if (location_key.type == BTRFS_INODE_ITEM_KEY ||
559 			   location_key.type == 0) {
560 			ret = check_inode_key(leaf, &location_key, slot);
561 			if (unlikely(ret < 0))
562 				return ret;
563 		} else {
564 			dir_item_err(leaf, slot,
565 			"invalid location key type, have %u, expect %u or %u",
566 				     location_key.type, BTRFS_ROOT_ITEM_KEY,
567 				     BTRFS_INODE_ITEM_KEY);
568 			return -EUCLEAN;
569 		}
570 
571 		/* dir type check */
572 		dir_type = btrfs_dir_ftype(leaf, di);
573 		if (unlikely(dir_type <= BTRFS_FT_UNKNOWN ||
574 			     dir_type >= BTRFS_FT_MAX)) {
575 			dir_item_err(leaf, slot,
576 			"invalid dir item type, have %u expect (0, %u)",
577 				dir_type, BTRFS_FT_MAX);
578 			return -EUCLEAN;
579 		}
580 
581 		if (unlikely(key->type == BTRFS_XATTR_ITEM_KEY &&
582 			     dir_type != BTRFS_FT_XATTR)) {
583 			dir_item_err(leaf, slot,
584 		"invalid dir item type for XATTR key, have %u expect %u",
585 				dir_type, BTRFS_FT_XATTR);
586 			return -EUCLEAN;
587 		}
588 		if (unlikely(dir_type == BTRFS_FT_XATTR &&
589 			     key->type != BTRFS_XATTR_ITEM_KEY)) {
590 			dir_item_err(leaf, slot,
591 			"xattr dir type found for non-XATTR key");
592 			return -EUCLEAN;
593 		}
594 		if (dir_type == BTRFS_FT_XATTR)
595 			max_name_len = XATTR_NAME_MAX;
596 		else
597 			max_name_len = BTRFS_NAME_LEN;
598 
599 		/* Name/data length check */
600 		name_len = btrfs_dir_name_len(leaf, di);
601 		data_len = btrfs_dir_data_len(leaf, di);
602 		if (unlikely(name_len > max_name_len)) {
603 			dir_item_err(leaf, slot,
604 			"dir item name len too long, have %u max %u",
605 				name_len, max_name_len);
606 			return -EUCLEAN;
607 		}
608 		if (unlikely(name_len + data_len > BTRFS_MAX_XATTR_SIZE(fs_info))) {
609 			dir_item_err(leaf, slot,
610 			"dir item name and data len too long, have %u max %u",
611 				name_len + data_len,
612 				BTRFS_MAX_XATTR_SIZE(fs_info));
613 			return -EUCLEAN;
614 		}
615 
616 		if (unlikely(data_len && dir_type != BTRFS_FT_XATTR)) {
617 			dir_item_err(leaf, slot,
618 			"dir item with invalid data len, have %u expect 0",
619 				data_len);
620 			return -EUCLEAN;
621 		}
622 
623 		total_size = sizeof(*di) + name_len + data_len;
624 
625 		/* header and name/data should not cross item boundary */
626 		if (unlikely(cur + total_size > item_size)) {
627 			dir_item_err(leaf, slot,
628 		"dir item data crosses item boundary, have %u boundary %u",
629 				cur + total_size, item_size);
630 			return -EUCLEAN;
631 		}
632 
633 		/*
634 		 * Special check for XATTR/DIR_ITEM, as key->offset is name
635 		 * hash, should match its name
636 		 */
637 		if (key->type == BTRFS_DIR_ITEM_KEY ||
638 		    key->type == BTRFS_XATTR_ITEM_KEY) {
639 			char namebuf[MAX(BTRFS_NAME_LEN, XATTR_NAME_MAX)];
640 
641 			read_extent_buffer(leaf, namebuf,
642 					(unsigned long)(di + 1), name_len);
643 			name_hash = btrfs_name_hash(namebuf, name_len);
644 			if (unlikely(key->offset != name_hash)) {
645 				dir_item_err(leaf, slot,
646 		"name hash mismatch with key, have 0x%016x expect 0x%016llx",
647 					name_hash, key->offset);
648 				return -EUCLEAN;
649 			}
650 		}
651 		cur += total_size;
652 		di = (struct btrfs_dir_item *)((void *)di + total_size);
653 	}
654 	return 0;
655 }
656 
657 __printf(3, 4)
658 __cold
block_group_err(const struct extent_buffer * eb,int slot,const char * fmt,...)659 static void block_group_err(const struct extent_buffer *eb, int slot,
660 			    const char *fmt, ...)
661 {
662 	const struct btrfs_fs_info *fs_info = eb->fs_info;
663 	struct btrfs_key key;
664 	struct va_format vaf;
665 	va_list args;
666 
667 	btrfs_item_key_to_cpu(eb, &key, slot);
668 	va_start(args, fmt);
669 
670 	vaf.fmt = fmt;
671 	vaf.va = &args;
672 
673 	dump_page(folio_page(eb->folios[0], 0), "eb page dump");
674 	btrfs_crit(fs_info,
675 	"corrupt %s: root=%llu block=%llu slot=%d bg_start=%llu bg_len=%llu, %pV",
676 		btrfs_header_level(eb) == 0 ? "leaf" : "node",
677 		btrfs_header_owner(eb), btrfs_header_bytenr(eb), slot,
678 		key.objectid, key.offset, &vaf);
679 	va_end(args);
680 }
681 
check_block_group_item(struct extent_buffer * leaf,struct btrfs_key * key,int slot)682 static int check_block_group_item(struct extent_buffer *leaf,
683 				  struct btrfs_key *key, int slot)
684 {
685 	struct btrfs_fs_info *fs_info = leaf->fs_info;
686 	struct btrfs_block_group_item bgi;
687 	u32 item_size = btrfs_item_size(leaf, slot);
688 	u64 chunk_objectid;
689 	u64 flags;
690 	u64 type;
691 
692 	/*
693 	 * Here we don't really care about alignment since extent allocator can
694 	 * handle it.  We care more about the size.
695 	 */
696 	if (unlikely(key->offset == 0)) {
697 		block_group_err(leaf, slot,
698 				"invalid block group size 0");
699 		return -EUCLEAN;
700 	}
701 
702 	if (unlikely(item_size != sizeof(bgi))) {
703 		block_group_err(leaf, slot,
704 			"invalid item size, have %u expect %zu",
705 				item_size, sizeof(bgi));
706 		return -EUCLEAN;
707 	}
708 
709 	read_extent_buffer(leaf, &bgi, btrfs_item_ptr_offset(leaf, slot),
710 			   sizeof(bgi));
711 	chunk_objectid = btrfs_stack_block_group_chunk_objectid(&bgi);
712 	if (btrfs_fs_incompat(fs_info, EXTENT_TREE_V2)) {
713 		/*
714 		 * We don't init the nr_global_roots until we load the global
715 		 * roots, so this could be 0 at mount time.  If it's 0 we'll
716 		 * just assume we're fine, and later we'll check against our
717 		 * actual value.
718 		 */
719 		if (unlikely(fs_info->nr_global_roots &&
720 			     chunk_objectid >= fs_info->nr_global_roots)) {
721 			block_group_err(leaf, slot,
722 	"invalid block group global root id, have %llu, needs to be <= %llu",
723 					chunk_objectid,
724 					fs_info->nr_global_roots);
725 			return -EUCLEAN;
726 		}
727 	} else if (unlikely(chunk_objectid != BTRFS_FIRST_CHUNK_TREE_OBJECTID)) {
728 		block_group_err(leaf, slot,
729 		"invalid block group chunk objectid, have %llu expect %llu",
730 				btrfs_stack_block_group_chunk_objectid(&bgi),
731 				BTRFS_FIRST_CHUNK_TREE_OBJECTID);
732 		return -EUCLEAN;
733 	}
734 
735 	if (unlikely(btrfs_stack_block_group_used(&bgi) > key->offset)) {
736 		block_group_err(leaf, slot,
737 			"invalid block group used, have %llu expect [0, %llu)",
738 				btrfs_stack_block_group_used(&bgi), key->offset);
739 		return -EUCLEAN;
740 	}
741 
742 	flags = btrfs_stack_block_group_flags(&bgi);
743 	if (unlikely(hweight64(flags & BTRFS_BLOCK_GROUP_PROFILE_MASK) > 1)) {
744 		block_group_err(leaf, slot,
745 "invalid profile flags, have 0x%llx (%lu bits set) expect no more than 1 bit set",
746 			flags & BTRFS_BLOCK_GROUP_PROFILE_MASK,
747 			hweight64(flags & BTRFS_BLOCK_GROUP_PROFILE_MASK));
748 		return -EUCLEAN;
749 	}
750 
751 	type = flags & BTRFS_BLOCK_GROUP_TYPE_MASK;
752 	if (unlikely(type != BTRFS_BLOCK_GROUP_DATA &&
753 		     type != BTRFS_BLOCK_GROUP_METADATA &&
754 		     type != BTRFS_BLOCK_GROUP_SYSTEM &&
755 		     type != (BTRFS_BLOCK_GROUP_METADATA |
756 			      BTRFS_BLOCK_GROUP_DATA))) {
757 		block_group_err(leaf, slot,
758 "invalid type, have 0x%llx (%lu bits set) expect either 0x%llx, 0x%llx, 0x%llx or 0x%llx",
759 			type, hweight64(type),
760 			BTRFS_BLOCK_GROUP_DATA, BTRFS_BLOCK_GROUP_METADATA,
761 			BTRFS_BLOCK_GROUP_SYSTEM,
762 			BTRFS_BLOCK_GROUP_METADATA | BTRFS_BLOCK_GROUP_DATA);
763 		return -EUCLEAN;
764 	}
765 	return 0;
766 }
767 
768 __printf(5, 6)
769 __cold
chunk_err(const struct btrfs_fs_info * fs_info,const struct extent_buffer * leaf,const struct btrfs_chunk * chunk,u64 logical,const char * fmt,...)770 static void chunk_err(const struct btrfs_fs_info *fs_info,
771 		      const struct extent_buffer *leaf,
772 		      const struct btrfs_chunk *chunk, u64 logical,
773 		      const char *fmt, ...)
774 {
775 	bool is_sb = !leaf;
776 	struct va_format vaf;
777 	va_list args;
778 	int i;
779 	int slot = -1;
780 
781 	if (!is_sb) {
782 		/*
783 		 * Get the slot number by iterating through all slots, this
784 		 * would provide better readability.
785 		 */
786 		for (i = 0; i < btrfs_header_nritems(leaf); i++) {
787 			if (btrfs_item_ptr_offset(leaf, i) ==
788 					(unsigned long)chunk) {
789 				slot = i;
790 				break;
791 			}
792 		}
793 	}
794 	va_start(args, fmt);
795 	vaf.fmt = fmt;
796 	vaf.va = &args;
797 
798 	if (is_sb)
799 		btrfs_crit(fs_info,
800 		"corrupt superblock syschunk array: chunk_start=%llu, %pV",
801 			   logical, &vaf);
802 	else
803 		btrfs_crit(fs_info,
804 	"corrupt leaf: root=%llu block=%llu slot=%d chunk_start=%llu, %pV",
805 			   BTRFS_CHUNK_TREE_OBJECTID, leaf->start, slot,
806 			   logical, &vaf);
807 	va_end(args);
808 }
809 
810 /*
811  * The common chunk check which could also work on super block sys chunk array.
812  *
813  * If @leaf is NULL, then @chunk must be an on-stack chunk item.
814  * (For superblock sys_chunk array, and fs_info->sectorsize is unreliable)
815  *
816  * Return -EUCLEAN if anything is corrupted.
817  * Return 0 if everything is OK.
818  */
btrfs_check_chunk_valid(const struct btrfs_fs_info * fs_info,const struct extent_buffer * leaf,const struct btrfs_chunk * chunk,u64 logical,u32 sectorsize)819 int btrfs_check_chunk_valid(const struct btrfs_fs_info *fs_info,
820 			    const struct extent_buffer *leaf,
821 			    const struct btrfs_chunk *chunk, u64 logical,
822 			    u32 sectorsize)
823 {
824 	u64 length;
825 	u64 chunk_end;
826 	u64 stripe_len;
827 	u16 num_stripes;
828 	u16 sub_stripes;
829 	u64 type;
830 	u64 features;
831 	u32 chunk_sector_size;
832 	bool mixed = false;
833 	int raid_index;
834 	int nparity;
835 	int ncopies;
836 
837 	if (leaf) {
838 		length = btrfs_chunk_length(leaf, chunk);
839 		stripe_len = btrfs_chunk_stripe_len(leaf, chunk);
840 		num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
841 		sub_stripes = btrfs_chunk_sub_stripes(leaf, chunk);
842 		type = btrfs_chunk_type(leaf, chunk);
843 		chunk_sector_size = btrfs_chunk_sector_size(leaf, chunk);
844 	} else {
845 		length = btrfs_stack_chunk_length(chunk);
846 		stripe_len = btrfs_stack_chunk_stripe_len(chunk);
847 		num_stripes = btrfs_stack_chunk_num_stripes(chunk);
848 		sub_stripes = btrfs_stack_chunk_sub_stripes(chunk);
849 		type = btrfs_stack_chunk_type(chunk);
850 		chunk_sector_size = btrfs_stack_chunk_sector_size(chunk);
851 	}
852 	raid_index = btrfs_bg_flags_to_raid_index(type);
853 	ncopies = btrfs_raid_array[raid_index].ncopies;
854 	nparity = btrfs_raid_array[raid_index].nparity;
855 
856 	if (unlikely(!num_stripes)) {
857 		chunk_err(fs_info, leaf, chunk, logical,
858 			  "invalid chunk num_stripes, have %u", num_stripes);
859 		return -EUCLEAN;
860 	}
861 	if (unlikely(num_stripes < ncopies)) {
862 		chunk_err(fs_info, leaf, chunk, logical,
863 			  "invalid chunk num_stripes < ncopies, have %u < %d",
864 			  num_stripes, ncopies);
865 		return -EUCLEAN;
866 	}
867 	if (unlikely(nparity && num_stripes == nparity)) {
868 		chunk_err(fs_info, leaf, chunk, logical,
869 			  "invalid chunk num_stripes == nparity, have %u == %d",
870 			  num_stripes, nparity);
871 		return -EUCLEAN;
872 	}
873 	if (unlikely(!IS_ALIGNED(logical, sectorsize))) {
874 		chunk_err(fs_info, leaf, chunk, logical,
875 		"invalid chunk logical, have %llu should aligned to %u",
876 			  logical, sectorsize);
877 		return -EUCLEAN;
878 	}
879 	if (unlikely(chunk_sector_size != sectorsize)) {
880 		chunk_err(fs_info, leaf, chunk, logical,
881 			  "invalid chunk sectorsize, have %u expect %u",
882 			  chunk_sector_size, sectorsize);
883 		return -EUCLEAN;
884 	}
885 	if (unlikely(!length || !IS_ALIGNED(length, sectorsize))) {
886 		chunk_err(fs_info, leaf, chunk, logical,
887 			  "invalid chunk length, have %llu", length);
888 		return -EUCLEAN;
889 	}
890 	if (unlikely(check_add_overflow(logical, length, &chunk_end))) {
891 		chunk_err(fs_info, leaf, chunk, logical,
892 "invalid chunk logical start and length, have logical start %llu length %llu",
893 			  logical, length);
894 		return -EUCLEAN;
895 	}
896 	if (unlikely(!is_power_of_2(stripe_len) || stripe_len != BTRFS_STRIPE_LEN)) {
897 		chunk_err(fs_info, leaf, chunk, logical,
898 			  "invalid chunk stripe length: %llu",
899 			  stripe_len);
900 		return -EUCLEAN;
901 	}
902 	/*
903 	 * We artificially limit the chunk size, so that the number of stripes
904 	 * inside a chunk can be fit into a U32.  The current limit (256G) is
905 	 * way too large for real world usage anyway, and it's also much larger
906 	 * than our existing limit (10G).
907 	 *
908 	 * Thus it should be a good way to catch obvious bitflips.
909 	 */
910 	if (unlikely(length >= btrfs_stripe_nr_to_offset(U32_MAX))) {
911 		chunk_err(fs_info, leaf, chunk, logical,
912 			  "chunk length too large: have %llu limit %llu",
913 			  length, btrfs_stripe_nr_to_offset(U32_MAX));
914 		return -EUCLEAN;
915 	}
916 	if (unlikely(type & ~(BTRFS_BLOCK_GROUP_TYPE_MASK |
917 			      BTRFS_BLOCK_GROUP_PROFILE_MASK))) {
918 		chunk_err(fs_info, leaf, chunk, logical,
919 			  "unrecognized chunk type: 0x%llx",
920 			  ~(BTRFS_BLOCK_GROUP_TYPE_MASK |
921 			    BTRFS_BLOCK_GROUP_PROFILE_MASK) & type);
922 		return -EUCLEAN;
923 	}
924 
925 	if (unlikely(!has_single_bit_set(type & BTRFS_BLOCK_GROUP_PROFILE_MASK) &&
926 		     (type & BTRFS_BLOCK_GROUP_PROFILE_MASK) != 0)) {
927 		chunk_err(fs_info, leaf, chunk, logical,
928 		"invalid chunk profile flag: 0x%llx, expect 0 or 1 bit set",
929 			  type & BTRFS_BLOCK_GROUP_PROFILE_MASK);
930 		return -EUCLEAN;
931 	}
932 	if (unlikely((type & BTRFS_BLOCK_GROUP_TYPE_MASK) == 0)) {
933 		chunk_err(fs_info, leaf, chunk, logical,
934 	"missing chunk type flag, have 0x%llx one bit must be set in 0x%llx",
935 			  type, BTRFS_BLOCK_GROUP_TYPE_MASK);
936 		return -EUCLEAN;
937 	}
938 
939 	if (unlikely((type & BTRFS_BLOCK_GROUP_SYSTEM) &&
940 		     (type & (BTRFS_BLOCK_GROUP_METADATA |
941 			      BTRFS_BLOCK_GROUP_DATA)))) {
942 		chunk_err(fs_info, leaf, chunk, logical,
943 			  "system chunk with data or metadata type: 0x%llx",
944 			  type);
945 		return -EUCLEAN;
946 	}
947 
948 	features = btrfs_super_incompat_flags(fs_info->super_copy);
949 	if (features & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
950 		mixed = true;
951 
952 	if (!mixed) {
953 		if (unlikely((type & BTRFS_BLOCK_GROUP_METADATA) &&
954 			     (type & BTRFS_BLOCK_GROUP_DATA))) {
955 			chunk_err(fs_info, leaf, chunk, logical,
956 			"mixed chunk type in non-mixed mode: 0x%llx", type);
957 			return -EUCLEAN;
958 		}
959 	}
960 
961 	if (unlikely((type & BTRFS_BLOCK_GROUP_RAID10 &&
962 		      sub_stripes != btrfs_raid_array[BTRFS_RAID_RAID10].sub_stripes) ||
963 		     (type & BTRFS_BLOCK_GROUP_RAID1 &&
964 		      num_stripes != btrfs_raid_array[BTRFS_RAID_RAID1].devs_min) ||
965 		     (type & BTRFS_BLOCK_GROUP_RAID1C3 &&
966 		      num_stripes != btrfs_raid_array[BTRFS_RAID_RAID1C3].devs_min) ||
967 		     (type & BTRFS_BLOCK_GROUP_RAID1C4 &&
968 		      num_stripes != btrfs_raid_array[BTRFS_RAID_RAID1C4].devs_min) ||
969 		     (type & BTRFS_BLOCK_GROUP_RAID5 &&
970 		      num_stripes < btrfs_raid_array[BTRFS_RAID_RAID5].devs_min) ||
971 		     (type & BTRFS_BLOCK_GROUP_RAID6 &&
972 		      num_stripes < btrfs_raid_array[BTRFS_RAID_RAID6].devs_min) ||
973 		     (type & BTRFS_BLOCK_GROUP_DUP &&
974 		      num_stripes != btrfs_raid_array[BTRFS_RAID_DUP].dev_stripes) ||
975 		     ((type & BTRFS_BLOCK_GROUP_PROFILE_MASK) == 0 &&
976 		      num_stripes != btrfs_raid_array[BTRFS_RAID_SINGLE].dev_stripes))) {
977 		chunk_err(fs_info, leaf, chunk, logical,
978 			"invalid num_stripes:sub_stripes %u:%u for profile %llu",
979 			num_stripes, sub_stripes,
980 			type & BTRFS_BLOCK_GROUP_PROFILE_MASK);
981 		return -EUCLEAN;
982 	}
983 
984 	return 0;
985 }
986 
987 /*
988  * Enhanced version of chunk item checker.
989  *
990  * The common btrfs_check_chunk_valid() doesn't check item size since it needs
991  * to work on super block sys_chunk_array which doesn't have full item ptr.
992  */
check_leaf_chunk_item(struct extent_buffer * leaf,struct btrfs_chunk * chunk,struct btrfs_key * key,int slot)993 static int check_leaf_chunk_item(struct extent_buffer *leaf,
994 				 struct btrfs_chunk *chunk,
995 				 struct btrfs_key *key, int slot)
996 {
997 	struct btrfs_fs_info *fs_info = leaf->fs_info;
998 	int num_stripes;
999 
1000 	if (unlikely(btrfs_item_size(leaf, slot) < sizeof(struct btrfs_chunk))) {
1001 		chunk_err(fs_info, leaf, chunk, key->offset,
1002 			"invalid chunk item size: have %u expect [%zu, %u)",
1003 			btrfs_item_size(leaf, slot),
1004 			sizeof(struct btrfs_chunk),
1005 			BTRFS_LEAF_DATA_SIZE(fs_info));
1006 		return -EUCLEAN;
1007 	}
1008 
1009 	num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
1010 	/* Let btrfs_check_chunk_valid() handle this error type */
1011 	if (num_stripes == 0)
1012 		goto out;
1013 
1014 	if (unlikely(btrfs_chunk_item_size(num_stripes) !=
1015 		     btrfs_item_size(leaf, slot))) {
1016 		chunk_err(fs_info, leaf, chunk, key->offset,
1017 			"invalid chunk item size: have %u expect %lu",
1018 			btrfs_item_size(leaf, slot),
1019 			btrfs_chunk_item_size(num_stripes));
1020 		return -EUCLEAN;
1021 	}
1022 out:
1023 	return btrfs_check_chunk_valid(fs_info, leaf, chunk, key->offset,
1024 				       fs_info->sectorsize);
1025 }
1026 
1027 __printf(3, 4)
1028 __cold
dev_item_err(const struct extent_buffer * eb,int slot,const char * fmt,...)1029 static void dev_item_err(const struct extent_buffer *eb, int slot,
1030 			 const char *fmt, ...)
1031 {
1032 	struct btrfs_key key;
1033 	struct va_format vaf;
1034 	va_list args;
1035 
1036 	btrfs_item_key_to_cpu(eb, &key, slot);
1037 	va_start(args, fmt);
1038 
1039 	vaf.fmt = fmt;
1040 	vaf.va = &args;
1041 
1042 	dump_page(folio_page(eb->folios[0], 0), "eb page dump");
1043 	btrfs_crit(eb->fs_info,
1044 	"corrupt %s: root=%llu block=%llu slot=%d devid=%llu %pV",
1045 		btrfs_header_level(eb) == 0 ? "leaf" : "node",
1046 		btrfs_header_owner(eb), btrfs_header_bytenr(eb), slot,
1047 		key.objectid, &vaf);
1048 	va_end(args);
1049 }
1050 
check_dev_item(struct extent_buffer * leaf,struct btrfs_key * key,int slot)1051 static int check_dev_item(struct extent_buffer *leaf,
1052 			  struct btrfs_key *key, int slot)
1053 {
1054 	struct btrfs_dev_item *ditem;
1055 	const u32 item_size = btrfs_item_size(leaf, slot);
1056 
1057 	if (unlikely(key->objectid != BTRFS_DEV_ITEMS_OBJECTID)) {
1058 		dev_item_err(leaf, slot,
1059 			     "invalid objectid: has=%llu expect=%llu",
1060 			     key->objectid, BTRFS_DEV_ITEMS_OBJECTID);
1061 		return -EUCLEAN;
1062 	}
1063 
1064 	if (unlikely(item_size != sizeof(*ditem))) {
1065 		dev_item_err(leaf, slot, "invalid item size: has %u expect %zu",
1066 			     item_size, sizeof(*ditem));
1067 		return -EUCLEAN;
1068 	}
1069 
1070 	ditem = btrfs_item_ptr(leaf, slot, struct btrfs_dev_item);
1071 	if (unlikely(btrfs_device_id(leaf, ditem) != key->offset)) {
1072 		dev_item_err(leaf, slot,
1073 			     "devid mismatch: key has=%llu item has=%llu",
1074 			     key->offset, btrfs_device_id(leaf, ditem));
1075 		return -EUCLEAN;
1076 	}
1077 
1078 	/*
1079 	 * For device total_bytes, we don't have reliable way to check it, as
1080 	 * it can be 0 for device removal. Device size check can only be done
1081 	 * by dev extents check.
1082 	 */
1083 	if (unlikely(btrfs_device_bytes_used(leaf, ditem) >
1084 		     btrfs_device_total_bytes(leaf, ditem))) {
1085 		dev_item_err(leaf, slot,
1086 			     "invalid bytes used: have %llu expect [0, %llu]",
1087 			     btrfs_device_bytes_used(leaf, ditem),
1088 			     btrfs_device_total_bytes(leaf, ditem));
1089 		return -EUCLEAN;
1090 	}
1091 	/*
1092 	 * Remaining members like io_align/type/gen/dev_group aren't really
1093 	 * utilized.  Skip them to make later usage of them easier.
1094 	 */
1095 	return 0;
1096 }
1097 
check_inode_item(struct extent_buffer * leaf,struct btrfs_key * key,int slot)1098 static int check_inode_item(struct extent_buffer *leaf,
1099 			    struct btrfs_key *key, int slot)
1100 {
1101 	struct btrfs_fs_info *fs_info = leaf->fs_info;
1102 	struct btrfs_inode_item *iitem;
1103 	u64 super_gen = btrfs_super_generation(fs_info->super_copy);
1104 	u32 valid_mask = (S_IFMT | S_ISUID | S_ISGID | S_ISVTX | 0777);
1105 	const u32 item_size = btrfs_item_size(leaf, slot);
1106 	u32 mode;
1107 	int ret;
1108 	u32 flags;
1109 	u32 ro_flags;
1110 
1111 	ret = check_inode_key(leaf, key, slot);
1112 	if (unlikely(ret < 0))
1113 		return ret;
1114 
1115 	if (unlikely(item_size != sizeof(*iitem))) {
1116 		generic_err(leaf, slot, "invalid item size: has %u expect %zu",
1117 			    item_size, sizeof(*iitem));
1118 		return -EUCLEAN;
1119 	}
1120 
1121 	iitem = btrfs_item_ptr(leaf, slot, struct btrfs_inode_item);
1122 
1123 	/* Here we use super block generation + 1 to handle log tree */
1124 	if (unlikely(btrfs_inode_generation(leaf, iitem) > super_gen + 1)) {
1125 		inode_item_err(leaf, slot,
1126 			"invalid inode generation: has %llu expect (0, %llu]",
1127 			       btrfs_inode_generation(leaf, iitem),
1128 			       super_gen + 1);
1129 		return -EUCLEAN;
1130 	}
1131 	/* Note for ROOT_TREE_DIR_ITEM, mkfs could set its transid 0 */
1132 	if (unlikely(btrfs_inode_transid(leaf, iitem) > super_gen + 1)) {
1133 		inode_item_err(leaf, slot,
1134 			"invalid inode transid: has %llu expect [0, %llu]",
1135 			       btrfs_inode_transid(leaf, iitem), super_gen + 1);
1136 		return -EUCLEAN;
1137 	}
1138 
1139 	/*
1140 	 * For size and nbytes it's better not to be too strict, as for dir
1141 	 * item its size/nbytes can easily get wrong, but doesn't affect
1142 	 * anything in the fs. So here we skip the check.
1143 	 */
1144 	mode = btrfs_inode_mode(leaf, iitem);
1145 	if (unlikely(mode & ~valid_mask)) {
1146 		inode_item_err(leaf, slot,
1147 			       "unknown mode bit detected: 0x%x",
1148 			       mode & ~valid_mask);
1149 		return -EUCLEAN;
1150 	}
1151 
1152 	/*
1153 	 * S_IFMT is not bit mapped so we can't completely rely on
1154 	 * is_power_of_2/has_single_bit_set, but it can save us from checking
1155 	 * FIFO/CHR/DIR/REG.  Only needs to check BLK, LNK and SOCKS
1156 	 */
1157 	if (!has_single_bit_set(mode & S_IFMT)) {
1158 		if (unlikely(!S_ISLNK(mode) && !S_ISBLK(mode) && !S_ISSOCK(mode))) {
1159 			inode_item_err(leaf, slot,
1160 			"invalid mode: has 0%o expect valid S_IF* bit(s)",
1161 				       mode & S_IFMT);
1162 			return -EUCLEAN;
1163 		}
1164 	}
1165 	if (unlikely(S_ISDIR(mode) && btrfs_inode_nlink(leaf, iitem) > 1)) {
1166 		inode_item_err(leaf, slot,
1167 		       "invalid nlink: has %u expect no more than 1 for dir",
1168 			btrfs_inode_nlink(leaf, iitem));
1169 		return -EUCLEAN;
1170 	}
1171 	btrfs_inode_split_flags(btrfs_inode_flags(leaf, iitem), &flags, &ro_flags);
1172 	if (unlikely(flags & ~BTRFS_INODE_FLAG_MASK)) {
1173 		inode_item_err(leaf, slot,
1174 			       "unknown incompat flags detected: 0x%x", flags);
1175 		return -EUCLEAN;
1176 	}
1177 	if (unlikely(!sb_rdonly(fs_info->sb) &&
1178 		     (ro_flags & ~BTRFS_INODE_RO_FLAG_MASK))) {
1179 		inode_item_err(leaf, slot,
1180 			"unknown ro-compat flags detected on writeable mount: 0x%x",
1181 			ro_flags);
1182 		return -EUCLEAN;
1183 	}
1184 	return 0;
1185 }
1186 
check_root_item(struct extent_buffer * leaf,struct btrfs_key * key,int slot)1187 static int check_root_item(struct extent_buffer *leaf, struct btrfs_key *key,
1188 			   int slot)
1189 {
1190 	struct btrfs_fs_info *fs_info = leaf->fs_info;
1191 	struct btrfs_root_item ri = { 0 };
1192 	const u64 valid_root_flags = BTRFS_ROOT_SUBVOL_RDONLY |
1193 				     BTRFS_ROOT_SUBVOL_DEAD;
1194 	int ret;
1195 
1196 	ret = check_root_key(leaf, key, slot);
1197 	if (unlikely(ret < 0))
1198 		return ret;
1199 
1200 	if (unlikely(btrfs_item_size(leaf, slot) != sizeof(ri) &&
1201 		     btrfs_item_size(leaf, slot) !=
1202 		     btrfs_legacy_root_item_size())) {
1203 		generic_err(leaf, slot,
1204 			    "invalid root item size, have %u expect %zu or %u",
1205 			    btrfs_item_size(leaf, slot), sizeof(ri),
1206 			    btrfs_legacy_root_item_size());
1207 		return -EUCLEAN;
1208 	}
1209 
1210 	/*
1211 	 * For legacy root item, the members starting at generation_v2 will be
1212 	 * all filled with 0.
1213 	 * And since we allow generation_v2 as 0, it will still pass the check.
1214 	 */
1215 	read_extent_buffer(leaf, &ri, btrfs_item_ptr_offset(leaf, slot),
1216 			   btrfs_item_size(leaf, slot));
1217 
1218 	/* Generation related */
1219 	if (unlikely(btrfs_root_generation(&ri) >
1220 		     btrfs_super_generation(fs_info->super_copy) + 1)) {
1221 		generic_err(leaf, slot,
1222 			"invalid root generation, have %llu expect (0, %llu]",
1223 			    btrfs_root_generation(&ri),
1224 			    btrfs_super_generation(fs_info->super_copy) + 1);
1225 		return -EUCLEAN;
1226 	}
1227 	if (unlikely(btrfs_root_generation_v2(&ri) >
1228 		     btrfs_super_generation(fs_info->super_copy) + 1)) {
1229 		generic_err(leaf, slot,
1230 		"invalid root v2 generation, have %llu expect (0, %llu]",
1231 			    btrfs_root_generation_v2(&ri),
1232 			    btrfs_super_generation(fs_info->super_copy) + 1);
1233 		return -EUCLEAN;
1234 	}
1235 	if (unlikely(btrfs_root_last_snapshot(&ri) >
1236 		     btrfs_super_generation(fs_info->super_copy) + 1)) {
1237 		generic_err(leaf, slot,
1238 		"invalid root last_snapshot, have %llu expect (0, %llu]",
1239 			    btrfs_root_last_snapshot(&ri),
1240 			    btrfs_super_generation(fs_info->super_copy) + 1);
1241 		return -EUCLEAN;
1242 	}
1243 
1244 	/* Alignment and level check */
1245 	if (unlikely(!IS_ALIGNED(btrfs_root_bytenr(&ri), fs_info->sectorsize))) {
1246 		generic_err(leaf, slot,
1247 		"invalid root bytenr, have %llu expect to be aligned to %u",
1248 			    btrfs_root_bytenr(&ri), fs_info->sectorsize);
1249 		return -EUCLEAN;
1250 	}
1251 	if (unlikely(btrfs_root_level(&ri) >= BTRFS_MAX_LEVEL)) {
1252 		generic_err(leaf, slot,
1253 			    "invalid root level, have %u expect [0, %u]",
1254 			    btrfs_root_level(&ri), BTRFS_MAX_LEVEL - 1);
1255 		return -EUCLEAN;
1256 	}
1257 	if (unlikely(btrfs_root_drop_level(&ri) >= BTRFS_MAX_LEVEL)) {
1258 		generic_err(leaf, slot,
1259 			    "invalid root level, have %u expect [0, %u]",
1260 			    btrfs_root_drop_level(&ri), BTRFS_MAX_LEVEL - 1);
1261 		return -EUCLEAN;
1262 	}
1263 
1264 	/* Flags check */
1265 	if (unlikely(btrfs_root_flags(&ri) & ~valid_root_flags)) {
1266 		generic_err(leaf, slot,
1267 			    "invalid root flags, have 0x%llx expect mask 0x%llx",
1268 			    btrfs_root_flags(&ri), valid_root_flags);
1269 		return -EUCLEAN;
1270 	}
1271 	return 0;
1272 }
1273 
1274 __printf(3,4)
1275 __cold
extent_err(const struct extent_buffer * eb,int slot,const char * fmt,...)1276 static void extent_err(const struct extent_buffer *eb, int slot,
1277 		       const char *fmt, ...)
1278 {
1279 	struct btrfs_key key;
1280 	struct va_format vaf;
1281 	va_list args;
1282 	u64 bytenr;
1283 	u64 len;
1284 
1285 	btrfs_item_key_to_cpu(eb, &key, slot);
1286 	bytenr = key.objectid;
1287 	if (key.type == BTRFS_METADATA_ITEM_KEY ||
1288 	    key.type == BTRFS_TREE_BLOCK_REF_KEY ||
1289 	    key.type == BTRFS_SHARED_BLOCK_REF_KEY)
1290 		len = eb->fs_info->nodesize;
1291 	else
1292 		len = key.offset;
1293 	va_start(args, fmt);
1294 
1295 	vaf.fmt = fmt;
1296 	vaf.va = &args;
1297 
1298 	dump_page(folio_page(eb->folios[0], 0), "eb page dump");
1299 	btrfs_crit(eb->fs_info,
1300 	"corrupt %s: block=%llu slot=%d extent bytenr=%llu len=%llu %pV",
1301 		btrfs_header_level(eb) == 0 ? "leaf" : "node",
1302 		eb->start, slot, bytenr, len, &vaf);
1303 	va_end(args);
1304 }
1305 
is_valid_dref_root(u64 rootid)1306 static bool is_valid_dref_root(u64 rootid)
1307 {
1308 	/*
1309 	 * The following tree root objectids are allowed to have a data backref:
1310 	 * - subvolume trees
1311 	 * - data reloc tree
1312 	 * - tree root
1313 	 *   For v1 space cache
1314 	 */
1315 	return btrfs_is_fstree(rootid) || rootid == BTRFS_DATA_RELOC_TREE_OBJECTID ||
1316 	       rootid == BTRFS_ROOT_TREE_OBJECTID;
1317 }
1318 
check_extent_item(struct extent_buffer * leaf,struct btrfs_key * key,int slot,struct btrfs_key * prev_key)1319 static int check_extent_item(struct extent_buffer *leaf,
1320 			     struct btrfs_key *key, int slot,
1321 			     struct btrfs_key *prev_key)
1322 {
1323 	struct btrfs_fs_info *fs_info = leaf->fs_info;
1324 	struct btrfs_extent_item *ei;
1325 	bool is_tree_block = false;
1326 	unsigned long ptr;	/* Current pointer inside inline refs */
1327 	unsigned long end;	/* Extent item end */
1328 	const u32 item_size = btrfs_item_size(leaf, slot);
1329 	u8 last_type = 0;
1330 	u64 last_seq = U64_MAX;
1331 	u64 flags;
1332 	u64 generation;
1333 	u64 total_refs;		/* Total refs in btrfs_extent_item */
1334 	u64 inline_refs = 0;	/* found total inline refs */
1335 
1336 	if (unlikely(key->type == BTRFS_METADATA_ITEM_KEY &&
1337 		     !btrfs_fs_incompat(fs_info, SKINNY_METADATA))) {
1338 		generic_err(leaf, slot,
1339 "invalid key type, METADATA_ITEM type invalid when SKINNY_METADATA feature disabled");
1340 		return -EUCLEAN;
1341 	}
1342 	/* key->objectid is the bytenr for both key types */
1343 	if (unlikely(!IS_ALIGNED(key->objectid, fs_info->sectorsize))) {
1344 		generic_err(leaf, slot,
1345 		"invalid key objectid, have %llu expect to be aligned to %u",
1346 			   key->objectid, fs_info->sectorsize);
1347 		return -EUCLEAN;
1348 	}
1349 
1350 	/* key->offset is tree level for METADATA_ITEM_KEY */
1351 	if (unlikely(key->type == BTRFS_METADATA_ITEM_KEY &&
1352 		     key->offset >= BTRFS_MAX_LEVEL)) {
1353 		extent_err(leaf, slot,
1354 			   "invalid tree level, have %llu expect [0, %u]",
1355 			   key->offset, BTRFS_MAX_LEVEL - 1);
1356 		return -EUCLEAN;
1357 	}
1358 
1359 	/*
1360 	 * EXTENT/METADATA_ITEM consists of:
1361 	 * 1) One btrfs_extent_item
1362 	 *    Records the total refs, type and generation of the extent.
1363 	 *
1364 	 * 2) One btrfs_tree_block_info (for EXTENT_ITEM and tree backref only)
1365 	 *    Records the first key and level of the tree block.
1366 	 *
1367 	 * 2) Zero or more btrfs_extent_inline_ref(s)
1368 	 *    Each inline ref has one btrfs_extent_inline_ref shows:
1369 	 *    2.1) The ref type, one of the 4
1370 	 *         TREE_BLOCK_REF	Tree block only
1371 	 *         SHARED_BLOCK_REF	Tree block only
1372 	 *         EXTENT_DATA_REF	Data only
1373 	 *         SHARED_DATA_REF	Data only
1374 	 *    2.2) Ref type specific data
1375 	 *         Either using btrfs_extent_inline_ref::offset, or specific
1376 	 *         data structure.
1377 	 *
1378 	 *    All above inline items should follow the order:
1379 	 *
1380 	 *    - All btrfs_extent_inline_ref::type should be in an ascending
1381 	 *      order
1382 	 *
1383 	 *    - Within the same type, the items should follow a descending
1384 	 *      order by their sequence number. The sequence number is
1385 	 *      determined by:
1386 	 *      * btrfs_extent_inline_ref::offset for all types  other than
1387 	 *        EXTENT_DATA_REF
1388 	 *      * hash_extent_data_ref() for EXTENT_DATA_REF
1389 	 */
1390 	if (unlikely(item_size < sizeof(*ei))) {
1391 		extent_err(leaf, slot,
1392 			   "invalid item size, have %u expect [%zu, %u)",
1393 			   item_size, sizeof(*ei),
1394 			   BTRFS_LEAF_DATA_SIZE(fs_info));
1395 		return -EUCLEAN;
1396 	}
1397 	end = item_size + btrfs_item_ptr_offset(leaf, slot);
1398 
1399 	/* Checks against extent_item */
1400 	ei = btrfs_item_ptr(leaf, slot, struct btrfs_extent_item);
1401 	flags = btrfs_extent_flags(leaf, ei);
1402 	total_refs = btrfs_extent_refs(leaf, ei);
1403 	generation = btrfs_extent_generation(leaf, ei);
1404 	if (unlikely(generation >
1405 		     btrfs_super_generation(fs_info->super_copy) + 1)) {
1406 		extent_err(leaf, slot,
1407 			   "invalid generation, have %llu expect (0, %llu]",
1408 			   generation,
1409 			   btrfs_super_generation(fs_info->super_copy) + 1);
1410 		return -EUCLEAN;
1411 	}
1412 	if (unlikely(!has_single_bit_set(flags & (BTRFS_EXTENT_FLAG_DATA |
1413 						  BTRFS_EXTENT_FLAG_TREE_BLOCK)))) {
1414 		extent_err(leaf, slot,
1415 		"invalid extent flag, have 0x%llx expect 1 bit set in 0x%llx",
1416 			flags, BTRFS_EXTENT_FLAG_DATA |
1417 			BTRFS_EXTENT_FLAG_TREE_BLOCK);
1418 		return -EUCLEAN;
1419 	}
1420 	is_tree_block = !!(flags & BTRFS_EXTENT_FLAG_TREE_BLOCK);
1421 	if (is_tree_block) {
1422 		if (unlikely(key->type == BTRFS_EXTENT_ITEM_KEY &&
1423 			     key->offset != fs_info->nodesize)) {
1424 			extent_err(leaf, slot,
1425 				   "invalid extent length, have %llu expect %u",
1426 				   key->offset, fs_info->nodesize);
1427 			return -EUCLEAN;
1428 		}
1429 	} else {
1430 		if (unlikely(key->type != BTRFS_EXTENT_ITEM_KEY)) {
1431 			extent_err(leaf, slot,
1432 			"invalid key type, have %u expect %u for data backref",
1433 				   key->type, BTRFS_EXTENT_ITEM_KEY);
1434 			return -EUCLEAN;
1435 		}
1436 		if (unlikely(!IS_ALIGNED(key->offset, fs_info->sectorsize))) {
1437 			extent_err(leaf, slot,
1438 			"invalid extent length, have %llu expect aligned to %u",
1439 				   key->offset, fs_info->sectorsize);
1440 			return -EUCLEAN;
1441 		}
1442 		if (unlikely(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF)) {
1443 			extent_err(leaf, slot,
1444 			"invalid extent flag, data has full backref set");
1445 			return -EUCLEAN;
1446 		}
1447 	}
1448 	ptr = (unsigned long)(struct btrfs_extent_item *)(ei + 1);
1449 
1450 	/* Check the special case of btrfs_tree_block_info */
1451 	if (is_tree_block && key->type != BTRFS_METADATA_ITEM_KEY) {
1452 		struct btrfs_tree_block_info *info;
1453 
1454 		info = (struct btrfs_tree_block_info *)ptr;
1455 		if (unlikely(btrfs_tree_block_level(leaf, info) >= BTRFS_MAX_LEVEL)) {
1456 			extent_err(leaf, slot,
1457 			"invalid tree block info level, have %u expect [0, %u]",
1458 				   btrfs_tree_block_level(leaf, info),
1459 				   BTRFS_MAX_LEVEL - 1);
1460 			return -EUCLEAN;
1461 		}
1462 		ptr = (unsigned long)(struct btrfs_tree_block_info *)(info + 1);
1463 	}
1464 
1465 	/* Check inline refs */
1466 	while (ptr < end) {
1467 		struct btrfs_extent_inline_ref *iref;
1468 		struct btrfs_extent_data_ref *dref;
1469 		struct btrfs_shared_data_ref *sref;
1470 		u64 seq;
1471 		u64 dref_root;
1472 		u64 dref_objectid;
1473 		u64 dref_offset;
1474 		u64 inline_offset;
1475 		u8 inline_type;
1476 
1477 		if (unlikely(ptr + sizeof(*iref) > end)) {
1478 			extent_err(leaf, slot,
1479 "inline ref item overflows extent item, ptr %lu iref size %zu end %lu",
1480 				   ptr, sizeof(*iref), end);
1481 			return -EUCLEAN;
1482 		}
1483 		iref = (struct btrfs_extent_inline_ref *)ptr;
1484 		inline_type = btrfs_extent_inline_ref_type(leaf, iref);
1485 		inline_offset = btrfs_extent_inline_ref_offset(leaf, iref);
1486 		seq = inline_offset;
1487 		if (unlikely(ptr + btrfs_extent_inline_ref_size(inline_type) > end)) {
1488 			extent_err(leaf, slot,
1489 "inline ref item overflows extent item, ptr %lu iref size %u end %lu",
1490 				   ptr, btrfs_extent_inline_ref_size(inline_type), end);
1491 			return -EUCLEAN;
1492 		}
1493 
1494 		switch (inline_type) {
1495 		/* inline_offset is subvolid of the owner, no need to check */
1496 		case BTRFS_TREE_BLOCK_REF_KEY:
1497 			inline_refs++;
1498 			break;
1499 		/* Contains parent bytenr */
1500 		case BTRFS_SHARED_BLOCK_REF_KEY:
1501 			if (unlikely(!IS_ALIGNED(inline_offset,
1502 						 fs_info->sectorsize))) {
1503 				extent_err(leaf, slot,
1504 		"invalid tree parent bytenr, have %llu expect aligned to %u",
1505 					   inline_offset, fs_info->sectorsize);
1506 				return -EUCLEAN;
1507 			}
1508 			inline_refs++;
1509 			break;
1510 		/*
1511 		 * Contains owner subvolid, owner key objectid, adjusted offset.
1512 		 * The only obvious corruption can happen in that offset.
1513 		 */
1514 		case BTRFS_EXTENT_DATA_REF_KEY:
1515 			dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1516 			dref_root = btrfs_extent_data_ref_root(leaf, dref);
1517 			dref_objectid = btrfs_extent_data_ref_objectid(leaf, dref);
1518 			dref_offset = btrfs_extent_data_ref_offset(leaf, dref);
1519 			seq = hash_extent_data_ref(
1520 					btrfs_extent_data_ref_root(leaf, dref),
1521 					btrfs_extent_data_ref_objectid(leaf, dref),
1522 					btrfs_extent_data_ref_offset(leaf, dref));
1523 			if (unlikely(!is_valid_dref_root(dref_root))) {
1524 				extent_err(leaf, slot,
1525 					   "invalid data ref root value %llu",
1526 					   dref_root);
1527 				return -EUCLEAN;
1528 			}
1529 			if (unlikely(dref_objectid < BTRFS_FIRST_FREE_OBJECTID ||
1530 				     dref_objectid > BTRFS_LAST_FREE_OBJECTID)) {
1531 				extent_err(leaf, slot,
1532 					   "invalid data ref objectid value %llu",
1533 					   dref_objectid);
1534 				return -EUCLEAN;
1535 			}
1536 			if (unlikely(!IS_ALIGNED(dref_offset,
1537 						 fs_info->sectorsize))) {
1538 				extent_err(leaf, slot,
1539 		"invalid data ref offset, have %llu expect aligned to %u",
1540 					   dref_offset, fs_info->sectorsize);
1541 				return -EUCLEAN;
1542 			}
1543 			if (unlikely(btrfs_extent_data_ref_count(leaf, dref) == 0)) {
1544 				extent_err(leaf, slot,
1545 			"invalid data ref count, should have non-zero value");
1546 				return -EUCLEAN;
1547 			}
1548 			inline_refs += btrfs_extent_data_ref_count(leaf, dref);
1549 			break;
1550 		/* Contains parent bytenr and ref count */
1551 		case BTRFS_SHARED_DATA_REF_KEY:
1552 			sref = (struct btrfs_shared_data_ref *)(iref + 1);
1553 			if (unlikely(!IS_ALIGNED(inline_offset,
1554 						 fs_info->sectorsize))) {
1555 				extent_err(leaf, slot,
1556 		"invalid data parent bytenr, have %llu expect aligned to %u",
1557 					   inline_offset, fs_info->sectorsize);
1558 				return -EUCLEAN;
1559 			}
1560 			if (unlikely(btrfs_shared_data_ref_count(leaf, sref) == 0)) {
1561 				extent_err(leaf, slot,
1562 			"invalid shared data ref count, should have non-zero value");
1563 				return -EUCLEAN;
1564 			}
1565 			inline_refs += btrfs_shared_data_ref_count(leaf, sref);
1566 			break;
1567 		case BTRFS_EXTENT_OWNER_REF_KEY:
1568 			WARN_ON(!btrfs_fs_incompat(fs_info, SIMPLE_QUOTA));
1569 			break;
1570 		default:
1571 			extent_err(leaf, slot, "unknown inline ref type: %u",
1572 				   inline_type);
1573 			return -EUCLEAN;
1574 		}
1575 		if (unlikely(inline_type < last_type)) {
1576 			extent_err(leaf, slot,
1577 				   "inline ref out-of-order: has type %u, prev type %u",
1578 				   inline_type, last_type);
1579 			return -EUCLEAN;
1580 		}
1581 		/* Type changed, allow the sequence starts from U64_MAX again. */
1582 		if (inline_type > last_type)
1583 			last_seq = U64_MAX;
1584 		if (unlikely(seq > last_seq)) {
1585 			extent_err(leaf, slot,
1586 "inline ref out-of-order: has type %u offset %llu seq 0x%llx, prev type %u seq 0x%llx",
1587 				   inline_type, inline_offset, seq,
1588 				   last_type, last_seq);
1589 			return -EUCLEAN;
1590 		}
1591 		last_type = inline_type;
1592 		last_seq = seq;
1593 		ptr += btrfs_extent_inline_ref_size(inline_type);
1594 	}
1595 	/* No padding is allowed */
1596 	if (unlikely(ptr != end)) {
1597 		extent_err(leaf, slot,
1598 			   "invalid extent item size, padding bytes found");
1599 		return -EUCLEAN;
1600 	}
1601 
1602 	/* Finally, check the inline refs against total refs */
1603 	if (unlikely(inline_refs > total_refs)) {
1604 		extent_err(leaf, slot,
1605 			"invalid extent refs, have %llu expect >= inline %llu",
1606 			   total_refs, inline_refs);
1607 		return -EUCLEAN;
1608 	}
1609 
1610 	if ((prev_key->type == BTRFS_EXTENT_ITEM_KEY) ||
1611 	    (prev_key->type == BTRFS_METADATA_ITEM_KEY)) {
1612 		u64 prev_end = prev_key->objectid;
1613 
1614 		if (prev_key->type == BTRFS_METADATA_ITEM_KEY)
1615 			prev_end += fs_info->nodesize;
1616 		else
1617 			prev_end += prev_key->offset;
1618 
1619 		if (unlikely(prev_end > key->objectid)) {
1620 			extent_err(leaf, slot,
1621 	"previous extent [%llu %u %llu] overlaps current extent [%llu %u %llu]",
1622 				   prev_key->objectid, prev_key->type,
1623 				   prev_key->offset, key->objectid, key->type,
1624 				   key->offset);
1625 			return -EUCLEAN;
1626 		}
1627 	}
1628 
1629 	return 0;
1630 }
1631 
check_simple_keyed_refs(struct extent_buffer * leaf,struct btrfs_key * key,int slot)1632 static int check_simple_keyed_refs(struct extent_buffer *leaf,
1633 				   struct btrfs_key *key, int slot)
1634 {
1635 	u32 expect_item_size = 0;
1636 
1637 	if (key->type == BTRFS_SHARED_DATA_REF_KEY) {
1638 		struct btrfs_shared_data_ref *sref;
1639 
1640 		sref = btrfs_item_ptr(leaf, slot, struct btrfs_shared_data_ref);
1641 		if (unlikely(btrfs_shared_data_ref_count(leaf, sref) == 0)) {
1642 			extent_err(leaf, slot,
1643 		"invalid shared data backref count, should have non-zero value");
1644 			return -EUCLEAN;
1645 		}
1646 
1647 		expect_item_size = sizeof(struct btrfs_shared_data_ref);
1648 	}
1649 
1650 	if (unlikely(btrfs_item_size(leaf, slot) != expect_item_size)) {
1651 		generic_err(leaf, slot,
1652 		"invalid item size, have %u expect %u for key type %u",
1653 			    btrfs_item_size(leaf, slot),
1654 			    expect_item_size, key->type);
1655 		return -EUCLEAN;
1656 	}
1657 	if (unlikely(!IS_ALIGNED(key->objectid, leaf->fs_info->sectorsize))) {
1658 		generic_err(leaf, slot,
1659 "invalid key objectid for shared block ref, have %llu expect aligned to %u",
1660 			    key->objectid, leaf->fs_info->sectorsize);
1661 		return -EUCLEAN;
1662 	}
1663 	if (unlikely(key->type != BTRFS_TREE_BLOCK_REF_KEY &&
1664 		     !IS_ALIGNED(key->offset, leaf->fs_info->sectorsize))) {
1665 		extent_err(leaf, slot,
1666 		"invalid tree parent bytenr, have %llu expect aligned to %u",
1667 			   key->offset, leaf->fs_info->sectorsize);
1668 		return -EUCLEAN;
1669 	}
1670 	return 0;
1671 }
1672 
check_extent_data_ref(struct extent_buffer * leaf,struct btrfs_key * key,int slot)1673 static int check_extent_data_ref(struct extent_buffer *leaf,
1674 				 struct btrfs_key *key, int slot)
1675 {
1676 	struct btrfs_extent_data_ref *dref;
1677 	unsigned long ptr = btrfs_item_ptr_offset(leaf, slot);
1678 	const unsigned long end = ptr + btrfs_item_size(leaf, slot);
1679 
1680 	if (unlikely(btrfs_item_size(leaf, slot) % sizeof(*dref) != 0)) {
1681 		generic_err(leaf, slot,
1682 	"invalid item size, have %u expect aligned to %zu for key type %u",
1683 			    btrfs_item_size(leaf, slot),
1684 			    sizeof(*dref), key->type);
1685 		return -EUCLEAN;
1686 	}
1687 	if (unlikely(!IS_ALIGNED(key->objectid, leaf->fs_info->sectorsize))) {
1688 		generic_err(leaf, slot,
1689 "invalid key objectid for shared block ref, have %llu expect aligned to %u",
1690 			    key->objectid, leaf->fs_info->sectorsize);
1691 		return -EUCLEAN;
1692 	}
1693 	for (; ptr < end; ptr += sizeof(*dref)) {
1694 		u64 root;
1695 		u64 objectid;
1696 		u64 offset;
1697 
1698 		/*
1699 		 * We cannot check the extent_data_ref hash due to possible
1700 		 * overflow from the leaf due to hash collisions.
1701 		 */
1702 		dref = (struct btrfs_extent_data_ref *)ptr;
1703 		root = btrfs_extent_data_ref_root(leaf, dref);
1704 		objectid = btrfs_extent_data_ref_objectid(leaf, dref);
1705 		offset = btrfs_extent_data_ref_offset(leaf, dref);
1706 		if (unlikely(!is_valid_dref_root(root))) {
1707 			extent_err(leaf, slot,
1708 				   "invalid extent data backref root value %llu",
1709 				   root);
1710 			return -EUCLEAN;
1711 		}
1712 		if (unlikely(objectid < BTRFS_FIRST_FREE_OBJECTID ||
1713 			     objectid > BTRFS_LAST_FREE_OBJECTID)) {
1714 			extent_err(leaf, slot,
1715 				   "invalid extent data backref objectid value %llu",
1716 				   root);
1717 			return -EUCLEAN;
1718 		}
1719 		if (unlikely(!IS_ALIGNED(offset, leaf->fs_info->sectorsize))) {
1720 			extent_err(leaf, slot,
1721 	"invalid extent data backref offset, have %llu expect aligned to %u",
1722 				   offset, leaf->fs_info->sectorsize);
1723 			return -EUCLEAN;
1724 		}
1725 		if (unlikely(btrfs_extent_data_ref_count(leaf, dref) == 0)) {
1726 			extent_err(leaf, slot,
1727 	"invalid extent data backref count, should have non-zero value");
1728 			return -EUCLEAN;
1729 		}
1730 	}
1731 	return 0;
1732 }
1733 
1734 #define inode_ref_err(eb, slot, fmt, args...)			\
1735 	inode_item_err(eb, slot, fmt, ##args)
check_inode_ref(struct extent_buffer * leaf,struct btrfs_key * key,struct btrfs_key * prev_key,int slot)1736 static int check_inode_ref(struct extent_buffer *leaf,
1737 			   struct btrfs_key *key, struct btrfs_key *prev_key,
1738 			   int slot)
1739 {
1740 	struct btrfs_inode_ref *iref;
1741 	unsigned long ptr;
1742 	unsigned long end;
1743 
1744 	if (unlikely(!check_prev_ino(leaf, key, slot, prev_key)))
1745 		return -EUCLEAN;
1746 	/* namelen can't be 0, so item_size == sizeof() is also invalid */
1747 	if (unlikely(btrfs_item_size(leaf, slot) <= sizeof(*iref))) {
1748 		inode_ref_err(leaf, slot,
1749 			"invalid item size, have %u expect (%zu, %u)",
1750 			btrfs_item_size(leaf, slot),
1751 			sizeof(*iref), BTRFS_LEAF_DATA_SIZE(leaf->fs_info));
1752 		return -EUCLEAN;
1753 	}
1754 
1755 	ptr = btrfs_item_ptr_offset(leaf, slot);
1756 	end = ptr + btrfs_item_size(leaf, slot);
1757 	while (ptr < end) {
1758 		u16 namelen;
1759 
1760 		if (unlikely(ptr + sizeof(*iref) > end)) {
1761 			inode_ref_err(leaf, slot,
1762 			"inode ref overflow, ptr %lu end %lu inode_ref_size %zu",
1763 				ptr, end, sizeof(*iref));
1764 			return -EUCLEAN;
1765 		}
1766 
1767 		iref = (struct btrfs_inode_ref *)ptr;
1768 		namelen = btrfs_inode_ref_name_len(leaf, iref);
1769 		if (unlikely(ptr + sizeof(*iref) + namelen > end)) {
1770 			inode_ref_err(leaf, slot,
1771 				"inode ref overflow, ptr %lu end %lu namelen %u",
1772 				ptr, end, namelen);
1773 			return -EUCLEAN;
1774 		}
1775 
1776 		/*
1777 		 * NOTE: In theory we should record all found index numbers
1778 		 * to find any duplicated indexes, but that will be too time
1779 		 * consuming for inodes with too many hard links.
1780 		 */
1781 		ptr += sizeof(*iref) + namelen;
1782 	}
1783 	return 0;
1784 }
1785 
check_inode_extref(struct extent_buffer * leaf,struct btrfs_key * key,struct btrfs_key * prev_key,int slot)1786 static int check_inode_extref(struct extent_buffer *leaf,
1787 			      struct btrfs_key *key, struct btrfs_key *prev_key,
1788 			      int slot)
1789 {
1790 	unsigned long ptr = btrfs_item_ptr_offset(leaf, slot);
1791 	unsigned long end = ptr + btrfs_item_size(leaf, slot);
1792 
1793 	if (unlikely(!check_prev_ino(leaf, key, slot, prev_key)))
1794 		return -EUCLEAN;
1795 
1796 	while (ptr < end) {
1797 		struct btrfs_inode_extref *extref = (struct btrfs_inode_extref *)ptr;
1798 		u16 namelen;
1799 
1800 		if (unlikely(ptr + sizeof(*extref)) > end) {
1801 			inode_ref_err(leaf, slot,
1802 			"inode extref overflow, ptr %lu end %lu inode_extref size %zu",
1803 				      ptr, end, sizeof(*extref));
1804 			return -EUCLEAN;
1805 		}
1806 
1807 		namelen = btrfs_inode_extref_name_len(leaf, extref);
1808 		if (unlikely(ptr + sizeof(*extref) + namelen > end)) {
1809 			inode_ref_err(leaf, slot,
1810 				"inode extref overflow, ptr %lu end %lu namelen %u",
1811 				ptr, end, namelen);
1812 			return -EUCLEAN;
1813 		}
1814 		ptr += sizeof(*extref) + namelen;
1815 	}
1816 	return 0;
1817 }
1818 
check_raid_stripe_extent(const struct extent_buffer * leaf,const struct btrfs_key * key,int slot)1819 static int check_raid_stripe_extent(const struct extent_buffer *leaf,
1820 				    const struct btrfs_key *key, int slot)
1821 {
1822 	if (unlikely(!IS_ALIGNED(key->objectid, leaf->fs_info->sectorsize))) {
1823 		generic_err(leaf, slot,
1824 "invalid key objectid for raid stripe extent, have %llu expect aligned to %u",
1825 			    key->objectid, leaf->fs_info->sectorsize);
1826 		return -EUCLEAN;
1827 	}
1828 
1829 	if (unlikely(!btrfs_fs_incompat(leaf->fs_info, RAID_STRIPE_TREE))) {
1830 		generic_err(leaf, slot,
1831 	"RAID_STRIPE_EXTENT present but RAID_STRIPE_TREE incompat bit unset");
1832 		return -EUCLEAN;
1833 	}
1834 
1835 	return 0;
1836 }
1837 
check_dev_extent_item(const struct extent_buffer * leaf,const struct btrfs_key * key,int slot,struct btrfs_key * prev_key)1838 static int check_dev_extent_item(const struct extent_buffer *leaf,
1839 				 const struct btrfs_key *key,
1840 				 int slot,
1841 				 struct btrfs_key *prev_key)
1842 {
1843 	struct btrfs_dev_extent *de;
1844 	const u32 sectorsize = leaf->fs_info->sectorsize;
1845 
1846 	de = btrfs_item_ptr(leaf, slot, struct btrfs_dev_extent);
1847 	/* Basic fixed member checks. */
1848 	if (unlikely(btrfs_dev_extent_chunk_tree(leaf, de) !=
1849 		     BTRFS_CHUNK_TREE_OBJECTID)) {
1850 		generic_err(leaf, slot,
1851 			    "invalid dev extent chunk tree id, has %llu expect %llu",
1852 			    btrfs_dev_extent_chunk_tree(leaf, de),
1853 			    BTRFS_CHUNK_TREE_OBJECTID);
1854 		return -EUCLEAN;
1855 	}
1856 	if (unlikely(btrfs_dev_extent_chunk_objectid(leaf, de) !=
1857 		     BTRFS_FIRST_CHUNK_TREE_OBJECTID)) {
1858 		generic_err(leaf, slot,
1859 			    "invalid dev extent chunk objectid, has %llu expect %llu",
1860 			    btrfs_dev_extent_chunk_objectid(leaf, de),
1861 			    BTRFS_FIRST_CHUNK_TREE_OBJECTID);
1862 		return -EUCLEAN;
1863 	}
1864 	/* Alignment check. */
1865 	if (unlikely(!IS_ALIGNED(key->offset, sectorsize))) {
1866 		generic_err(leaf, slot,
1867 			    "invalid dev extent key.offset, has %llu not aligned to %u",
1868 			    key->offset, sectorsize);
1869 		return -EUCLEAN;
1870 	}
1871 	if (unlikely(!IS_ALIGNED(btrfs_dev_extent_chunk_offset(leaf, de),
1872 				 sectorsize))) {
1873 		generic_err(leaf, slot,
1874 			    "invalid dev extent chunk offset, has %llu not aligned to %u",
1875 			    btrfs_dev_extent_chunk_objectid(leaf, de),
1876 			    sectorsize);
1877 		return -EUCLEAN;
1878 	}
1879 	if (unlikely(!IS_ALIGNED(btrfs_dev_extent_length(leaf, de),
1880 				 sectorsize))) {
1881 		generic_err(leaf, slot,
1882 			    "invalid dev extent length, has %llu not aligned to %u",
1883 			    btrfs_dev_extent_length(leaf, de), sectorsize);
1884 		return -EUCLEAN;
1885 	}
1886 	/* Overlap check with previous dev extent. */
1887 	if (slot && prev_key->objectid == key->objectid &&
1888 	    prev_key->type == key->type) {
1889 		struct btrfs_dev_extent *prev_de;
1890 		u64 prev_len;
1891 
1892 		prev_de = btrfs_item_ptr(leaf, slot - 1, struct btrfs_dev_extent);
1893 		prev_len = btrfs_dev_extent_length(leaf, prev_de);
1894 		if (unlikely(prev_key->offset + prev_len > key->offset)) {
1895 			generic_err(leaf, slot,
1896 		"dev extent overlap, prev offset %llu len %llu current offset %llu",
1897 				    prev_key->objectid, prev_len, key->offset);
1898 			return -EUCLEAN;
1899 		}
1900 	}
1901 	return 0;
1902 }
1903 
1904 /*
1905  * Common point to switch the item-specific validation.
1906  */
check_leaf_item(struct extent_buffer * leaf,struct btrfs_key * key,int slot,struct btrfs_key * prev_key)1907 static enum btrfs_tree_block_status check_leaf_item(struct extent_buffer *leaf,
1908 						    struct btrfs_key *key,
1909 						    int slot,
1910 						    struct btrfs_key *prev_key)
1911 {
1912 	int ret = 0;
1913 	struct btrfs_chunk *chunk;
1914 
1915 	switch (key->type) {
1916 	case BTRFS_EXTENT_DATA_KEY:
1917 		ret = check_extent_data_item(leaf, key, slot, prev_key);
1918 		break;
1919 	case BTRFS_EXTENT_CSUM_KEY:
1920 		ret = check_csum_item(leaf, key, slot, prev_key);
1921 		break;
1922 	case BTRFS_DIR_ITEM_KEY:
1923 	case BTRFS_DIR_INDEX_KEY:
1924 	case BTRFS_XATTR_ITEM_KEY:
1925 		ret = check_dir_item(leaf, key, prev_key, slot);
1926 		break;
1927 	case BTRFS_INODE_REF_KEY:
1928 		ret = check_inode_ref(leaf, key, prev_key, slot);
1929 		break;
1930 	case BTRFS_INODE_EXTREF_KEY:
1931 		ret = check_inode_extref(leaf, key, prev_key, slot);
1932 		break;
1933 	case BTRFS_BLOCK_GROUP_ITEM_KEY:
1934 		ret = check_block_group_item(leaf, key, slot);
1935 		break;
1936 	case BTRFS_CHUNK_ITEM_KEY:
1937 		chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
1938 		ret = check_leaf_chunk_item(leaf, chunk, key, slot);
1939 		break;
1940 	case BTRFS_DEV_ITEM_KEY:
1941 		ret = check_dev_item(leaf, key, slot);
1942 		break;
1943 	case BTRFS_DEV_EXTENT_KEY:
1944 		ret = check_dev_extent_item(leaf, key, slot, prev_key);
1945 		break;
1946 	case BTRFS_INODE_ITEM_KEY:
1947 		ret = check_inode_item(leaf, key, slot);
1948 		break;
1949 	case BTRFS_ROOT_ITEM_KEY:
1950 		ret = check_root_item(leaf, key, slot);
1951 		break;
1952 	case BTRFS_EXTENT_ITEM_KEY:
1953 	case BTRFS_METADATA_ITEM_KEY:
1954 		ret = check_extent_item(leaf, key, slot, prev_key);
1955 		break;
1956 	case BTRFS_TREE_BLOCK_REF_KEY:
1957 	case BTRFS_SHARED_DATA_REF_KEY:
1958 	case BTRFS_SHARED_BLOCK_REF_KEY:
1959 		ret = check_simple_keyed_refs(leaf, key, slot);
1960 		break;
1961 	case BTRFS_EXTENT_DATA_REF_KEY:
1962 		ret = check_extent_data_ref(leaf, key, slot);
1963 		break;
1964 	case BTRFS_RAID_STRIPE_KEY:
1965 		ret = check_raid_stripe_extent(leaf, key, slot);
1966 		break;
1967 	}
1968 
1969 	if (unlikely(ret))
1970 		return BTRFS_TREE_BLOCK_INVALID_ITEM;
1971 	return BTRFS_TREE_BLOCK_CLEAN;
1972 }
1973 
__btrfs_check_leaf(struct extent_buffer * leaf)1974 enum btrfs_tree_block_status __btrfs_check_leaf(struct extent_buffer *leaf)
1975 {
1976 	struct btrfs_fs_info *fs_info = leaf->fs_info;
1977 	/* No valid key type is 0, so all key should be larger than this key */
1978 	struct btrfs_key prev_key = {0, 0, 0};
1979 	struct btrfs_key key;
1980 	u32 nritems = btrfs_header_nritems(leaf);
1981 	int slot;
1982 
1983 	if (unlikely(btrfs_header_level(leaf) != 0)) {
1984 		generic_err(leaf, 0,
1985 			"invalid level for leaf, have %d expect 0",
1986 			btrfs_header_level(leaf));
1987 		return BTRFS_TREE_BLOCK_INVALID_LEVEL;
1988 	}
1989 
1990 	if (unlikely(!btrfs_header_flag(leaf, BTRFS_HEADER_FLAG_WRITTEN))) {
1991 		generic_err(leaf, 0, "invalid flag for leaf, WRITTEN not set");
1992 		return BTRFS_TREE_BLOCK_WRITTEN_NOT_SET;
1993 	}
1994 
1995 	/*
1996 	 * Extent buffers from a relocation tree have a owner field that
1997 	 * corresponds to the subvolume tree they are based on. So just from an
1998 	 * extent buffer alone we can not find out what is the id of the
1999 	 * corresponding subvolume tree, so we can not figure out if the extent
2000 	 * buffer corresponds to the root of the relocation tree or not. So
2001 	 * skip this check for relocation trees.
2002 	 */
2003 	if (nritems == 0 && !btrfs_header_flag(leaf, BTRFS_HEADER_FLAG_RELOC)) {
2004 		u64 owner = btrfs_header_owner(leaf);
2005 
2006 		/* These trees must never be empty */
2007 		if (unlikely(owner == BTRFS_ROOT_TREE_OBJECTID ||
2008 			     owner == BTRFS_CHUNK_TREE_OBJECTID ||
2009 			     owner == BTRFS_DEV_TREE_OBJECTID ||
2010 			     owner == BTRFS_FS_TREE_OBJECTID ||
2011 			     owner == BTRFS_DATA_RELOC_TREE_OBJECTID)) {
2012 			generic_err(leaf, 0,
2013 			"invalid root, root %llu must never be empty",
2014 				    owner);
2015 			return BTRFS_TREE_BLOCK_INVALID_NRITEMS;
2016 		}
2017 
2018 		/* Unknown tree */
2019 		if (unlikely(owner == 0)) {
2020 			generic_err(leaf, 0,
2021 				"invalid owner, root 0 is not defined");
2022 			return BTRFS_TREE_BLOCK_INVALID_OWNER;
2023 		}
2024 
2025 		/* EXTENT_TREE_V2 can have empty extent trees. */
2026 		if (btrfs_fs_incompat(fs_info, EXTENT_TREE_V2))
2027 			return BTRFS_TREE_BLOCK_CLEAN;
2028 
2029 		if (unlikely(owner == BTRFS_EXTENT_TREE_OBJECTID)) {
2030 			generic_err(leaf, 0,
2031 			"invalid root, root %llu must never be empty",
2032 				    owner);
2033 			return BTRFS_TREE_BLOCK_INVALID_NRITEMS;
2034 		}
2035 
2036 		return BTRFS_TREE_BLOCK_CLEAN;
2037 	}
2038 
2039 	if (unlikely(nritems == 0))
2040 		return BTRFS_TREE_BLOCK_CLEAN;
2041 
2042 	/*
2043 	 * Check the following things to make sure this is a good leaf, and
2044 	 * leaf users won't need to bother with similar sanity checks:
2045 	 *
2046 	 * 1) key ordering
2047 	 * 2) item offset and size
2048 	 *    No overlap, no hole, all inside the leaf.
2049 	 * 3) item content
2050 	 *    If possible, do comprehensive sanity check.
2051 	 *    NOTE: All checks must only rely on the item data itself.
2052 	 */
2053 	for (slot = 0; slot < nritems; slot++) {
2054 		u32 item_end_expected;
2055 		u64 item_data_end;
2056 		enum btrfs_tree_block_status ret;
2057 
2058 		btrfs_item_key_to_cpu(leaf, &key, slot);
2059 
2060 		/* Make sure the keys are in the right order */
2061 		if (unlikely(btrfs_comp_cpu_keys(&prev_key, &key) >= 0)) {
2062 			generic_err(leaf, slot,
2063 	"bad key order, prev (%llu %u %llu) current (%llu %u %llu)",
2064 				prev_key.objectid, prev_key.type,
2065 				prev_key.offset, key.objectid, key.type,
2066 				key.offset);
2067 			return BTRFS_TREE_BLOCK_BAD_KEY_ORDER;
2068 		}
2069 
2070 		item_data_end = (u64)btrfs_item_offset(leaf, slot) +
2071 				btrfs_item_size(leaf, slot);
2072 		/*
2073 		 * Make sure the offset and ends are right, remember that the
2074 		 * item data starts at the end of the leaf and grows towards the
2075 		 * front.
2076 		 */
2077 		if (slot == 0)
2078 			item_end_expected = BTRFS_LEAF_DATA_SIZE(fs_info);
2079 		else
2080 			item_end_expected = btrfs_item_offset(leaf,
2081 								 slot - 1);
2082 		if (unlikely(item_data_end != item_end_expected)) {
2083 			generic_err(leaf, slot,
2084 				"unexpected item end, have %llu expect %u",
2085 				item_data_end, item_end_expected);
2086 			return BTRFS_TREE_BLOCK_INVALID_OFFSETS;
2087 		}
2088 
2089 		/*
2090 		 * Check to make sure that we don't point outside of the leaf,
2091 		 * just in case all the items are consistent to each other, but
2092 		 * all point outside of the leaf.
2093 		 */
2094 		if (unlikely(item_data_end > BTRFS_LEAF_DATA_SIZE(fs_info))) {
2095 			generic_err(leaf, slot,
2096 			"slot end outside of leaf, have %llu expect range [0, %u]",
2097 				item_data_end, BTRFS_LEAF_DATA_SIZE(fs_info));
2098 			return BTRFS_TREE_BLOCK_INVALID_OFFSETS;
2099 		}
2100 
2101 		/* Also check if the item pointer overlaps with btrfs item. */
2102 		if (unlikely(btrfs_item_ptr_offset(leaf, slot) <
2103 			     btrfs_item_nr_offset(leaf, slot) + sizeof(struct btrfs_item))) {
2104 			generic_err(leaf, slot,
2105 		"slot overlaps with its data, item end %lu data start %lu",
2106 				btrfs_item_nr_offset(leaf, slot) +
2107 				sizeof(struct btrfs_item),
2108 				btrfs_item_ptr_offset(leaf, slot));
2109 			return BTRFS_TREE_BLOCK_INVALID_OFFSETS;
2110 		}
2111 
2112 		/* Check if the item size and content meet other criteria. */
2113 		ret = check_leaf_item(leaf, &key, slot, &prev_key);
2114 		if (unlikely(ret != BTRFS_TREE_BLOCK_CLEAN))
2115 			return ret;
2116 
2117 		prev_key.objectid = key.objectid;
2118 		prev_key.type = key.type;
2119 		prev_key.offset = key.offset;
2120 	}
2121 
2122 	return BTRFS_TREE_BLOCK_CLEAN;
2123 }
2124 
btrfs_check_leaf(struct extent_buffer * leaf)2125 int btrfs_check_leaf(struct extent_buffer *leaf)
2126 {
2127 	enum btrfs_tree_block_status ret;
2128 
2129 	ret = __btrfs_check_leaf(leaf);
2130 	if (unlikely(ret != BTRFS_TREE_BLOCK_CLEAN))
2131 		return -EUCLEAN;
2132 	return 0;
2133 }
2134 ALLOW_ERROR_INJECTION(btrfs_check_leaf, ERRNO);
2135 
__btrfs_check_node(struct extent_buffer * node)2136 enum btrfs_tree_block_status __btrfs_check_node(struct extent_buffer *node)
2137 {
2138 	struct btrfs_fs_info *fs_info = node->fs_info;
2139 	unsigned long nr = btrfs_header_nritems(node);
2140 	struct btrfs_key key, next_key;
2141 	int slot;
2142 	int level = btrfs_header_level(node);
2143 	u64 bytenr;
2144 
2145 	if (unlikely(!btrfs_header_flag(node, BTRFS_HEADER_FLAG_WRITTEN))) {
2146 		generic_err(node, 0, "invalid flag for node, WRITTEN not set");
2147 		return BTRFS_TREE_BLOCK_WRITTEN_NOT_SET;
2148 	}
2149 
2150 	if (unlikely(level <= 0 || level >= BTRFS_MAX_LEVEL)) {
2151 		generic_err(node, 0,
2152 			"invalid level for node, have %d expect [1, %d]",
2153 			level, BTRFS_MAX_LEVEL - 1);
2154 		return BTRFS_TREE_BLOCK_INVALID_LEVEL;
2155 	}
2156 	if (unlikely(nr == 0 || nr > BTRFS_NODEPTRS_PER_BLOCK(fs_info))) {
2157 		btrfs_crit(fs_info,
2158 "corrupt node: root=%llu block=%llu, nritems too %s, have %lu expect range [1,%u]",
2159 			   btrfs_header_owner(node), node->start,
2160 			   nr == 0 ? "small" : "large", nr,
2161 			   BTRFS_NODEPTRS_PER_BLOCK(fs_info));
2162 		return BTRFS_TREE_BLOCK_INVALID_NRITEMS;
2163 	}
2164 
2165 	for (slot = 0; slot < nr - 1; slot++) {
2166 		bytenr = btrfs_node_blockptr(node, slot);
2167 		btrfs_node_key_to_cpu(node, &key, slot);
2168 		btrfs_node_key_to_cpu(node, &next_key, slot + 1);
2169 
2170 		if (unlikely(!bytenr)) {
2171 			generic_err(node, slot,
2172 				"invalid NULL node pointer");
2173 			return BTRFS_TREE_BLOCK_INVALID_BLOCKPTR;
2174 		}
2175 		if (unlikely(!IS_ALIGNED(bytenr, fs_info->sectorsize))) {
2176 			generic_err(node, slot,
2177 			"unaligned pointer, have %llu should be aligned to %u",
2178 				bytenr, fs_info->sectorsize);
2179 			return BTRFS_TREE_BLOCK_INVALID_BLOCKPTR;
2180 		}
2181 
2182 		if (unlikely(btrfs_comp_cpu_keys(&key, &next_key) >= 0)) {
2183 			generic_err(node, slot,
2184 	"bad key order, current (%llu %u %llu) next (%llu %u %llu)",
2185 				key.objectid, key.type, key.offset,
2186 				next_key.objectid, next_key.type,
2187 				next_key.offset);
2188 			return BTRFS_TREE_BLOCK_BAD_KEY_ORDER;
2189 		}
2190 	}
2191 	return BTRFS_TREE_BLOCK_CLEAN;
2192 }
2193 
btrfs_check_node(struct extent_buffer * node)2194 int btrfs_check_node(struct extent_buffer *node)
2195 {
2196 	enum btrfs_tree_block_status ret;
2197 
2198 	ret = __btrfs_check_node(node);
2199 	if (unlikely(ret != BTRFS_TREE_BLOCK_CLEAN))
2200 		return -EUCLEAN;
2201 	return 0;
2202 }
2203 ALLOW_ERROR_INJECTION(btrfs_check_node, ERRNO);
2204 
btrfs_check_eb_owner(const struct extent_buffer * eb,u64 root_owner)2205 int btrfs_check_eb_owner(const struct extent_buffer *eb, u64 root_owner)
2206 {
2207 	const bool is_subvol = btrfs_is_fstree(root_owner);
2208 	const u64 eb_owner = btrfs_header_owner(eb);
2209 
2210 	/*
2211 	 * Skip dummy fs, as selftests don't create unique ebs for each dummy
2212 	 * root.
2213 	 */
2214 	if (btrfs_is_testing(eb->fs_info))
2215 		return 0;
2216 	/*
2217 	 * There are several call sites (backref walking, qgroup, and data
2218 	 * reloc) passing 0 as @root_owner, as they are not holding the
2219 	 * tree root.  In that case, we can not do a reliable ownership check,
2220 	 * so just exit.
2221 	 */
2222 	if (root_owner == 0)
2223 		return 0;
2224 	/*
2225 	 * These trees use key.offset as their owner, our callers don't have
2226 	 * the extra capacity to pass key.offset here.  So we just skip them.
2227 	 */
2228 	if (root_owner == BTRFS_TREE_LOG_OBJECTID ||
2229 	    root_owner == BTRFS_TREE_RELOC_OBJECTID)
2230 		return 0;
2231 
2232 	if (!is_subvol) {
2233 		/* For non-subvolume trees, the eb owner should match root owner */
2234 		if (unlikely(root_owner != eb_owner)) {
2235 			btrfs_crit(eb->fs_info,
2236 "corrupted %s, root=%llu block=%llu owner mismatch, have %llu expect %llu",
2237 				btrfs_header_level(eb) == 0 ? "leaf" : "node",
2238 				root_owner, btrfs_header_bytenr(eb), eb_owner,
2239 				root_owner);
2240 			return -EUCLEAN;
2241 		}
2242 		return 0;
2243 	}
2244 
2245 	/*
2246 	 * For subvolume trees, owners can mismatch, but they should all belong
2247 	 * to subvolume trees.
2248 	 */
2249 	if (unlikely(is_subvol != btrfs_is_fstree(eb_owner))) {
2250 		btrfs_crit(eb->fs_info,
2251 "corrupted %s, root=%llu block=%llu owner mismatch, have %llu expect [%llu, %llu]",
2252 			btrfs_header_level(eb) == 0 ? "leaf" : "node",
2253 			root_owner, btrfs_header_bytenr(eb), eb_owner,
2254 			BTRFS_FIRST_FREE_OBJECTID, BTRFS_LAST_FREE_OBJECTID);
2255 		return -EUCLEAN;
2256 	}
2257 	return 0;
2258 }
2259 
btrfs_verify_level_key(struct extent_buffer * eb,const struct btrfs_tree_parent_check * check)2260 int btrfs_verify_level_key(struct extent_buffer *eb,
2261 			   const struct btrfs_tree_parent_check *check)
2262 {
2263 	struct btrfs_fs_info *fs_info = eb->fs_info;
2264 	int found_level;
2265 	struct btrfs_key found_key;
2266 	int ret;
2267 
2268 	found_level = btrfs_header_level(eb);
2269 	if (unlikely(found_level != check->level)) {
2270 		DEBUG_WARN();
2271 		btrfs_err(fs_info,
2272 "tree level mismatch detected, bytenr=%llu level expected=%u has=%u",
2273 			  eb->start, check->level, found_level);
2274 		return -EUCLEAN;
2275 	}
2276 
2277 	if (!check->has_first_key)
2278 		return 0;
2279 
2280 	/*
2281 	 * For live tree block (new tree blocks in current transaction),
2282 	 * we need proper lock context to avoid race, which is impossible here.
2283 	 * So we only checks tree blocks which is read from disk, whose
2284 	 * generation <= fs_info->last_trans_committed.
2285 	 */
2286 	if (btrfs_header_generation(eb) > btrfs_get_last_trans_committed(fs_info))
2287 		return 0;
2288 
2289 	/* We have @first_key, so this @eb must have at least one item */
2290 	if (unlikely(btrfs_header_nritems(eb) == 0)) {
2291 		btrfs_err(fs_info,
2292 		"invalid tree nritems, bytenr=%llu nritems=0 expect >0",
2293 			  eb->start);
2294 		DEBUG_WARN();
2295 		return -EUCLEAN;
2296 	}
2297 
2298 	if (found_level)
2299 		btrfs_node_key_to_cpu(eb, &found_key, 0);
2300 	else
2301 		btrfs_item_key_to_cpu(eb, &found_key, 0);
2302 
2303 	ret = btrfs_comp_cpu_keys(&check->first_key, &found_key);
2304 	if (unlikely(ret)) {
2305 		DEBUG_WARN();
2306 		btrfs_err(fs_info,
2307 "tree first key mismatch detected, bytenr=%llu parent_transid=%llu key expected=(%llu,%u,%llu) has=(%llu,%u,%llu)",
2308 			  eb->start, check->transid, check->first_key.objectid,
2309 			  check->first_key.type, check->first_key.offset,
2310 			  found_key.objectid, found_key.type,
2311 			  found_key.offset);
2312 	}
2313 	return ret;
2314 }
2315