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