xref: /linux/fs/btrfs/tree-checker.c (revision a6e5521ecc5e7129f1e4f4391ae4c24a75062d30)
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 	const u64 val = btrfs_file_extent_##name((leaf), (fi));               \
112 	const bool not_aligned = !IS_ALIGNED(val, (alignment));		      \
113 									      \
114 	if (unlikely(not_aligned))			      		      \
115 		file_extent_err((leaf), (slot),				      \
116 	"invalid %s for file extent, have %llu, should be aligned to %u",     \
117 			(#name), val, (alignment));			      \
118 	not_aligned;			                                      \
119 })
120 
121 static u64 file_extent_end(struct extent_buffer *leaf,
122 			   struct btrfs_key *key,
123 			   struct btrfs_file_extent_item *extent)
124 {
125 	u64 end;
126 	u64 len;
127 
128 	if (btrfs_file_extent_type(leaf, extent) == BTRFS_FILE_EXTENT_INLINE) {
129 		len = btrfs_file_extent_ram_bytes(leaf, extent);
130 		end = ALIGN(key->offset + len, leaf->fs_info->sectorsize);
131 	} else {
132 		len = btrfs_file_extent_num_bytes(leaf, extent);
133 		end = key->offset + len;
134 	}
135 	return end;
136 }
137 
138 /*
139  * Customized report for dir_item, the only new important information is
140  * key->objectid, which represents inode number
141  */
142 __printf(3, 4)
143 __cold
144 static void dir_item_err(const struct extent_buffer *eb, int slot,
145 			 const char *fmt, ...)
146 {
147 	const struct btrfs_fs_info *fs_info = eb->fs_info;
148 	struct btrfs_key key;
149 	struct va_format vaf;
150 	va_list args;
151 
152 	btrfs_item_key_to_cpu(eb, &key, slot);
153 	va_start(args, fmt);
154 
155 	vaf.fmt = fmt;
156 	vaf.va = &args;
157 
158 	dump_page(folio_page(eb->folios[0], 0), "eb page dump");
159 	btrfs_crit(fs_info,
160 		"corrupt %s: root=%llu block=%llu slot=%d ino=%llu, %pV",
161 		btrfs_header_level(eb) == 0 ? "leaf" : "node",
162 		btrfs_header_owner(eb), btrfs_header_bytenr(eb), slot,
163 		key.objectid, &vaf);
164 	va_end(args);
165 }
166 
167 /* Record info for the last hit inode. */
168 struct saved_inode_info {
169 	u64 ino;
170 	u32 mode;
171 };
172 
173 /*
174  * This functions checks prev_key->objectid, to ensure current key and prev_key
175  * share the same objectid as inode number.
176  *
177  * This is to detect missing INODE_ITEM in subvolume trees.
178  *
179  * Return true if everything is OK or we don't need to check.
180  * Return false if anything is wrong.
181  */
182 static bool check_prev_ino(struct extent_buffer *leaf,
183 			   struct btrfs_key *key, int slot,
184 			   struct btrfs_key *prev_key)
185 {
186 	/* No prev key, skip check */
187 	if (slot == 0)
188 		return true;
189 
190 	/* Only these key->types needs to be checked */
191 	ASSERT(key->type == BTRFS_XATTR_ITEM_KEY ||
192 	       key->type == BTRFS_INODE_REF_KEY ||
193 	       key->type == BTRFS_INODE_EXTREF_KEY ||
194 	       key->type == BTRFS_DIR_INDEX_KEY ||
195 	       key->type == BTRFS_DIR_ITEM_KEY ||
196 	       key->type == BTRFS_EXTENT_DATA_KEY, "key->type=%u", key->type);
197 
198 	/*
199 	 * Only subvolume trees along with their reloc trees need this check.
200 	 * Things like log tree doesn't follow this ino requirement.
201 	 */
202 	if (!btrfs_is_fstree(btrfs_header_owner(leaf)))
203 		return true;
204 
205 	if (key->objectid == prev_key->objectid)
206 		return true;
207 
208 	/* Error found */
209 	dir_item_err(leaf, slot,
210 		"invalid previous key objectid, have %llu expect %llu",
211 		prev_key->objectid, key->objectid);
212 	return false;
213 }
214 
215 static bool can_have_extent_data(struct extent_buffer *leaf,
216 				 struct btrfs_key *key, int slot, u8 fi_type,
217 				 const struct saved_inode_info *inode_info)
218 {
219 	/* No inode item in this leaf. */
220 	if (inode_info->ino != key->objectid)
221 		return true;
222 	if (S_ISREG(inode_info->mode))
223 		return true;
224 	if (S_ISLNK(inode_info->mode)) {
225 		/* For a symlink, the file extent item should always be inlined. */
226 		if (unlikely(fi_type != BTRFS_FILE_EXTENT_INLINE))
227 			return false;
228 		return true;
229 	}
230 
231 	/*
232 	 * The rest are special files, e.g. block/FIFO files, which cannot
233 	 * have any file extent.
234 	 */
235 	return false;
236 }
237 
238 static int check_extent_data_item(struct extent_buffer *leaf,
239 				  struct btrfs_key *key, int slot,
240 				  struct btrfs_key *prev_key,
241 				  const struct saved_inode_info *inode_info)
242 {
243 	struct btrfs_fs_info *fs_info = leaf->fs_info;
244 	struct btrfs_file_extent_item *fi;
245 	u32 sectorsize = fs_info->sectorsize;
246 	u32 item_size = btrfs_item_size(leaf, slot);
247 	u64 extent_end;
248 	u8 fi_type;
249 
250 	if (unlikely(!IS_ALIGNED(key->offset, sectorsize))) {
251 		file_extent_err(leaf, slot,
252 "unaligned file_offset for file extent, have %llu should be aligned to %u",
253 			key->offset, sectorsize);
254 		return -EUCLEAN;
255 	}
256 
257 	/*
258 	 * Previous key must have the same key->objectid (ino).
259 	 * It can be XATTR_ITEM, INODE_ITEM or just another EXTENT_DATA.
260 	 * But if objectids mismatch, it means we have a missing
261 	 * INODE_ITEM.
262 	 */
263 	if (unlikely(!check_prev_ino(leaf, key, slot, prev_key)))
264 		return -EUCLEAN;
265 
266 	fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
267 
268 	/*
269 	 * Make sure the item contains at least inline header, so the file
270 	 * extent type is not some garbage.
271 	 */
272 	if (unlikely(item_size < BTRFS_FILE_EXTENT_INLINE_DATA_START)) {
273 		file_extent_err(leaf, slot,
274 				"invalid item size, have %u expect [%zu, %u)",
275 				item_size, BTRFS_FILE_EXTENT_INLINE_DATA_START,
276 				SZ_4K);
277 		return -EUCLEAN;
278 	}
279 	fi_type = btrfs_file_extent_type(leaf, fi);
280 	if (unlikely(fi_type >= BTRFS_NR_FILE_EXTENT_TYPES)) {
281 		file_extent_err(leaf, slot,
282 		"invalid type for file extent, have %u expect range [0, %u]",
283 			fi_type, BTRFS_NR_FILE_EXTENT_TYPES - 1);
284 		return -EUCLEAN;
285 	}
286 
287 	if (unlikely(!can_have_extent_data(leaf, key, slot, fi_type, inode_info))) {
288 		file_extent_err(leaf, slot,
289 				"unexpected file extent item type %u for inode mode 0%o",
290 				fi_type, inode_info->mode);
291 		return -EUCLEAN;
292 	}
293 
294 	/*
295 	 * Support for new compression/encryption must introduce incompat flag,
296 	 * and must be caught in open_ctree().
297 	 */
298 	if (unlikely(btrfs_file_extent_compression(leaf, fi) >=
299 		     BTRFS_NR_COMPRESS_TYPES)) {
300 		file_extent_err(leaf, slot,
301 	"invalid compression for file extent, have %u expect range [0, %u]",
302 			btrfs_file_extent_compression(leaf, fi),
303 			BTRFS_NR_COMPRESS_TYPES - 1);
304 		return -EUCLEAN;
305 	}
306 	if (unlikely(btrfs_file_extent_encryption(leaf, fi))) {
307 		file_extent_err(leaf, slot,
308 			"invalid encryption for file extent, have %u expect 0",
309 			btrfs_file_extent_encryption(leaf, fi));
310 		return -EUCLEAN;
311 	}
312 
313 	if (fi_type == BTRFS_FILE_EXTENT_INLINE) {
314 		/* Inline extent must have 0 as key offset */
315 		if (unlikely(key->offset)) {
316 			file_extent_err(leaf, slot,
317 		"invalid file_offset for inline file extent, have %llu expect 0",
318 				key->offset);
319 			return -EUCLEAN;
320 		}
321 
322 		/* Compressed inline extent has no on-disk size, skip it */
323 		if (btrfs_file_extent_compression(leaf, fi) !=
324 		    BTRFS_COMPRESS_NONE)
325 			return 0;
326 
327 		/* Uncompressed inline extent size must match item size */
328 		if (unlikely(item_size != BTRFS_FILE_EXTENT_INLINE_DATA_START +
329 					  btrfs_file_extent_ram_bytes(leaf, fi))) {
330 			file_extent_err(leaf, slot,
331 	"invalid ram_bytes for uncompressed inline extent, have %u expect %llu",
332 				item_size, BTRFS_FILE_EXTENT_INLINE_DATA_START +
333 				btrfs_file_extent_ram_bytes(leaf, fi));
334 			return -EUCLEAN;
335 		}
336 		return 0;
337 	}
338 
339 	/*
340 	 * For the data reloc tree, file extent items are written by
341 	 * relocation's own paths. The data reloc inode is created with
342 	 * BTRFS_INODE_NOCOMPRESS, so insert_ordered_extent_file_extent()
343 	 * always leaves the compression field at 0. Encryption and
344 	 * other_encoding are reserved-and-zero in btrfs. A non-zero value
345 	 * for any of these means the leaf decoded from disk does not match
346 	 * what the kernel wrote, i.e. on-disk corruption.
347 	 *
348 	 * The file_extent_item's offset field is NOT a universal invariant
349 	 * here: partial-PREALLOC writebacks legitimately produce REG items
350 	 * with non-zero offset at non-boundary keys. The offset check is
351 	 * performed at the call site in get_new_location(), which only
352 	 * inspects cluster-boundary keys where offset is always 0.
353 	 */
354 	if (unlikely(btrfs_header_owner(leaf) == BTRFS_DATA_RELOC_TREE_OBJECTID &&
355 		     (btrfs_file_extent_compression(leaf, fi) ||
356 		      btrfs_file_extent_encryption(leaf, fi) ||
357 		      btrfs_file_extent_other_encoding(leaf, fi)))) {
358 		file_extent_err(leaf, slot,
359 "invalid encoding fields for data reloc tree, compression=%u encryption=%u other_encoding=%u",
360 				btrfs_file_extent_compression(leaf, fi),
361 				btrfs_file_extent_encryption(leaf, fi),
362 				btrfs_file_extent_other_encoding(leaf, fi));
363 		return -EUCLEAN;
364 	}
365 
366 	/* Regular or preallocated extent has fixed item size */
367 	if (unlikely(item_size != sizeof(*fi))) {
368 		file_extent_err(leaf, slot,
369 	"invalid item size for reg/prealloc file extent, have %u expect %zu",
370 			item_size, sizeof(*fi));
371 		return -EUCLEAN;
372 	}
373 	if (unlikely(CHECK_FE_ALIGNED(leaf, slot, fi, ram_bytes, sectorsize) ||
374 		     CHECK_FE_ALIGNED(leaf, slot, fi, disk_bytenr, sectorsize) ||
375 		     CHECK_FE_ALIGNED(leaf, slot, fi, disk_num_bytes, sectorsize) ||
376 		     CHECK_FE_ALIGNED(leaf, slot, fi, offset, sectorsize) ||
377 		     CHECK_FE_ALIGNED(leaf, slot, fi, num_bytes, sectorsize)))
378 		return -EUCLEAN;
379 
380 	/* Catch extent end overflow */
381 	if (unlikely(check_add_overflow(btrfs_file_extent_num_bytes(leaf, fi),
382 					key->offset, &extent_end))) {
383 		file_extent_err(leaf, slot,
384 	"extent end overflow, have file offset %llu extent num bytes %llu",
385 				key->offset,
386 				btrfs_file_extent_num_bytes(leaf, fi));
387 		return -EUCLEAN;
388 	}
389 
390 	/*
391 	 * Check that no two consecutive file extent items, in the same leaf,
392 	 * present ranges that overlap each other.
393 	 */
394 	if (slot > 0 &&
395 	    prev_key->objectid == key->objectid &&
396 	    prev_key->type == BTRFS_EXTENT_DATA_KEY) {
397 		struct btrfs_file_extent_item *prev_fi;
398 		u64 prev_end;
399 
400 		prev_fi = btrfs_item_ptr(leaf, slot - 1,
401 					 struct btrfs_file_extent_item);
402 		prev_end = file_extent_end(leaf, prev_key, prev_fi);
403 		if (unlikely(prev_end > key->offset)) {
404 			file_extent_err(leaf, slot - 1,
405 "file extent end range (%llu) goes beyond start offset (%llu) of the next file extent",
406 					prev_end, key->offset);
407 			return -EUCLEAN;
408 		}
409 	}
410 
411 	/*
412 	 * For non-compressed data extents, ram_bytes should match its
413 	 * disk_num_bytes.
414 	 * However we do not really utilize ram_bytes in this case, so this check
415 	 * is only optional for DEBUG builds for developers to catch the
416 	 * unexpected behaviors.
417 	 */
418 	if (IS_ENABLED(CONFIG_BTRFS_DEBUG) &&
419 	    btrfs_file_extent_compression(leaf, fi) == BTRFS_COMPRESS_NONE &&
420 	    btrfs_file_extent_disk_bytenr(leaf, fi)) {
421 		if (WARN_ON(btrfs_file_extent_ram_bytes(leaf, fi) !=
422 			    btrfs_file_extent_disk_num_bytes(leaf, fi)))
423 			file_extent_err(leaf, slot,
424 "mismatch ram_bytes (%llu) and disk_num_bytes (%llu) for non-compressed extent",
425 					btrfs_file_extent_ram_bytes(leaf, fi),
426 					btrfs_file_extent_disk_num_bytes(leaf, fi));
427 	}
428 
429 	return 0;
430 }
431 
432 static int check_csum_item(struct extent_buffer *leaf, struct btrfs_key *key,
433 			   int slot, struct btrfs_key *prev_key)
434 {
435 	struct btrfs_fs_info *fs_info = leaf->fs_info;
436 	u32 sectorsize = fs_info->sectorsize;
437 	const u32 csumsize = fs_info->csum_size;
438 
439 	if (unlikely(key->objectid != BTRFS_EXTENT_CSUM_OBJECTID)) {
440 		generic_err(leaf, slot,
441 		"invalid key objectid for csum item, have %llu expect %llu",
442 			key->objectid, BTRFS_EXTENT_CSUM_OBJECTID);
443 		return -EUCLEAN;
444 	}
445 	if (unlikely(!IS_ALIGNED(key->offset, sectorsize))) {
446 		generic_err(leaf, slot,
447 	"unaligned key offset for csum item, have %llu should be aligned to %u",
448 			key->offset, sectorsize);
449 		return -EUCLEAN;
450 	}
451 	if (unlikely(!IS_ALIGNED(btrfs_item_size(leaf, slot), csumsize))) {
452 		generic_err(leaf, slot,
453 	"unaligned item size for csum item, have %u should be aligned to %u",
454 			btrfs_item_size(leaf, slot), csumsize);
455 		return -EUCLEAN;
456 	}
457 	if (slot > 0 && prev_key->type == BTRFS_EXTENT_CSUM_KEY) {
458 		u64 prev_csum_end;
459 		u32 prev_item_size;
460 
461 		prev_item_size = btrfs_item_size(leaf, slot - 1);
462 		prev_csum_end = (prev_item_size / csumsize) * sectorsize;
463 		prev_csum_end += prev_key->offset;
464 		if (unlikely(prev_csum_end > key->offset)) {
465 			generic_err(leaf, slot - 1,
466 "csum end range (%llu) goes beyond the start range (%llu) of the next csum item",
467 				    prev_csum_end, key->offset);
468 			return -EUCLEAN;
469 		}
470 	}
471 	return 0;
472 }
473 
474 /* Inode item error output has the same format as dir_item_err() */
475 #define inode_item_err(eb, slot, fmt, ...)			\
476 	dir_item_err(eb, slot, fmt, __VA_ARGS__)
477 
478 static int check_inode_key(struct extent_buffer *leaf, struct btrfs_key *key,
479 			   int slot)
480 {
481 	struct btrfs_key item_key;
482 	bool is_inode_item;
483 
484 	btrfs_item_key_to_cpu(leaf, &item_key, slot);
485 	is_inode_item = (item_key.type == BTRFS_INODE_ITEM_KEY);
486 
487 	/* For XATTR_ITEM, location key should be all 0 */
488 	if (item_key.type == BTRFS_XATTR_ITEM_KEY) {
489 		if (unlikely(key->objectid != 0 || key->type != 0 ||
490 			     key->offset != 0))
491 			return -EUCLEAN;
492 		return 0;
493 	}
494 
495 	if (unlikely((key->objectid < BTRFS_FIRST_FREE_OBJECTID ||
496 		      key->objectid > BTRFS_LAST_FREE_OBJECTID) &&
497 		     key->objectid != BTRFS_ROOT_TREE_DIR_OBJECTID &&
498 		     key->objectid != BTRFS_FREE_INO_OBJECTID)) {
499 		if (is_inode_item) {
500 			generic_err(leaf, slot,
501 	"invalid key objectid: has %llu expect %llu or [%llu, %llu] or %llu",
502 				key->objectid, BTRFS_ROOT_TREE_DIR_OBJECTID,
503 				BTRFS_FIRST_FREE_OBJECTID,
504 				BTRFS_LAST_FREE_OBJECTID,
505 				BTRFS_FREE_INO_OBJECTID);
506 		} else {
507 			dir_item_err(leaf, slot,
508 "invalid location key objectid: has %llu expect %llu or [%llu, %llu] or %llu",
509 				key->objectid, BTRFS_ROOT_TREE_DIR_OBJECTID,
510 				BTRFS_FIRST_FREE_OBJECTID,
511 				BTRFS_LAST_FREE_OBJECTID,
512 				BTRFS_FREE_INO_OBJECTID);
513 		}
514 		return -EUCLEAN;
515 	}
516 	if (unlikely(key->offset != 0)) {
517 		if (is_inode_item)
518 			inode_item_err(leaf, slot,
519 				       "invalid key offset: has %llu expect 0",
520 				       key->offset);
521 		else
522 			dir_item_err(leaf, slot,
523 				"invalid location key offset:has %llu expect 0",
524 				key->offset);
525 		return -EUCLEAN;
526 	}
527 	return 0;
528 }
529 
530 static int check_root_key(struct extent_buffer *leaf, struct btrfs_key *key,
531 			  int slot)
532 {
533 	struct btrfs_key item_key;
534 	bool is_root_item;
535 
536 	btrfs_item_key_to_cpu(leaf, &item_key, slot);
537 	is_root_item = (item_key.type == BTRFS_ROOT_ITEM_KEY);
538 
539 	/*
540 	 * Bad rootid for reloc trees.
541 	 *
542 	 * Reloc trees are only for subvolume trees, other trees only need
543 	 * to be COWed to be relocated.
544 	 */
545 	if (unlikely(is_root_item && key->objectid == BTRFS_TREE_RELOC_OBJECTID &&
546 		     !btrfs_is_fstree(key->offset))) {
547 		generic_err(leaf, slot,
548 		"invalid reloc tree for root %lld, root id is not a subvolume tree",
549 			    key->offset);
550 		return -EUCLEAN;
551 	}
552 
553 	/* No such tree id */
554 	if (unlikely(key->objectid == 0)) {
555 		if (is_root_item)
556 			generic_err(leaf, slot, "invalid root id 0");
557 		else
558 			dir_item_err(leaf, slot,
559 				     "invalid location key root id 0");
560 		return -EUCLEAN;
561 	}
562 
563 	/* DIR_ITEM/INDEX/INODE_REF is not allowed to point to non-fs trees */
564 	if (unlikely(!btrfs_is_fstree(key->objectid) && !is_root_item)) {
565 		dir_item_err(leaf, slot,
566 		"invalid location key objectid, have %llu expect [%llu, %llu]",
567 				key->objectid, BTRFS_FIRST_FREE_OBJECTID,
568 				BTRFS_LAST_FREE_OBJECTID);
569 		return -EUCLEAN;
570 	}
571 
572 	/*
573 	 * ROOT_ITEM with non-zero offset means this is a snapshot, created at
574 	 * @offset transid.
575 	 * Furthermore, for location key in DIR_ITEM, its offset is always -1.
576 	 *
577 	 * So here we only check offset for reloc tree whose key->offset must
578 	 * be a valid tree.
579 	 */
580 	if (unlikely(key->objectid == BTRFS_TREE_RELOC_OBJECTID &&
581 		     key->offset == 0)) {
582 		generic_err(leaf, slot, "invalid root id 0 for reloc tree");
583 		return -EUCLEAN;
584 	}
585 	return 0;
586 }
587 
588 static int check_dir_item(struct extent_buffer *leaf,
589 			  struct btrfs_key *key, struct btrfs_key *prev_key,
590 			  int slot)
591 {
592 	struct btrfs_fs_info *fs_info = leaf->fs_info;
593 	struct btrfs_dir_item *di;
594 	u32 item_size = btrfs_item_size(leaf, slot);
595 	u32 cur = 0;
596 
597 	if (unlikely(!check_prev_ino(leaf, key, slot, prev_key)))
598 		return -EUCLEAN;
599 
600 	di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
601 	while (cur < item_size) {
602 		struct btrfs_key location_key;
603 		u32 name_len;
604 		u32 data_len;
605 		u32 max_name_len;
606 		u32 total_size;
607 		u32 name_hash;
608 		u8 dir_type;
609 		int ret;
610 
611 		/* header itself should not cross item boundary */
612 		if (unlikely(cur + sizeof(*di) > item_size)) {
613 			dir_item_err(leaf, slot,
614 		"dir item header crosses item boundary, have %zu boundary %u",
615 				cur + sizeof(*di), item_size);
616 			return -EUCLEAN;
617 		}
618 
619 		/* Location key check */
620 		btrfs_dir_item_key_to_cpu(leaf, di, &location_key);
621 		if (location_key.type == BTRFS_ROOT_ITEM_KEY) {
622 			ret = check_root_key(leaf, &location_key, slot);
623 			if (unlikely(ret < 0))
624 				return ret;
625 		} else if (location_key.type == BTRFS_INODE_ITEM_KEY ||
626 			   location_key.type == 0) {
627 			ret = check_inode_key(leaf, &location_key, slot);
628 			if (unlikely(ret < 0))
629 				return ret;
630 		} else {
631 			dir_item_err(leaf, slot,
632 			"invalid location key type, have %u, expect %u or %u",
633 				     location_key.type, BTRFS_ROOT_ITEM_KEY,
634 				     BTRFS_INODE_ITEM_KEY);
635 			return -EUCLEAN;
636 		}
637 
638 		/* dir type check */
639 		dir_type = btrfs_dir_ftype(leaf, di);
640 		if (unlikely(dir_type <= BTRFS_FT_UNKNOWN ||
641 			     dir_type >= BTRFS_FT_MAX)) {
642 			dir_item_err(leaf, slot,
643 			"invalid dir item type, have %u expect (0, %u)",
644 				dir_type, BTRFS_FT_MAX);
645 			return -EUCLEAN;
646 		}
647 
648 		if (unlikely(key->type == BTRFS_XATTR_ITEM_KEY &&
649 			     dir_type != BTRFS_FT_XATTR)) {
650 			dir_item_err(leaf, slot,
651 		"invalid dir item type for XATTR key, have %u expect %u",
652 				dir_type, BTRFS_FT_XATTR);
653 			return -EUCLEAN;
654 		}
655 		if (unlikely(dir_type == BTRFS_FT_XATTR &&
656 			     key->type != BTRFS_XATTR_ITEM_KEY)) {
657 			dir_item_err(leaf, slot,
658 			"xattr dir type found for non-XATTR key");
659 			return -EUCLEAN;
660 		}
661 		if (dir_type == BTRFS_FT_XATTR)
662 			max_name_len = XATTR_NAME_MAX;
663 		else
664 			max_name_len = BTRFS_NAME_LEN;
665 
666 		/* Name/data length check */
667 		name_len = btrfs_dir_name_len(leaf, di);
668 		data_len = btrfs_dir_data_len(leaf, di);
669 		if (unlikely(name_len > max_name_len)) {
670 			dir_item_err(leaf, slot,
671 			"dir item name len too long, have %u max %u",
672 				name_len, max_name_len);
673 			return -EUCLEAN;
674 		}
675 		if (unlikely(name_len + data_len > BTRFS_MAX_XATTR_SIZE(fs_info))) {
676 			dir_item_err(leaf, slot,
677 			"dir item name and data len too long, have %u max %u",
678 				name_len + data_len,
679 				BTRFS_MAX_XATTR_SIZE(fs_info));
680 			return -EUCLEAN;
681 		}
682 
683 		if (unlikely(data_len && dir_type != BTRFS_FT_XATTR)) {
684 			dir_item_err(leaf, slot,
685 			"dir item with invalid data len, have %u expect 0",
686 				data_len);
687 			return -EUCLEAN;
688 		}
689 
690 		total_size = sizeof(*di) + name_len + data_len;
691 
692 		/* header and name/data should not cross item boundary */
693 		if (unlikely(cur + total_size > item_size)) {
694 			dir_item_err(leaf, slot,
695 		"dir item data crosses item boundary, have %u boundary %u",
696 				cur + total_size, item_size);
697 			return -EUCLEAN;
698 		}
699 
700 		/*
701 		 * Special check for XATTR/DIR_ITEM, as key->offset is name
702 		 * hash, should match its name
703 		 */
704 		if (key->type == BTRFS_DIR_ITEM_KEY ||
705 		    key->type == BTRFS_XATTR_ITEM_KEY) {
706 			char namebuf[MAX(BTRFS_NAME_LEN, XATTR_NAME_MAX)];
707 
708 			read_extent_buffer(leaf, namebuf,
709 					(unsigned long)(di + 1), name_len);
710 			name_hash = btrfs_name_hash(namebuf, name_len);
711 			if (unlikely(key->offset != name_hash)) {
712 				dir_item_err(leaf, slot,
713 		"name hash mismatch with key, have 0x%016x expect 0x%016llx",
714 					name_hash, key->offset);
715 				return -EUCLEAN;
716 			}
717 		}
718 		cur += total_size;
719 		di = (struct btrfs_dir_item *)((void *)di + total_size);
720 	}
721 	return 0;
722 }
723 
724 __printf(3, 4)
725 __cold
726 static void block_group_err(const struct extent_buffer *eb, int slot,
727 			    const char *fmt, ...)
728 {
729 	const struct btrfs_fs_info *fs_info = eb->fs_info;
730 	struct btrfs_key key;
731 	struct va_format vaf;
732 	va_list args;
733 
734 	btrfs_item_key_to_cpu(eb, &key, slot);
735 	va_start(args, fmt);
736 
737 	vaf.fmt = fmt;
738 	vaf.va = &args;
739 
740 	dump_page(folio_page(eb->folios[0], 0), "eb page dump");
741 	btrfs_crit(fs_info,
742 	"corrupt %s: root=%llu block=%llu slot=%d bg_start=%llu bg_len=%llu, %pV",
743 		btrfs_header_level(eb) == 0 ? "leaf" : "node",
744 		btrfs_header_owner(eb), btrfs_header_bytenr(eb), slot,
745 		key.objectid, key.offset, &vaf);
746 	va_end(args);
747 }
748 
749 static int check_block_group_item(struct extent_buffer *leaf,
750 				  struct btrfs_key *key, int slot)
751 {
752 	struct btrfs_fs_info *fs_info = leaf->fs_info;
753 	struct btrfs_block_group_item bgi;
754 	u32 item_size = btrfs_item_size(leaf, slot);
755 	u64 chunk_objectid;
756 	u64 flags;
757 	u64 type;
758 	size_t exp_size;
759 
760 	/*
761 	 * Here we don't really care about alignment since extent allocator can
762 	 * handle it.  We care more about the size.
763 	 */
764 	if (unlikely(key->offset == 0)) {
765 		block_group_err(leaf, slot,
766 				"invalid block group size 0");
767 		return -EUCLEAN;
768 	}
769 
770 	if (btrfs_fs_incompat(fs_info, REMAP_TREE))
771 		exp_size = sizeof(struct btrfs_block_group_item_v2);
772 	else
773 		exp_size = sizeof(struct btrfs_block_group_item);
774 
775 	if (unlikely(item_size != exp_size)) {
776 		block_group_err(leaf, slot,
777 			"invalid item size, have %u expect %zu",
778 				item_size, exp_size);
779 		return -EUCLEAN;
780 	}
781 
782 	read_extent_buffer(leaf, &bgi, btrfs_item_ptr_offset(leaf, slot),
783 			   sizeof(bgi));
784 	chunk_objectid = btrfs_stack_block_group_chunk_objectid(&bgi);
785 	if (btrfs_fs_incompat(fs_info, EXTENT_TREE_V2)) {
786 		/*
787 		 * We don't init the nr_global_roots until we load the global
788 		 * roots, so this could be 0 at mount time.  If it's 0 we'll
789 		 * just assume we're fine, and later we'll check against our
790 		 * actual value.
791 		 */
792 		if (unlikely(fs_info->nr_global_roots &&
793 			     chunk_objectid >= fs_info->nr_global_roots)) {
794 			block_group_err(leaf, slot,
795 	"invalid block group global root id, have %llu, needs to be <= %llu",
796 					chunk_objectid,
797 					fs_info->nr_global_roots);
798 			return -EUCLEAN;
799 		}
800 	} else if (unlikely(chunk_objectid != BTRFS_FIRST_CHUNK_TREE_OBJECTID)) {
801 		block_group_err(leaf, slot,
802 		"invalid block group chunk objectid, have %llu expect %llu",
803 				btrfs_stack_block_group_chunk_objectid(&bgi),
804 				BTRFS_FIRST_CHUNK_TREE_OBJECTID);
805 		return -EUCLEAN;
806 	}
807 
808 	if (unlikely(btrfs_stack_block_group_used(&bgi) > key->offset)) {
809 		block_group_err(leaf, slot,
810 			"invalid block group used, have %llu expect [0, %llu)",
811 				btrfs_stack_block_group_used(&bgi), key->offset);
812 		return -EUCLEAN;
813 	}
814 
815 	flags = btrfs_stack_block_group_flags(&bgi);
816 	if (unlikely(hweight64(flags & BTRFS_BLOCK_GROUP_PROFILE_MASK) > 1)) {
817 		block_group_err(leaf, slot,
818 "invalid profile flags, have 0x%llx (%lu bits set) expect no more than 1 bit set",
819 			flags & BTRFS_BLOCK_GROUP_PROFILE_MASK,
820 			hweight64(flags & BTRFS_BLOCK_GROUP_PROFILE_MASK));
821 		return -EUCLEAN;
822 	}
823 
824 	if (unlikely(flags & BTRFS_BLOCK_GROUP_METADATA_REMAP &&
825 		     !btrfs_fs_incompat(fs_info, REMAP_TREE))) {
826 		block_group_err(leaf, slot,
827 "invalid flags, have 0x%llx (METADATA_REMAP flag set) but no remap-tree incompat flag",
828 				flags);
829 		return -EUCLEAN;
830 	}
831 
832 	type = flags & BTRFS_BLOCK_GROUP_TYPE_MASK;
833 	if (unlikely(type != BTRFS_BLOCK_GROUP_DATA &&
834 		     type != BTRFS_BLOCK_GROUP_METADATA &&
835 		     type != BTRFS_BLOCK_GROUP_SYSTEM &&
836 		     type != BTRFS_BLOCK_GROUP_METADATA_REMAP &&
837 		     type != (BTRFS_BLOCK_GROUP_METADATA |
838 			      BTRFS_BLOCK_GROUP_DATA))) {
839 		block_group_err(leaf, slot,
840 "invalid type, have 0x%llx (%lu bits set) expect either 0x%llx, 0x%llx, 0x%llx, 0x%llx or 0x%llx",
841 			type, hweight64(type),
842 			BTRFS_BLOCK_GROUP_DATA, BTRFS_BLOCK_GROUP_METADATA,
843 			BTRFS_BLOCK_GROUP_SYSTEM, BTRFS_BLOCK_GROUP_METADATA_REMAP,
844 			BTRFS_BLOCK_GROUP_METADATA | BTRFS_BLOCK_GROUP_DATA);
845 		return -EUCLEAN;
846 	}
847 
848 	if (unlikely(!btrfs_fs_incompat(fs_info, REMAP_TREE) &&
849 		     type == BTRFS_BLOCK_GROUP_METADATA_REMAP)) {
850 		block_group_err(leaf, slot,
851 		"invalid type, METADATA_REMAP set but REMAP_TREE incompat flag not set");
852 		return -EUCLEAN;
853 	}
854 
855 	if (unlikely(!btrfs_fs_incompat(fs_info, REMAP_TREE) &&
856 		     flags & BTRFS_BLOCK_GROUP_REMAPPED)) {
857 		block_group_err(leaf, slot,
858 		"invalid flags, REMAPPED set but REMAP_TREE incompat flag not set");
859 		return -EUCLEAN;
860 	}
861 
862 	if (item_size == sizeof(struct btrfs_block_group_item_v2)) {
863 		struct btrfs_block_group_item_v2 *bgi2;
864 		u64 remap_bytes;
865 		u32 identity_remap_count;
866 
867 		bgi2 = btrfs_item_ptr(leaf, slot, struct btrfs_block_group_item_v2);
868 		remap_bytes = btrfs_block_group_v2_remap_bytes(leaf, bgi2);
869 
870 		if (unlikely(remap_bytes > key->offset)) {
871 			block_group_err(leaf, slot,
872 				"invalid remap_bytes, have %llu expect [0, %llu]",
873 					remap_bytes, key->offset);
874 			return -EUCLEAN;
875 		}
876 
877 		identity_remap_count = btrfs_block_group_v2_identity_remap_count(leaf, bgi2);
878 		if (unlikely((u64)identity_remap_count >
879 			     key->offset >> fs_info->sectorsize_bits)) {
880 			block_group_err(leaf, slot,
881 				"invalid identity_remap_count, have %u expect [0, %llu]",
882 					identity_remap_count,
883 					key->offset >> fs_info->sectorsize_bits);
884 			return -EUCLEAN;
885 		}
886 	}
887 
888 	return 0;
889 }
890 
891 __printf(5, 6)
892 __cold
893 static void chunk_err(const struct btrfs_fs_info *fs_info,
894 		      const struct extent_buffer *leaf,
895 		      const struct btrfs_chunk *chunk, u64 logical,
896 		      const char *fmt, ...)
897 {
898 	bool is_sb = !leaf;
899 	struct va_format vaf;
900 	va_list args;
901 	int i;
902 	int slot = -1;
903 
904 	if (!is_sb) {
905 		/*
906 		 * Get the slot number by iterating through all slots, this
907 		 * would provide better readability.
908 		 */
909 		for (i = 0; i < btrfs_header_nritems(leaf); i++) {
910 			if (btrfs_item_ptr_offset(leaf, i) ==
911 					(unsigned long)chunk) {
912 				slot = i;
913 				break;
914 			}
915 		}
916 	}
917 	va_start(args, fmt);
918 	vaf.fmt = fmt;
919 	vaf.va = &args;
920 
921 	if (is_sb)
922 		btrfs_crit(fs_info,
923 		"corrupt superblock syschunk array: chunk_start=%llu, %pV",
924 			   logical, &vaf);
925 	else
926 		btrfs_crit(fs_info,
927 	"corrupt leaf: root=%llu block=%llu slot=%d chunk_start=%llu, %pV",
928 			   BTRFS_CHUNK_TREE_OBJECTID, leaf->start, slot,
929 			   logical, &vaf);
930 	va_end(args);
931 }
932 
933 static bool valid_stripe_count(u64 profile, u16 num_stripes, u16 sub_stripes)
934 {
935 	switch (profile) {
936 	case BTRFS_BLOCK_GROUP_RAID0:
937 		return true;
938 	case BTRFS_BLOCK_GROUP_RAID10:
939 		return sub_stripes == btrfs_raid_array[BTRFS_RAID_RAID10].sub_stripes;
940 	case BTRFS_BLOCK_GROUP_RAID1:
941 		return num_stripes == btrfs_raid_array[BTRFS_RAID_RAID1].devs_min;
942 	case BTRFS_BLOCK_GROUP_RAID1C3:
943 		return num_stripes == btrfs_raid_array[BTRFS_RAID_RAID1C3].devs_min;
944 	case BTRFS_BLOCK_GROUP_RAID1C4:
945 		return num_stripes == btrfs_raid_array[BTRFS_RAID_RAID1C4].devs_min;
946 	case BTRFS_BLOCK_GROUP_RAID5:
947 		return num_stripes >= btrfs_raid_array[BTRFS_RAID_RAID5].devs_min;
948 	case BTRFS_BLOCK_GROUP_RAID6:
949 		return num_stripes >= btrfs_raid_array[BTRFS_RAID_RAID6].devs_min;
950 	case BTRFS_BLOCK_GROUP_DUP:
951 		return num_stripes == btrfs_raid_array[BTRFS_RAID_DUP].dev_stripes;
952 	case 0: /* SINGLE */
953 		return num_stripes == btrfs_raid_array[BTRFS_RAID_SINGLE].dev_stripes;
954 	default:
955 		BUG();
956 	}
957 }
958 
959 /*
960  * The common chunk check which could also work on super block sys chunk array.
961  *
962  * If @leaf is NULL, then @chunk must be an on-stack chunk item.
963  * (For superblock sys_chunk array, and fs_info->sectorsize is unreliable)
964  *
965  * Return -EUCLEAN if anything is corrupted.
966  * Return 0 if everything is OK.
967  */
968 int btrfs_check_chunk_valid(const struct btrfs_fs_info *fs_info,
969 			    const struct extent_buffer *leaf,
970 			    const struct btrfs_chunk *chunk, u64 logical,
971 			    u32 sectorsize)
972 {
973 	u64 length;
974 	u64 chunk_end;
975 	u64 stripe_len;
976 	u16 num_stripes;
977 	u16 sub_stripes;
978 	u64 type;
979 	u64 features;
980 	u32 chunk_sector_size;
981 	bool mixed = false;
982 	bool remapped;
983 	int raid_index;
984 	int nparity;
985 	int ncopies;
986 
987 	if (leaf) {
988 		length = btrfs_chunk_length(leaf, chunk);
989 		stripe_len = btrfs_chunk_stripe_len(leaf, chunk);
990 		num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
991 		sub_stripes = btrfs_chunk_sub_stripes(leaf, chunk);
992 		type = btrfs_chunk_type(leaf, chunk);
993 		chunk_sector_size = btrfs_chunk_sector_size(leaf, chunk);
994 	} else {
995 		length = btrfs_stack_chunk_length(chunk);
996 		stripe_len = btrfs_stack_chunk_stripe_len(chunk);
997 		num_stripes = btrfs_stack_chunk_num_stripes(chunk);
998 		sub_stripes = btrfs_stack_chunk_sub_stripes(chunk);
999 		type = btrfs_stack_chunk_type(chunk);
1000 		chunk_sector_size = btrfs_stack_chunk_sector_size(chunk);
1001 	}
1002 	raid_index = btrfs_bg_flags_to_raid_index(type);
1003 	ncopies = btrfs_raid_array[raid_index].ncopies;
1004 	nparity = btrfs_raid_array[raid_index].nparity;
1005 	remapped = (type & BTRFS_BLOCK_GROUP_REMAPPED);
1006 
1007 	if (unlikely(!remapped && !num_stripes)) {
1008 		chunk_err(fs_info, leaf, chunk, logical,
1009 			  "invalid chunk num_stripes, have %u", num_stripes);
1010 		return -EUCLEAN;
1011 	}
1012 	if (unlikely(num_stripes != 0 && num_stripes < ncopies)) {
1013 		chunk_err(fs_info, leaf, chunk, logical,
1014 			  "invalid chunk num_stripes < ncopies, have %u < %d",
1015 			  num_stripes, ncopies);
1016 		return -EUCLEAN;
1017 	}
1018 	if (unlikely(nparity && num_stripes == nparity)) {
1019 		chunk_err(fs_info, leaf, chunk, logical,
1020 			  "invalid chunk num_stripes == nparity, have %u == %d",
1021 			  num_stripes, nparity);
1022 		return -EUCLEAN;
1023 	}
1024 	if (unlikely(!IS_ALIGNED(logical, sectorsize))) {
1025 		chunk_err(fs_info, leaf, chunk, logical,
1026 		"invalid chunk logical, have %llu should aligned to %u",
1027 			  logical, sectorsize);
1028 		return -EUCLEAN;
1029 	}
1030 	if (unlikely(chunk_sector_size != sectorsize)) {
1031 		chunk_err(fs_info, leaf, chunk, logical,
1032 			  "invalid chunk sectorsize, have %u expect %u",
1033 			  chunk_sector_size, sectorsize);
1034 		return -EUCLEAN;
1035 	}
1036 	if (unlikely(!length || !IS_ALIGNED(length, sectorsize))) {
1037 		chunk_err(fs_info, leaf, chunk, logical,
1038 			  "invalid chunk length, have %llu", length);
1039 		return -EUCLEAN;
1040 	}
1041 	if (unlikely(check_add_overflow(logical, length, &chunk_end))) {
1042 		chunk_err(fs_info, leaf, chunk, logical,
1043 "invalid chunk logical start and length, have logical start %llu length %llu",
1044 			  logical, length);
1045 		return -EUCLEAN;
1046 	}
1047 	if (unlikely(!is_power_of_2(stripe_len) || stripe_len != BTRFS_STRIPE_LEN)) {
1048 		chunk_err(fs_info, leaf, chunk, logical,
1049 			  "invalid chunk stripe length: %llu",
1050 			  stripe_len);
1051 		return -EUCLEAN;
1052 	}
1053 	/*
1054 	 * We artificially limit the chunk size, so that the number of stripes
1055 	 * inside a chunk can be fit into a U32.  The current limit (256G) is
1056 	 * way too large for real world usage anyway, and it's also much larger
1057 	 * than our existing limit (10G).
1058 	 *
1059 	 * Thus it should be a good way to catch obvious bitflips.
1060 	 */
1061 	if (unlikely(length >= btrfs_stripe_nr_to_offset(U32_MAX))) {
1062 		chunk_err(fs_info, leaf, chunk, logical,
1063 			  "chunk length too large: have %llu limit %llu",
1064 			  length, btrfs_stripe_nr_to_offset(U32_MAX));
1065 		return -EUCLEAN;
1066 	}
1067 	if (unlikely(type & ~BTRFS_BLOCK_GROUP_VALID)) {
1068 		chunk_err(fs_info, leaf, chunk, logical,
1069 			  "unrecognized chunk type: 0x%llx",
1070 			  type & ~BTRFS_BLOCK_GROUP_VALID);
1071 		return -EUCLEAN;
1072 	}
1073 
1074 	if (unlikely(!has_single_bit_set(type & BTRFS_BLOCK_GROUP_PROFILE_MASK) &&
1075 		     (type & BTRFS_BLOCK_GROUP_PROFILE_MASK) != 0)) {
1076 		chunk_err(fs_info, leaf, chunk, logical,
1077 		"invalid chunk profile flag: 0x%llx, expect 0 or 1 bit set",
1078 			  type & BTRFS_BLOCK_GROUP_PROFILE_MASK);
1079 		return -EUCLEAN;
1080 	}
1081 	if (unlikely((type & BTRFS_BLOCK_GROUP_TYPE_MASK) == 0)) {
1082 		chunk_err(fs_info, leaf, chunk, logical,
1083 	"missing chunk type flag, have 0x%llx one bit must be set in 0x%llx",
1084 			  type, BTRFS_BLOCK_GROUP_TYPE_MASK);
1085 		return -EUCLEAN;
1086 	}
1087 
1088 	if (unlikely((type & BTRFS_BLOCK_GROUP_SYSTEM) &&
1089 		     (type & (BTRFS_BLOCK_GROUP_METADATA |
1090 			      BTRFS_BLOCK_GROUP_DATA)))) {
1091 		chunk_err(fs_info, leaf, chunk, logical,
1092 			  "system chunk with data or metadata type: 0x%llx",
1093 			  type);
1094 		return -EUCLEAN;
1095 	}
1096 
1097 	features = btrfs_super_incompat_flags(fs_info->super_copy);
1098 	if (features & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
1099 		mixed = true;
1100 
1101 	if (!mixed) {
1102 		if (unlikely((type & BTRFS_BLOCK_GROUP_METADATA) &&
1103 			     (type & BTRFS_BLOCK_GROUP_DATA))) {
1104 			chunk_err(fs_info, leaf, chunk, logical,
1105 			"mixed chunk type in non-mixed mode: 0x%llx", type);
1106 			return -EUCLEAN;
1107 		}
1108 	}
1109 
1110 	if (unlikely((type & BTRFS_BLOCK_GROUP_METADATA_REMAP) &&
1111 		     !(features & BTRFS_FEATURE_INCOMPAT_REMAP_TREE))) {
1112 		chunk_err(fs_info, leaf, chunk, logical,
1113 		"METADATA_REMAP chunk type without REMAP_TREE incompat bit");
1114 		return -EUCLEAN;
1115 	}
1116 
1117 	if (unlikely(remapped &&
1118 		     !(features & BTRFS_FEATURE_INCOMPAT_REMAP_TREE))) {
1119 		chunk_err(fs_info, leaf, chunk, logical,
1120 		"REMAPPED chunk flag without REMAP_TREE incompat bit");
1121 		return -EUCLEAN;
1122 	}
1123 
1124 	if (unlikely(!remapped &&
1125 		     !valid_stripe_count(type & BTRFS_BLOCK_GROUP_PROFILE_MASK,
1126 					 num_stripes, sub_stripes))) {
1127 		chunk_err(fs_info, leaf, chunk, logical,
1128 			"invalid num_stripes:sub_stripes %u:%u for profile %llu",
1129 			num_stripes, sub_stripes,
1130 			type & BTRFS_BLOCK_GROUP_PROFILE_MASK);
1131 		return -EUCLEAN;
1132 	}
1133 
1134 	return 0;
1135 }
1136 
1137 /*
1138  * Enhanced version of chunk item checker.
1139  *
1140  * The common btrfs_check_chunk_valid() doesn't check item size since it needs
1141  * to work on super block sys_chunk_array which doesn't have full item ptr.
1142  */
1143 static int check_leaf_chunk_item(struct extent_buffer *leaf,
1144 				 struct btrfs_chunk *chunk,
1145 				 struct btrfs_key *key, int slot)
1146 {
1147 	struct btrfs_fs_info *fs_info = leaf->fs_info;
1148 	int num_stripes;
1149 
1150 	if (unlikely(btrfs_item_size(leaf, slot) < offsetof(struct btrfs_chunk, stripe))) {
1151 		chunk_err(fs_info, leaf, chunk, key->offset,
1152 			"invalid chunk item size: have %u expect [%zu, %u)",
1153 			btrfs_item_size(leaf, slot),
1154 			offsetof(struct btrfs_chunk, stripe),
1155 			BTRFS_LEAF_DATA_SIZE(fs_info));
1156 		return -EUCLEAN;
1157 	}
1158 
1159 	num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
1160 	/* Let btrfs_check_chunk_valid() handle this error type */
1161 	if (num_stripes == 0)
1162 		goto out;
1163 
1164 	if (unlikely(btrfs_chunk_item_size(num_stripes) !=
1165 		     btrfs_item_size(leaf, slot))) {
1166 		chunk_err(fs_info, leaf, chunk, key->offset,
1167 			"invalid chunk item size: have %u expect %lu",
1168 			btrfs_item_size(leaf, slot),
1169 			btrfs_chunk_item_size(num_stripes));
1170 		return -EUCLEAN;
1171 	}
1172 out:
1173 	return btrfs_check_chunk_valid(fs_info, leaf, chunk, key->offset,
1174 				       fs_info->sectorsize);
1175 }
1176 
1177 __printf(3, 4)
1178 __cold
1179 static void dev_item_err(const struct extent_buffer *eb, int slot,
1180 			 const char *fmt, ...)
1181 {
1182 	struct btrfs_key key;
1183 	struct va_format vaf;
1184 	va_list args;
1185 
1186 	btrfs_item_key_to_cpu(eb, &key, slot);
1187 	va_start(args, fmt);
1188 
1189 	vaf.fmt = fmt;
1190 	vaf.va = &args;
1191 
1192 	dump_page(folio_page(eb->folios[0], 0), "eb page dump");
1193 	btrfs_crit(eb->fs_info,
1194 	"corrupt %s: root=%llu block=%llu slot=%d devid=%llu %pV",
1195 		btrfs_header_level(eb) == 0 ? "leaf" : "node",
1196 		btrfs_header_owner(eb), btrfs_header_bytenr(eb), slot,
1197 		key.objectid, &vaf);
1198 	va_end(args);
1199 }
1200 
1201 static int check_dev_item(struct extent_buffer *leaf,
1202 			  struct btrfs_key *key, int slot)
1203 {
1204 	struct btrfs_dev_item *ditem;
1205 	const u32 item_size = btrfs_item_size(leaf, slot);
1206 
1207 	if (unlikely(key->objectid != BTRFS_DEV_ITEMS_OBJECTID)) {
1208 		dev_item_err(leaf, slot,
1209 			     "invalid objectid: has=%llu expect=%llu",
1210 			     key->objectid, BTRFS_DEV_ITEMS_OBJECTID);
1211 		return -EUCLEAN;
1212 	}
1213 
1214 	if (unlikely(item_size != sizeof(*ditem))) {
1215 		dev_item_err(leaf, slot, "invalid item size: has %u expect %zu",
1216 			     item_size, sizeof(*ditem));
1217 		return -EUCLEAN;
1218 	}
1219 
1220 	ditem = btrfs_item_ptr(leaf, slot, struct btrfs_dev_item);
1221 	if (unlikely(btrfs_device_id(leaf, ditem) != key->offset)) {
1222 		dev_item_err(leaf, slot,
1223 			     "devid mismatch: key has=%llu item has=%llu",
1224 			     key->offset, btrfs_device_id(leaf, ditem));
1225 		return -EUCLEAN;
1226 	}
1227 
1228 	/*
1229 	 * For device total_bytes, we don't have reliable way to check it, as
1230 	 * it can be 0 for device removal. Device size check can only be done
1231 	 * by dev extents check.
1232 	 */
1233 	if (unlikely(btrfs_device_bytes_used(leaf, ditem) >
1234 		     btrfs_device_total_bytes(leaf, ditem))) {
1235 		dev_item_err(leaf, slot,
1236 			     "invalid bytes used: have %llu expect [0, %llu]",
1237 			     btrfs_device_bytes_used(leaf, ditem),
1238 			     btrfs_device_total_bytes(leaf, ditem));
1239 		return -EUCLEAN;
1240 	}
1241 	/*
1242 	 * Remaining members like io_align/type/gen/dev_group aren't really
1243 	 * utilized.  Skip them to make later usage of them easier.
1244 	 */
1245 	return 0;
1246 }
1247 
1248 static int check_inode_item(struct extent_buffer *leaf,
1249 			    struct btrfs_key *key, int slot,
1250 			    struct saved_inode_info *inode_info)
1251 {
1252 	struct btrfs_fs_info *fs_info = leaf->fs_info;
1253 	struct btrfs_inode_item *iitem;
1254 	u64 super_gen = btrfs_super_generation(fs_info->super_copy);
1255 	u32 valid_mask = (S_IFMT | S_ISUID | S_ISGID | S_ISVTX | 0777);
1256 	const u32 item_size = btrfs_item_size(leaf, slot);
1257 	u32 mode;
1258 	int ret;
1259 	u32 flags;
1260 	u32 ro_flags;
1261 
1262 	ret = check_inode_key(leaf, key, slot);
1263 	if (unlikely(ret < 0))
1264 		return ret;
1265 
1266 	if (unlikely(item_size != sizeof(*iitem))) {
1267 		generic_err(leaf, slot, "invalid item size: has %u expect %zu",
1268 			    item_size, sizeof(*iitem));
1269 		return -EUCLEAN;
1270 	}
1271 
1272 	iitem = btrfs_item_ptr(leaf, slot, struct btrfs_inode_item);
1273 
1274 	/* Here we use super block generation + 1 to handle log tree */
1275 	if (unlikely(btrfs_inode_generation(leaf, iitem) > super_gen + 1)) {
1276 		inode_item_err(leaf, slot,
1277 			"invalid inode generation: has %llu expect (0, %llu]",
1278 			       btrfs_inode_generation(leaf, iitem),
1279 			       super_gen + 1);
1280 		return -EUCLEAN;
1281 	}
1282 	/* Note for ROOT_TREE_DIR_ITEM, mkfs could set its transid 0 */
1283 	if (unlikely(btrfs_inode_transid(leaf, iitem) > super_gen + 1)) {
1284 		inode_item_err(leaf, slot,
1285 			"invalid inode transid: has %llu expect [0, %llu]",
1286 			       btrfs_inode_transid(leaf, iitem), super_gen + 1);
1287 		return -EUCLEAN;
1288 	}
1289 
1290 	/*
1291 	 * For size and nbytes it's better not to be too strict, as for dir
1292 	 * item its size/nbytes can easily get wrong, but doesn't affect
1293 	 * anything in the fs. So here we skip the check.
1294 	 */
1295 	mode = btrfs_inode_mode(leaf, iitem);
1296 	if (unlikely(mode & ~valid_mask)) {
1297 		inode_item_err(leaf, slot,
1298 			       "unknown mode bit detected: 0x%x",
1299 			       mode & ~valid_mask);
1300 		return -EUCLEAN;
1301 	}
1302 
1303 	/*
1304 	 * S_IFMT is not bit mapped so we can't completely rely on
1305 	 * is_power_of_2/has_single_bit_set, but it can save us from checking
1306 	 * FIFO/CHR/DIR/REG.  Only needs to check BLK, LNK and SOCKS
1307 	 */
1308 	if (!has_single_bit_set(mode & S_IFMT)) {
1309 		if (unlikely(!S_ISLNK(mode) && !S_ISBLK(mode) && !S_ISSOCK(mode))) {
1310 			inode_item_err(leaf, slot,
1311 			"invalid mode: has 0%o expect valid S_IF* bit(s)",
1312 				       mode & S_IFMT);
1313 			return -EUCLEAN;
1314 		}
1315 	}
1316 	if (unlikely(S_ISDIR(mode) && btrfs_inode_nlink(leaf, iitem) > 1)) {
1317 		inode_item_err(leaf, slot,
1318 		       "invalid nlink: has %u expect no more than 1 for dir",
1319 			btrfs_inode_nlink(leaf, iitem));
1320 		return -EUCLEAN;
1321 	}
1322 	btrfs_inode_split_flags(btrfs_inode_flags(leaf, iitem), &flags, &ro_flags);
1323 	if (unlikely(flags & ~BTRFS_INODE_FLAG_MASK)) {
1324 		inode_item_err(leaf, slot,
1325 			       "unknown incompat flags detected: 0x%x", flags);
1326 		return -EUCLEAN;
1327 	}
1328 	if (unlikely(!sb_rdonly(fs_info->sb) &&
1329 		     (ro_flags & ~BTRFS_INODE_RO_FLAG_MASK))) {
1330 		inode_item_err(leaf, slot,
1331 			"unknown ro-compat flags detected on writeable mount: 0x%x",
1332 			ro_flags);
1333 		return -EUCLEAN;
1334 	}
1335 	inode_info->ino = key->objectid;
1336 	inode_info->mode = mode;
1337 	return 0;
1338 }
1339 
1340 static int check_root_item(struct extent_buffer *leaf, struct btrfs_key *key,
1341 			   int slot)
1342 {
1343 	struct btrfs_fs_info *fs_info = leaf->fs_info;
1344 	struct btrfs_root_item ri = { 0 };
1345 	const u64 valid_root_flags = BTRFS_ROOT_SUBVOL_RDONLY |
1346 				     BTRFS_ROOT_SUBVOL_DEAD;
1347 	int ret;
1348 
1349 	ret = check_root_key(leaf, key, slot);
1350 	if (unlikely(ret < 0))
1351 		return ret;
1352 
1353 	if (unlikely(btrfs_item_size(leaf, slot) != sizeof(ri) &&
1354 		     btrfs_item_size(leaf, slot) !=
1355 		     btrfs_legacy_root_item_size())) {
1356 		generic_err(leaf, slot,
1357 			    "invalid root item size, have %u expect %zu or %u",
1358 			    btrfs_item_size(leaf, slot), sizeof(ri),
1359 			    btrfs_legacy_root_item_size());
1360 		return -EUCLEAN;
1361 	}
1362 
1363 	/*
1364 	 * For legacy root item, the members starting at generation_v2 will be
1365 	 * all filled with 0.
1366 	 * And since we allow generation_v2 as 0, it will still pass the check.
1367 	 */
1368 	read_extent_buffer(leaf, &ri, btrfs_item_ptr_offset(leaf, slot),
1369 			   btrfs_item_size(leaf, slot));
1370 
1371 	/* Generation related */
1372 	if (unlikely(btrfs_root_generation(&ri) >
1373 		     btrfs_super_generation(fs_info->super_copy) + 1)) {
1374 		generic_err(leaf, slot,
1375 			"invalid root generation, have %llu expect (0, %llu]",
1376 			    btrfs_root_generation(&ri),
1377 			    btrfs_super_generation(fs_info->super_copy) + 1);
1378 		return -EUCLEAN;
1379 	}
1380 	if (unlikely(btrfs_root_generation_v2(&ri) >
1381 		     btrfs_super_generation(fs_info->super_copy) + 1)) {
1382 		generic_err(leaf, slot,
1383 		"invalid root v2 generation, have %llu expect (0, %llu]",
1384 			    btrfs_root_generation_v2(&ri),
1385 			    btrfs_super_generation(fs_info->super_copy) + 1);
1386 		return -EUCLEAN;
1387 	}
1388 	if (unlikely(btrfs_root_last_snapshot(&ri) >
1389 		     btrfs_super_generation(fs_info->super_copy) + 1)) {
1390 		generic_err(leaf, slot,
1391 		"invalid root last_snapshot, have %llu expect (0, %llu]",
1392 			    btrfs_root_last_snapshot(&ri),
1393 			    btrfs_super_generation(fs_info->super_copy) + 1);
1394 		return -EUCLEAN;
1395 	}
1396 
1397 	/* Alignment and level check */
1398 	if (unlikely(!IS_ALIGNED(btrfs_root_bytenr(&ri), fs_info->sectorsize))) {
1399 		generic_err(leaf, slot,
1400 		"invalid root bytenr, have %llu expect to be aligned to %u",
1401 			    btrfs_root_bytenr(&ri), fs_info->sectorsize);
1402 		return -EUCLEAN;
1403 	}
1404 	if (unlikely(btrfs_root_level(&ri) >= BTRFS_MAX_LEVEL)) {
1405 		generic_err(leaf, slot,
1406 			    "invalid root level, have %u expect [0, %u]",
1407 			    btrfs_root_level(&ri), BTRFS_MAX_LEVEL - 1);
1408 		return -EUCLEAN;
1409 	}
1410 	if (unlikely(btrfs_root_drop_level(&ri) >= BTRFS_MAX_LEVEL)) {
1411 		generic_err(leaf, slot,
1412 			    "invalid root drop_level, have %u expect [0, %u]",
1413 			    btrfs_root_drop_level(&ri), BTRFS_MAX_LEVEL - 1);
1414 		return -EUCLEAN;
1415 	}
1416 	/*
1417 	 * If drop_progress.objectid is non-zero, a btrfs_drop_snapshot() was
1418 	 * interrupted and the resume point was recorded in drop_progress and
1419 	 * drop_level.  In that case drop_level must be >= 1: level 0 is the
1420 	 * leaf level and drop_snapshot never saves a checkpoint there (it
1421 	 * only records checkpoints at internal node levels in DROP_REFERENCE
1422 	 * stage).  A zero drop_level combined with a non-zero drop_progress
1423 	 * objectid indicates on-disk corruption and would cause a BUG_ON in
1424 	 * merge_reloc_root() and btrfs_drop_snapshot() at mount time.
1425 	 */
1426 	if (unlikely(btrfs_disk_key_objectid(&ri.drop_progress) != 0 &&
1427 		     btrfs_root_drop_level(&ri) == 0)) {
1428 		generic_err(leaf, slot,
1429 			    "invalid root drop_level 0 with non-zero drop_progress objectid %llu",
1430 			    btrfs_disk_key_objectid(&ri.drop_progress));
1431 		return -EUCLEAN;
1432 	}
1433 
1434 	/* Flags check */
1435 	if (unlikely(btrfs_root_flags(&ri) & ~valid_root_flags)) {
1436 		generic_err(leaf, slot,
1437 			    "invalid root flags, have 0x%llx expect mask 0x%llx",
1438 			    btrfs_root_flags(&ri), valid_root_flags);
1439 		return -EUCLEAN;
1440 	}
1441 	return 0;
1442 }
1443 
1444 static int check_root_ref(struct extent_buffer *leaf, struct btrfs_key *key, int slot)
1445 {
1446 	struct btrfs_root_ref *rref;
1447 	u32 item_size = btrfs_item_size(leaf, slot);
1448 	u32 name_len;
1449 
1450 	if (unlikely(item_size <= sizeof(*rref))) {
1451 		generic_err(leaf, slot,
1452 			    "invalid root ref item size for key type %u, have %u expect > %zu",
1453 			    key->type, item_size, sizeof(*rref));
1454 		return -EUCLEAN;
1455 	}
1456 
1457 	rref = btrfs_item_ptr(leaf, slot, struct btrfs_root_ref);
1458 	name_len = btrfs_root_ref_name_len(leaf, rref);
1459 	if (unlikely(name_len > BTRFS_NAME_LEN)) {
1460 		generic_err(leaf, slot,
1461 			    "root ref name too long for key type %u, have %u max %u",
1462 			    key->type, name_len, BTRFS_NAME_LEN);
1463 		return -EUCLEAN;
1464 	}
1465 	if (unlikely(item_size != sizeof(*rref) + name_len)) {
1466 		generic_err(leaf, slot,
1467 			    "invalid root ref item size for key type %u, have %u expect %zu",
1468 			    key->type, item_size, sizeof(*rref) + name_len);
1469 		return -EUCLEAN;
1470 	}
1471 
1472 	return 0;
1473 }
1474 
1475 __printf(3,4)
1476 __cold
1477 static void extent_err(const struct extent_buffer *eb, int slot,
1478 		       const char *fmt, ...)
1479 {
1480 	struct btrfs_key key;
1481 	struct va_format vaf;
1482 	va_list args;
1483 	u64 bytenr;
1484 	u64 len;
1485 
1486 	btrfs_item_key_to_cpu(eb, &key, slot);
1487 	bytenr = key.objectid;
1488 	if (key.type == BTRFS_METADATA_ITEM_KEY ||
1489 	    key.type == BTRFS_TREE_BLOCK_REF_KEY ||
1490 	    key.type == BTRFS_SHARED_BLOCK_REF_KEY)
1491 		len = eb->fs_info->nodesize;
1492 	else
1493 		len = key.offset;
1494 	va_start(args, fmt);
1495 
1496 	vaf.fmt = fmt;
1497 	vaf.va = &args;
1498 
1499 	dump_page(folio_page(eb->folios[0], 0), "eb page dump");
1500 	btrfs_crit(eb->fs_info,
1501 	"corrupt %s: block=%llu slot=%d extent bytenr=%llu len=%llu %pV",
1502 		btrfs_header_level(eb) == 0 ? "leaf" : "node",
1503 		eb->start, slot, bytenr, len, &vaf);
1504 	va_end(args);
1505 }
1506 
1507 static bool is_valid_dref_root(u64 rootid)
1508 {
1509 	/*
1510 	 * The following tree root objectids are allowed to have a data backref:
1511 	 * - subvolume trees
1512 	 * - data reloc tree
1513 	 * - tree root
1514 	 *   For v1 space cache
1515 	 */
1516 	return btrfs_is_fstree(rootid) || rootid == BTRFS_DATA_RELOC_TREE_OBJECTID ||
1517 	       rootid == BTRFS_ROOT_TREE_OBJECTID;
1518 }
1519 
1520 static int check_extent_item(struct extent_buffer *leaf,
1521 			     struct btrfs_key *key, int slot,
1522 			     struct btrfs_key *prev_key)
1523 {
1524 	struct btrfs_fs_info *fs_info = leaf->fs_info;
1525 	struct btrfs_extent_item *ei;
1526 	bool is_tree_block = false;
1527 	unsigned long ptr;	/* Current pointer inside inline refs */
1528 	unsigned long end;	/* Extent item end */
1529 	const u32 item_size = btrfs_item_size(leaf, slot);
1530 	u8 last_type = 0;
1531 	u64 last_seq = U64_MAX;
1532 	u64 flags;
1533 	u64 generation;
1534 	u64 total_refs;		/* Total refs in btrfs_extent_item */
1535 	u64 inline_refs = 0;	/* found total inline refs */
1536 
1537 	if (unlikely(key->type == BTRFS_METADATA_ITEM_KEY &&
1538 		     !btrfs_fs_incompat(fs_info, SKINNY_METADATA))) {
1539 		generic_err(leaf, slot,
1540 "invalid key type, METADATA_ITEM type invalid when SKINNY_METADATA feature disabled");
1541 		return -EUCLEAN;
1542 	}
1543 	/* key->objectid is the bytenr for both key types */
1544 	if (unlikely(!IS_ALIGNED(key->objectid, fs_info->sectorsize))) {
1545 		generic_err(leaf, slot,
1546 		"invalid key objectid, have %llu expect to be aligned to %u",
1547 			   key->objectid, fs_info->sectorsize);
1548 		return -EUCLEAN;
1549 	}
1550 
1551 	/* key->offset is tree level for METADATA_ITEM_KEY */
1552 	if (unlikely(key->type == BTRFS_METADATA_ITEM_KEY &&
1553 		     key->offset >= BTRFS_MAX_LEVEL)) {
1554 		extent_err(leaf, slot,
1555 			   "invalid tree level, have %llu expect [0, %u]",
1556 			   key->offset, BTRFS_MAX_LEVEL - 1);
1557 		return -EUCLEAN;
1558 	}
1559 
1560 	/*
1561 	 * EXTENT/METADATA_ITEM consists of:
1562 	 * 1) One btrfs_extent_item
1563 	 *    Records the total refs, type and generation of the extent.
1564 	 *
1565 	 * 2) One btrfs_tree_block_info (for EXTENT_ITEM and tree backref only)
1566 	 *    Records the first key and level of the tree block.
1567 	 *
1568 	 * 2) Zero or more btrfs_extent_inline_ref(s)
1569 	 *    Each inline ref has one btrfs_extent_inline_ref shows:
1570 	 *    2.1) The ref type, one of the 4
1571 	 *         TREE_BLOCK_REF	Tree block only
1572 	 *         SHARED_BLOCK_REF	Tree block only
1573 	 *         EXTENT_DATA_REF	Data only
1574 	 *         SHARED_DATA_REF	Data only
1575 	 *    2.2) Ref type specific data
1576 	 *         Either using btrfs_extent_inline_ref::offset, or specific
1577 	 *         data structure.
1578 	 *
1579 	 *    All above inline items should follow the order:
1580 	 *
1581 	 *    - All btrfs_extent_inline_ref::type should be in an ascending
1582 	 *      order
1583 	 *
1584 	 *    - Within the same type, the items should follow a descending
1585 	 *      order by their sequence number. The sequence number is
1586 	 *      determined by:
1587 	 *      * btrfs_extent_inline_ref::offset for all types  other than
1588 	 *        EXTENT_DATA_REF
1589 	 *      * hash_extent_data_ref() for EXTENT_DATA_REF
1590 	 */
1591 	if (unlikely(item_size < sizeof(*ei))) {
1592 		extent_err(leaf, slot,
1593 			   "invalid item size, have %u expect [%zu, %u)",
1594 			   item_size, sizeof(*ei),
1595 			   BTRFS_LEAF_DATA_SIZE(fs_info));
1596 		return -EUCLEAN;
1597 	}
1598 	end = item_size + btrfs_item_ptr_offset(leaf, slot);
1599 
1600 	/* Checks against extent_item */
1601 	ei = btrfs_item_ptr(leaf, slot, struct btrfs_extent_item);
1602 	flags = btrfs_extent_flags(leaf, ei);
1603 	total_refs = btrfs_extent_refs(leaf, ei);
1604 	generation = btrfs_extent_generation(leaf, ei);
1605 	if (unlikely(generation >
1606 		     btrfs_super_generation(fs_info->super_copy) + 1)) {
1607 		extent_err(leaf, slot,
1608 			   "invalid generation, have %llu expect (0, %llu]",
1609 			   generation,
1610 			   btrfs_super_generation(fs_info->super_copy) + 1);
1611 		return -EUCLEAN;
1612 	}
1613 	if (unlikely(!has_single_bit_set(flags & (BTRFS_EXTENT_FLAG_DATA |
1614 						  BTRFS_EXTENT_FLAG_TREE_BLOCK)))) {
1615 		extent_err(leaf, slot,
1616 		"invalid extent flag, have 0x%llx expect 1 bit set in 0x%llx",
1617 			flags, BTRFS_EXTENT_FLAG_DATA |
1618 			BTRFS_EXTENT_FLAG_TREE_BLOCK);
1619 		return -EUCLEAN;
1620 	}
1621 	is_tree_block = !!(flags & BTRFS_EXTENT_FLAG_TREE_BLOCK);
1622 	if (is_tree_block) {
1623 		if (unlikely(key->type == BTRFS_EXTENT_ITEM_KEY &&
1624 			     key->offset != fs_info->nodesize)) {
1625 			extent_err(leaf, slot,
1626 				   "invalid extent length, have %llu expect %u",
1627 				   key->offset, fs_info->nodesize);
1628 			return -EUCLEAN;
1629 		}
1630 	} else {
1631 		if (unlikely(key->type != BTRFS_EXTENT_ITEM_KEY)) {
1632 			extent_err(leaf, slot,
1633 			"invalid key type, have %u expect %u for data backref",
1634 				   key->type, BTRFS_EXTENT_ITEM_KEY);
1635 			return -EUCLEAN;
1636 		}
1637 		if (unlikely(!IS_ALIGNED(key->offset, fs_info->sectorsize))) {
1638 			extent_err(leaf, slot,
1639 			"invalid extent length, have %llu expect aligned to %u",
1640 				   key->offset, fs_info->sectorsize);
1641 			return -EUCLEAN;
1642 		}
1643 		if (unlikely(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF)) {
1644 			extent_err(leaf, slot,
1645 			"invalid extent flag, data has full backref set");
1646 			return -EUCLEAN;
1647 		}
1648 	}
1649 	ptr = (unsigned long)(struct btrfs_extent_item *)(ei + 1);
1650 
1651 	/* Check the special case of btrfs_tree_block_info */
1652 	if (is_tree_block && key->type != BTRFS_METADATA_ITEM_KEY) {
1653 		struct btrfs_tree_block_info *info;
1654 
1655 		info = (struct btrfs_tree_block_info *)ptr;
1656 		if (unlikely(btrfs_tree_block_level(leaf, info) >= BTRFS_MAX_LEVEL)) {
1657 			extent_err(leaf, slot,
1658 			"invalid tree block info level, have %u expect [0, %u]",
1659 				   btrfs_tree_block_level(leaf, info),
1660 				   BTRFS_MAX_LEVEL - 1);
1661 			return -EUCLEAN;
1662 		}
1663 		ptr = (unsigned long)(struct btrfs_tree_block_info *)(info + 1);
1664 	}
1665 
1666 	/* Check inline refs */
1667 	while (ptr < end) {
1668 		struct btrfs_extent_inline_ref *iref;
1669 		struct btrfs_extent_data_ref *dref;
1670 		struct btrfs_shared_data_ref *sref;
1671 		u64 seq;
1672 		u64 dref_root;
1673 		u64 dref_objectid;
1674 		u64 dref_offset;
1675 		u64 inline_offset;
1676 		u8 inline_type;
1677 
1678 		if (unlikely(ptr + sizeof(*iref) > end)) {
1679 			extent_err(leaf, slot,
1680 "inline ref item overflows extent item, ptr %lu iref size %zu end %lu",
1681 				   ptr, sizeof(*iref), end);
1682 			return -EUCLEAN;
1683 		}
1684 		iref = (struct btrfs_extent_inline_ref *)ptr;
1685 		inline_type = btrfs_extent_inline_ref_type(leaf, iref);
1686 		inline_offset = btrfs_extent_inline_ref_offset(leaf, iref);
1687 		seq = inline_offset;
1688 		if (unlikely(ptr + btrfs_extent_inline_ref_size(inline_type) > end)) {
1689 			extent_err(leaf, slot,
1690 "inline ref item overflows extent item, ptr %lu iref size %u end %lu",
1691 				   ptr, btrfs_extent_inline_ref_size(inline_type), end);
1692 			return -EUCLEAN;
1693 		}
1694 
1695 		switch (inline_type) {
1696 		/* inline_offset is subvolid of the owner, no need to check */
1697 		case BTRFS_TREE_BLOCK_REF_KEY:
1698 			inline_refs++;
1699 			break;
1700 		/* Contains parent bytenr */
1701 		case BTRFS_SHARED_BLOCK_REF_KEY:
1702 			if (unlikely(!IS_ALIGNED(inline_offset,
1703 						 fs_info->sectorsize))) {
1704 				extent_err(leaf, slot,
1705 		"invalid tree parent bytenr, have %llu expect aligned to %u",
1706 					   inline_offset, fs_info->sectorsize);
1707 				return -EUCLEAN;
1708 			}
1709 			inline_refs++;
1710 			break;
1711 		/*
1712 		 * Contains owner subvolid, owner key objectid, adjusted offset.
1713 		 * The only obvious corruption can happen in that offset.
1714 		 */
1715 		case BTRFS_EXTENT_DATA_REF_KEY:
1716 			dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1717 			dref_root = btrfs_extent_data_ref_root(leaf, dref);
1718 			dref_objectid = btrfs_extent_data_ref_objectid(leaf, dref);
1719 			dref_offset = btrfs_extent_data_ref_offset(leaf, dref);
1720 			seq = hash_extent_data_ref(
1721 					btrfs_extent_data_ref_root(leaf, dref),
1722 					btrfs_extent_data_ref_objectid(leaf, dref),
1723 					btrfs_extent_data_ref_offset(leaf, dref));
1724 			if (unlikely(!is_valid_dref_root(dref_root))) {
1725 				extent_err(leaf, slot,
1726 					   "invalid data ref root value %llu",
1727 					   dref_root);
1728 				return -EUCLEAN;
1729 			}
1730 			if (unlikely(dref_objectid < BTRFS_FIRST_FREE_OBJECTID ||
1731 				     dref_objectid > BTRFS_LAST_FREE_OBJECTID)) {
1732 				extent_err(leaf, slot,
1733 					   "invalid data ref objectid value %llu",
1734 					   dref_objectid);
1735 				return -EUCLEAN;
1736 			}
1737 			if (unlikely(!IS_ALIGNED(dref_offset,
1738 						 fs_info->sectorsize))) {
1739 				extent_err(leaf, slot,
1740 		"invalid data ref offset, have %llu expect aligned to %u",
1741 					   dref_offset, fs_info->sectorsize);
1742 				return -EUCLEAN;
1743 			}
1744 			if (unlikely(btrfs_extent_data_ref_count(leaf, dref) == 0)) {
1745 				extent_err(leaf, slot,
1746 			"invalid data ref count, should have non-zero value");
1747 				return -EUCLEAN;
1748 			}
1749 			inline_refs += btrfs_extent_data_ref_count(leaf, dref);
1750 			break;
1751 		/* Contains parent bytenr and ref count */
1752 		case BTRFS_SHARED_DATA_REF_KEY:
1753 			sref = (struct btrfs_shared_data_ref *)(iref + 1);
1754 			if (unlikely(!IS_ALIGNED(inline_offset,
1755 						 fs_info->sectorsize))) {
1756 				extent_err(leaf, slot,
1757 		"invalid data parent bytenr, have %llu expect aligned to %u",
1758 					   inline_offset, fs_info->sectorsize);
1759 				return -EUCLEAN;
1760 			}
1761 			if (unlikely(btrfs_shared_data_ref_count(leaf, sref) == 0)) {
1762 				extent_err(leaf, slot,
1763 			"invalid shared data ref count, should have non-zero value");
1764 				return -EUCLEAN;
1765 			}
1766 			inline_refs += btrfs_shared_data_ref_count(leaf, sref);
1767 			break;
1768 		case BTRFS_EXTENT_OWNER_REF_KEY:
1769 			WARN_ON(!btrfs_fs_incompat(fs_info, SIMPLE_QUOTA));
1770 			break;
1771 		default:
1772 			extent_err(leaf, slot, "unknown inline ref type: %u",
1773 				   inline_type);
1774 			return -EUCLEAN;
1775 		}
1776 		if (unlikely(inline_type < last_type)) {
1777 			extent_err(leaf, slot,
1778 				   "inline ref out-of-order: has type %u, prev type %u",
1779 				   inline_type, last_type);
1780 			return -EUCLEAN;
1781 		}
1782 		/* Type changed, allow the sequence starts from U64_MAX again. */
1783 		if (inline_type > last_type)
1784 			last_seq = U64_MAX;
1785 		if (unlikely(seq > last_seq)) {
1786 			extent_err(leaf, slot,
1787 "inline ref out-of-order: has type %u offset %llu seq 0x%llx, prev type %u seq 0x%llx",
1788 				   inline_type, inline_offset, seq,
1789 				   last_type, last_seq);
1790 			return -EUCLEAN;
1791 		}
1792 		last_type = inline_type;
1793 		last_seq = seq;
1794 		ptr += btrfs_extent_inline_ref_size(inline_type);
1795 	}
1796 	/* No padding is allowed */
1797 	if (unlikely(ptr != end)) {
1798 		extent_err(leaf, slot,
1799 			   "invalid extent item size, padding bytes found");
1800 		return -EUCLEAN;
1801 	}
1802 
1803 	/* Finally, check the inline refs against total refs */
1804 	if (unlikely(inline_refs > total_refs)) {
1805 		extent_err(leaf, slot,
1806 			"invalid extent refs, have %llu expect >= inline %llu",
1807 			   total_refs, inline_refs);
1808 		return -EUCLEAN;
1809 	}
1810 
1811 	if ((prev_key->type == BTRFS_EXTENT_ITEM_KEY) ||
1812 	    (prev_key->type == BTRFS_METADATA_ITEM_KEY)) {
1813 		u64 prev_end = prev_key->objectid;
1814 
1815 		if (prev_key->type == BTRFS_METADATA_ITEM_KEY)
1816 			prev_end += fs_info->nodesize;
1817 		else
1818 			prev_end += prev_key->offset;
1819 
1820 		if (unlikely(prev_end > key->objectid)) {
1821 			extent_err(leaf, slot,
1822 	"previous extent " BTRFS_KEY_FMT " overlaps current extent " BTRFS_KEY_FMT,
1823 				   BTRFS_KEY_FMT_VALUE(prev_key),
1824 				   BTRFS_KEY_FMT_VALUE(key));
1825 			return -EUCLEAN;
1826 		}
1827 	}
1828 
1829 	return 0;
1830 }
1831 
1832 static int check_simple_keyed_refs(struct extent_buffer *leaf,
1833 				   struct btrfs_key *key, int slot)
1834 {
1835 	u32 expect_item_size = 0;
1836 
1837 	if (key->type == BTRFS_SHARED_DATA_REF_KEY) {
1838 		struct btrfs_shared_data_ref *sref;
1839 
1840 		sref = btrfs_item_ptr(leaf, slot, struct btrfs_shared_data_ref);
1841 		if (unlikely(btrfs_shared_data_ref_count(leaf, sref) == 0)) {
1842 			extent_err(leaf, slot,
1843 		"invalid shared data backref count, should have non-zero value");
1844 			return -EUCLEAN;
1845 		}
1846 
1847 		expect_item_size = sizeof(struct btrfs_shared_data_ref);
1848 	}
1849 
1850 	if (unlikely(btrfs_item_size(leaf, slot) != expect_item_size)) {
1851 		generic_err(leaf, slot,
1852 		"invalid item size, have %u expect %u for key type %u",
1853 			    btrfs_item_size(leaf, slot),
1854 			    expect_item_size, key->type);
1855 		return -EUCLEAN;
1856 	}
1857 	if (unlikely(!IS_ALIGNED(key->objectid, leaf->fs_info->sectorsize))) {
1858 		generic_err(leaf, slot,
1859 "invalid key objectid for shared block ref, have %llu expect aligned to %u",
1860 			    key->objectid, leaf->fs_info->sectorsize);
1861 		return -EUCLEAN;
1862 	}
1863 	if (unlikely(key->type != BTRFS_TREE_BLOCK_REF_KEY &&
1864 		     !IS_ALIGNED(key->offset, leaf->fs_info->sectorsize))) {
1865 		extent_err(leaf, slot,
1866 		"invalid tree parent bytenr, have %llu expect aligned to %u",
1867 			   key->offset, leaf->fs_info->sectorsize);
1868 		return -EUCLEAN;
1869 	}
1870 	return 0;
1871 }
1872 
1873 static int check_extent_data_ref(struct extent_buffer *leaf,
1874 				 struct btrfs_key *key, int slot)
1875 {
1876 	struct btrfs_extent_data_ref *dref;
1877 	unsigned long ptr = btrfs_item_ptr_offset(leaf, slot);
1878 	const unsigned long end = ptr + btrfs_item_size(leaf, slot);
1879 
1880 	if (unlikely(btrfs_item_size(leaf, slot) % sizeof(*dref) != 0)) {
1881 		generic_err(leaf, slot,
1882 	"invalid item size, have %u expect aligned to %zu for key type %u",
1883 			    btrfs_item_size(leaf, slot),
1884 			    sizeof(*dref), key->type);
1885 		return -EUCLEAN;
1886 	}
1887 	if (unlikely(!IS_ALIGNED(key->objectid, leaf->fs_info->sectorsize))) {
1888 		generic_err(leaf, slot,
1889 "invalid key objectid for shared block ref, have %llu expect aligned to %u",
1890 			    key->objectid, leaf->fs_info->sectorsize);
1891 		return -EUCLEAN;
1892 	}
1893 	for (; ptr < end; ptr += sizeof(*dref)) {
1894 		u64 root;
1895 		u64 objectid;
1896 		u64 offset;
1897 
1898 		/*
1899 		 * We cannot check the extent_data_ref hash due to possible
1900 		 * overflow from the leaf due to hash collisions.
1901 		 */
1902 		dref = (struct btrfs_extent_data_ref *)ptr;
1903 		root = btrfs_extent_data_ref_root(leaf, dref);
1904 		objectid = btrfs_extent_data_ref_objectid(leaf, dref);
1905 		offset = btrfs_extent_data_ref_offset(leaf, dref);
1906 		if (unlikely(!is_valid_dref_root(root))) {
1907 			extent_err(leaf, slot,
1908 				   "invalid extent data backref root value %llu",
1909 				   root);
1910 			return -EUCLEAN;
1911 		}
1912 		if (unlikely(objectid < BTRFS_FIRST_FREE_OBJECTID ||
1913 			     objectid > BTRFS_LAST_FREE_OBJECTID)) {
1914 			extent_err(leaf, slot,
1915 				   "invalid extent data backref objectid value %llu",
1916 				   objectid);
1917 			return -EUCLEAN;
1918 		}
1919 		if (unlikely(!IS_ALIGNED(offset, leaf->fs_info->sectorsize))) {
1920 			extent_err(leaf, slot,
1921 	"invalid extent data backref offset, have %llu expect aligned to %u",
1922 				   offset, leaf->fs_info->sectorsize);
1923 			return -EUCLEAN;
1924 		}
1925 		if (unlikely(btrfs_extent_data_ref_count(leaf, dref) == 0)) {
1926 			extent_err(leaf, slot,
1927 	"invalid extent data backref count, should have non-zero value");
1928 			return -EUCLEAN;
1929 		}
1930 	}
1931 	return 0;
1932 }
1933 
1934 #define inode_ref_err(eb, slot, fmt, args...)			\
1935 	inode_item_err(eb, slot, fmt, ##args)
1936 static int check_inode_ref(struct extent_buffer *leaf,
1937 			   struct btrfs_key *key, struct btrfs_key *prev_key,
1938 			   int slot)
1939 {
1940 	struct btrfs_inode_ref *iref;
1941 	unsigned long ptr;
1942 	unsigned long end;
1943 
1944 	if (unlikely(!check_prev_ino(leaf, key, slot, prev_key)))
1945 		return -EUCLEAN;
1946 	/* namelen can't be 0, so item_size == sizeof() is also invalid */
1947 	if (unlikely(btrfs_item_size(leaf, slot) <= sizeof(*iref))) {
1948 		inode_ref_err(leaf, slot,
1949 			"invalid item size, have %u expect (%zu, %u)",
1950 			btrfs_item_size(leaf, slot),
1951 			sizeof(*iref), BTRFS_LEAF_DATA_SIZE(leaf->fs_info));
1952 		return -EUCLEAN;
1953 	}
1954 
1955 	if (unlikely(btrfs_is_fstree(btrfs_header_owner(leaf)) &&
1956 	     (key->offset < BTRFS_FIRST_FREE_OBJECTID ||
1957 	      key->offset > BTRFS_LAST_FREE_OBJECTID))) {
1958 		inode_ref_err(leaf, slot,
1959 			      "invalid offset for ref key, have %llu expect [%llu, %lld]",
1960 			      key->offset, BTRFS_FIRST_FREE_OBJECTID,
1961 			      BTRFS_LAST_FREE_OBJECTID);
1962 		return -EUCLEAN;
1963 	}
1964 
1965 	ptr = btrfs_item_ptr_offset(leaf, slot);
1966 	end = ptr + btrfs_item_size(leaf, slot);
1967 	while (ptr < end) {
1968 		u16 namelen;
1969 
1970 		if (unlikely(ptr + sizeof(*iref) > end)) {
1971 			inode_ref_err(leaf, slot,
1972 			"inode ref overflow, ptr %lu end %lu inode_ref_size %zu",
1973 				ptr, end, sizeof(*iref));
1974 			return -EUCLEAN;
1975 		}
1976 
1977 		iref = (struct btrfs_inode_ref *)ptr;
1978 		namelen = btrfs_inode_ref_name_len(leaf, iref);
1979 		if (unlikely(namelen == 0 || namelen > BTRFS_NAME_LEN)) {
1980 			inode_ref_err(leaf, slot,
1981 				"invalid inode ref name length, has %u expect [1, %u]",
1982 				namelen, BTRFS_NAME_LEN);
1983 			return -EUCLEAN;
1984 		}
1985 		if (unlikely(ptr + sizeof(*iref) + namelen > end)) {
1986 			inode_ref_err(leaf, slot,
1987 				"inode ref overflow, ptr %lu end %lu namelen %u",
1988 				ptr, end, namelen);
1989 			return -EUCLEAN;
1990 		}
1991 
1992 		/*
1993 		 * NOTE: In theory we should record all found index numbers
1994 		 * to find any duplicated indexes, but that will be too time
1995 		 * consuming for inodes with too many hard links.
1996 		 */
1997 		ptr += sizeof(*iref) + namelen;
1998 	}
1999 	return 0;
2000 }
2001 
2002 static int check_inode_extref(struct extent_buffer *leaf,
2003 			      struct btrfs_key *key, struct btrfs_key *prev_key,
2004 			      int slot)
2005 {
2006 	unsigned long ptr = btrfs_item_ptr_offset(leaf, slot);
2007 	unsigned long end = ptr + btrfs_item_size(leaf, slot);
2008 	const bool is_fstree = btrfs_is_fstree(btrfs_header_owner(leaf));
2009 
2010 	if (unlikely(!check_prev_ino(leaf, key, slot, prev_key)))
2011 		return -EUCLEAN;
2012 
2013 	while (ptr < end) {
2014 		struct btrfs_inode_extref *extref = (struct btrfs_inode_extref *)ptr;
2015 		u64 parent;
2016 		u16 namelen;
2017 
2018 		if (unlikely(ptr + sizeof(*extref) > end)) {
2019 			inode_ref_err(leaf, slot,
2020 			"inode extref overflow, ptr %lu end %lu inode_extref size %zu",
2021 				      ptr, end, sizeof(*extref));
2022 			return -EUCLEAN;
2023 		}
2024 
2025 		parent = btrfs_inode_extref_parent(leaf, extref);
2026 		if (unlikely(is_fstree && (parent < BTRFS_FIRST_FREE_OBJECTID ||
2027 					   parent > BTRFS_LAST_FREE_OBJECTID))) {
2028 			inode_ref_err(leaf, slot,
2029 		      "invalid parent for extref key, have %llu expect [%llu, %lld]",
2030 			      parent, BTRFS_FIRST_FREE_OBJECTID,
2031 				      BTRFS_LAST_FREE_OBJECTID);
2032 			return -EUCLEAN;
2033 		}
2034 
2035 		namelen = btrfs_inode_extref_name_len(leaf, extref);
2036 		if (unlikely(namelen == 0 || namelen > BTRFS_NAME_LEN)) {
2037 			inode_ref_err(leaf, slot,
2038 				"invalid inode extref name length, has %u expect [1, %u]",
2039 				namelen, BTRFS_NAME_LEN);
2040 			return -EUCLEAN;
2041 		}
2042 
2043 		if (unlikely(ptr + sizeof(*extref) + namelen > end)) {
2044 			inode_ref_err(leaf, slot,
2045 				"inode extref overflow, ptr %lu end %lu namelen %u",
2046 				ptr, end, namelen);
2047 			return -EUCLEAN;
2048 		}
2049 		ptr += sizeof(*extref) + namelen;
2050 	}
2051 	return 0;
2052 }
2053 
2054 static int check_raid_stripe_extent(const struct extent_buffer *leaf,
2055 				    const struct btrfs_key *key, int slot)
2056 {
2057 	if (unlikely(!IS_ALIGNED(key->objectid, leaf->fs_info->sectorsize))) {
2058 		generic_err(leaf, slot,
2059 "invalid key objectid for raid stripe extent, have %llu expect aligned to %u",
2060 			    key->objectid, leaf->fs_info->sectorsize);
2061 		return -EUCLEAN;
2062 	}
2063 
2064 	if (unlikely(!btrfs_fs_incompat(leaf->fs_info, RAID_STRIPE_TREE))) {
2065 		generic_err(leaf, slot,
2066 	"RAID_STRIPE_EXTENT present but RAID_STRIPE_TREE incompat bit unset");
2067 		return -EUCLEAN;
2068 	}
2069 
2070 	return 0;
2071 }
2072 
2073 static int check_remap_key(const struct extent_buffer *leaf,
2074 			   const struct btrfs_key *key, int slot)
2075 {
2076 	const u32 item_size = btrfs_item_size(leaf, slot);
2077 	const u32 sectorsize = leaf->fs_info->sectorsize;
2078 	u64 end;
2079 
2080 	if (unlikely(!btrfs_fs_incompat(leaf->fs_info, REMAP_TREE))) {
2081 		generic_err(leaf, slot,
2082 		"remap key type %u present but REMAP_TREE incompat bit unset",
2083 			    key->type);
2084 		return -EUCLEAN;
2085 	}
2086 
2087 	switch (key->type) {
2088 	case BTRFS_IDENTITY_REMAP_KEY:
2089 		if (unlikely(item_size != 0)) {
2090 			generic_err(leaf, slot,
2091 			"invalid item size for IDENTITY_REMAP, have %u expect 0",
2092 				    item_size);
2093 			return -EUCLEAN;
2094 		}
2095 	break;
2096 	case BTRFS_REMAP_KEY:
2097 	case BTRFS_REMAP_BACKREF_KEY:
2098 		if (unlikely(item_size != sizeof(struct btrfs_remap_item))) {
2099 			generic_err(leaf, slot,
2100 			"invalid item size for remap key type %u, have %u expect %zu",
2101 				    key->type, item_size,
2102 				    sizeof(struct btrfs_remap_item));
2103 			return -EUCLEAN;
2104 		}
2105 		break;
2106 	}
2107 
2108 	if (unlikely(key->offset == 0)) {
2109 		generic_err(leaf, slot,
2110 			    "invalid remap key length, have 0 expect nonzero");
2111 		return -EUCLEAN;
2112 	}
2113 
2114 	if (unlikely(!IS_ALIGNED(key->objectid, sectorsize))) {
2115 		generic_err(leaf, slot,
2116 		"invalid remap key objectid, have %llu expect aligned to %u",
2117 			    key->objectid, sectorsize);
2118 		return -EUCLEAN;
2119 	}
2120 
2121 	if (unlikely(!IS_ALIGNED(key->offset, sectorsize))) {
2122 		generic_err(leaf, slot,
2123 		"invalid remap key offset (length), have %llu expect aligned to %u",
2124 			    key->offset, sectorsize);
2125 		return -EUCLEAN;
2126 	}
2127 
2128 	if (unlikely(check_add_overflow(key->objectid, key->offset, &end))) {
2129 		generic_err(leaf, slot,
2130 		"remap key overflow, objectid %llu + offset %llu wraps",
2131 			    key->objectid, key->offset);
2132 		return -EUCLEAN;
2133 	}
2134 
2135 	return 0;
2136 }
2137 
2138 static int check_dev_extent_item(const struct extent_buffer *leaf,
2139 				 const struct btrfs_key *key,
2140 				 int slot,
2141 				 struct btrfs_key *prev_key)
2142 {
2143 	struct btrfs_dev_extent *de;
2144 	const u32 sectorsize = leaf->fs_info->sectorsize;
2145 
2146 	de = btrfs_item_ptr(leaf, slot, struct btrfs_dev_extent);
2147 	/* Basic fixed member checks. */
2148 	if (unlikely(btrfs_dev_extent_chunk_tree(leaf, de) !=
2149 		     BTRFS_CHUNK_TREE_OBJECTID)) {
2150 		generic_err(leaf, slot,
2151 			    "invalid dev extent chunk tree id, has %llu expect %llu",
2152 			    btrfs_dev_extent_chunk_tree(leaf, de),
2153 			    BTRFS_CHUNK_TREE_OBJECTID);
2154 		return -EUCLEAN;
2155 	}
2156 	if (unlikely(btrfs_dev_extent_chunk_objectid(leaf, de) !=
2157 		     BTRFS_FIRST_CHUNK_TREE_OBJECTID)) {
2158 		generic_err(leaf, slot,
2159 			    "invalid dev extent chunk objectid, has %llu expect %llu",
2160 			    btrfs_dev_extent_chunk_objectid(leaf, de),
2161 			    BTRFS_FIRST_CHUNK_TREE_OBJECTID);
2162 		return -EUCLEAN;
2163 	}
2164 	/* Alignment check. */
2165 	if (unlikely(!IS_ALIGNED(key->offset, sectorsize))) {
2166 		generic_err(leaf, slot,
2167 			    "invalid dev extent key.offset, has %llu not aligned to %u",
2168 			    key->offset, sectorsize);
2169 		return -EUCLEAN;
2170 	}
2171 	if (unlikely(!IS_ALIGNED(btrfs_dev_extent_chunk_offset(leaf, de),
2172 				 sectorsize))) {
2173 		generic_err(leaf, slot,
2174 			    "invalid dev extent chunk offset, has %llu not aligned to %u",
2175 			    btrfs_dev_extent_chunk_offset(leaf, de),
2176 			    sectorsize);
2177 		return -EUCLEAN;
2178 	}
2179 	if (unlikely(!IS_ALIGNED(btrfs_dev_extent_length(leaf, de),
2180 				 sectorsize))) {
2181 		generic_err(leaf, slot,
2182 			    "invalid dev extent length, has %llu not aligned to %u",
2183 			    btrfs_dev_extent_length(leaf, de), sectorsize);
2184 		return -EUCLEAN;
2185 	}
2186 	/* Overlap check with previous dev extent. */
2187 	if (slot && prev_key->objectid == key->objectid &&
2188 	    prev_key->type == key->type) {
2189 		struct btrfs_dev_extent *prev_de;
2190 		u64 prev_len;
2191 
2192 		prev_de = btrfs_item_ptr(leaf, slot - 1, struct btrfs_dev_extent);
2193 		prev_len = btrfs_dev_extent_length(leaf, prev_de);
2194 		if (unlikely(prev_key->offset + prev_len > key->offset)) {
2195 			generic_err(leaf, slot,
2196 		"dev extent overlap, prev offset %llu len %llu current offset %llu",
2197 				    prev_key->offset, prev_len, key->offset);
2198 			return -EUCLEAN;
2199 		}
2200 	}
2201 	return 0;
2202 }
2203 
2204 static int check_free_space_info(struct extent_buffer *leaf, struct btrfs_key *key,
2205 				 int slot)
2206 {
2207 	struct btrfs_fs_info *fs_info = leaf->fs_info;
2208 	struct btrfs_free_space_info *fsi;
2209 	const u32 blocksize = fs_info->sectorsize;
2210 	u64 end;
2211 	u32 flags;
2212 
2213 	if (unlikely(!IS_ALIGNED(key->objectid, blocksize))) {
2214 		generic_err(leaf, slot,
2215 		"free space info key objectid is not aligned to %u, has " BTRFS_KEY_FMT,
2216 			    blocksize, BTRFS_KEY_FMT_VALUE(key));
2217 		return -EUCLEAN;
2218 	}
2219 	if (unlikely(!IS_ALIGNED(key->offset, blocksize))) {
2220 		generic_err(leaf, slot,
2221 		"free space info key offset is not aligned to %u, has " BTRFS_KEY_FMT,
2222 			    blocksize, BTRFS_KEY_FMT_VALUE(key));
2223 		return -EUCLEAN;
2224 	}
2225 	if (unlikely(check_add_overflow(key->objectid, key->offset, &end))) {
2226 		generic_err(leaf, slot,
2227 			    "free space info key overflows, has " BTRFS_KEY_FMT,
2228 			    BTRFS_KEY_FMT_VALUE(key));
2229 		return -EUCLEAN;
2230 	}
2231 	if (unlikely(btrfs_item_size(leaf, slot) !=
2232 		     sizeof(struct btrfs_free_space_info))) {
2233 		generic_err(leaf, slot,
2234 		"invalid item size for free space info, has %u expect %zu",
2235 			    btrfs_item_size(leaf, slot),
2236 			    sizeof(struct btrfs_free_space_info));
2237 		return -EUCLEAN;
2238 	}
2239 	fsi = btrfs_item_ptr(leaf, slot, struct btrfs_free_space_info);
2240 	flags = btrfs_free_space_flags(leaf, fsi);
2241 	if (unlikely(flags & ~BTRFS_FREE_SPACE_FLAGS_MASK)) {
2242 		generic_err(leaf, slot,
2243 		"unknown flags for free space info, has 0x%x valid mask 0x%lx",
2244 			    flags, BTRFS_FREE_SPACE_FLAGS_MASK);
2245 		return -EUCLEAN;
2246 	}
2247 	if (unlikely(btrfs_free_space_extent_count(leaf, fsi) >
2248 		     key->offset >> fs_info->sectorsize_bits)) {
2249 		generic_err(leaf, slot,
2250 			    "suspicious extent count, has %u max valid %llu",
2251 			    btrfs_free_space_extent_count(leaf, fsi),
2252 			    key->offset >> fs_info->sectorsize_bits);
2253 		return -EUCLEAN;
2254 	}
2255 	return 0;
2256 }
2257 
2258 static int check_free_space_common_key(struct extent_buffer *leaf, struct btrfs_key *key, int slot,
2259 				       struct btrfs_key *prev_key)
2260 {
2261 	struct btrfs_fs_info *fs_info = leaf->fs_info;
2262 	const u32 blocksize = fs_info->sectorsize;
2263 	const char *type_str = (key->type == BTRFS_FREE_SPACE_EXTENT_KEY) ? "extent" : "bitmap";
2264 	u64 end;
2265 
2266 	if (unlikely(!IS_ALIGNED(key->objectid, blocksize))) {
2267 		generic_err(leaf, slot,
2268 		"free space %s key objectid is not aligned to %u, has " BTRFS_KEY_FMT,
2269 			    type_str, blocksize, BTRFS_KEY_FMT_VALUE(key));
2270 		return -EUCLEAN;
2271 	}
2272 	if (unlikely(!IS_ALIGNED(key->offset, blocksize))) {
2273 		generic_err(leaf, slot,
2274 		"free space %s key offset is not aligned to %u, has " BTRFS_KEY_FMT,
2275 			    type_str, blocksize, BTRFS_KEY_FMT_VALUE(key));
2276 		return -EUCLEAN;
2277 	}
2278 	if (unlikely(key->offset == 0)) {
2279 		generic_err(leaf, slot, "free space %s length is 0", type_str);
2280 		return -EUCLEAN;
2281 	}
2282 	if (unlikely(check_add_overflow(key->objectid, key->offset, &end))) {
2283 		generic_err(leaf, slot,
2284 			    "free space %s end overflow, have objectid %llu offset %llu",
2285 			    type_str, key->objectid, key->offset);
2286 		return -EUCLEAN;
2287 	}
2288 	if (slot == 0)
2289 		return 0;
2290 
2291 	/*
2292 	 * Make sure the current key is inside the block group, and matching
2293 	 * the expected info type.
2294 	 */
2295 	if (prev_key->type == BTRFS_FREE_SPACE_INFO_KEY) {
2296 		struct btrfs_free_space_info *fsi;
2297 		u32 info_flags;
2298 
2299 		if (unlikely(key->objectid < prev_key->objectid ||
2300 			     key->objectid + key->offset > prev_key->objectid + prev_key->offset)) {
2301 			generic_err(leaf, slot,
2302 "free space %s is not inside the space info, prev key " BTRFS_KEY_FMT " current key " BTRFS_KEY_FMT,
2303 				    type_str, BTRFS_KEY_FMT_VALUE(prev_key),
2304 				    BTRFS_KEY_FMT_VALUE(key));
2305 			return -EUCLEAN;
2306 		}
2307 		fsi = btrfs_item_ptr(leaf, slot - 1, struct btrfs_free_space_info);
2308 		info_flags = btrfs_free_space_flags(leaf, fsi);
2309 		if (unlikely((info_flags == BTRFS_FREE_SPACE_USING_BITMAPS &&
2310 			      key->type == BTRFS_FREE_SPACE_EXTENT_KEY) ||
2311 			     (info_flags != BTRFS_FREE_SPACE_USING_BITMAPS &&
2312 			      key->type == BTRFS_FREE_SPACE_BITMAP_KEY))) {
2313 			generic_err(leaf, slot,
2314 "free space %s key type is not matching the type of space info, key type %u space info flags %u",
2315 				    type_str, key->type, info_flags);
2316 			return -EUCLEAN;
2317 		}
2318 		return 0;
2319 	}
2320 	/*
2321 	 * Previous key should be either FREE_SPACE_EXTENT or FREE_SPACE_BITMAP.
2322 	 * Inside the same block group the key type should match each other, and
2323 	 * no overlaps.
2324 	 */
2325 	if (unlikely(key->type != prev_key->type)) {
2326 		generic_err(leaf, slot,
2327 "free space %s key type is not matching the type of previous key, key type %u prev key type %u",
2328 			    type_str, key->type, prev_key->type);
2329 		return -EUCLEAN;
2330 	}
2331 	if (unlikely(prev_key->objectid + prev_key->offset > key->objectid)) {
2332 		generic_err(leaf, slot,
2333 "free space %s key overlaps previous key, prev key " BTRFS_KEY_FMT " current key " BTRFS_KEY_FMT,
2334 			    type_str, BTRFS_KEY_FMT_VALUE(prev_key),
2335 			    BTRFS_KEY_FMT_VALUE(key));
2336 		return -EUCLEAN;
2337 	}
2338 	return 0;
2339 }
2340 
2341 static int check_free_space_extent(struct extent_buffer *leaf, struct btrfs_key *key, int slot,
2342 				   struct btrfs_key *prev_key)
2343 {
2344 	int ret;
2345 
2346 	ret = check_free_space_common_key(leaf, key, slot, prev_key);
2347 	if (unlikely(ret < 0))
2348 		return ret;
2349 
2350 	if (unlikely(btrfs_item_size(leaf, slot) != 0)) {
2351 		generic_err(leaf, slot,
2352 			    "invalid item size for free space extent, has %u expect 0",
2353 			    btrfs_item_size(leaf, slot));
2354 		return -EUCLEAN;
2355 	}
2356 	return 0;
2357 }
2358 
2359 static int check_free_space_bitmap(struct extent_buffer *leaf,
2360 				   struct btrfs_key *key, int slot,
2361 				   struct btrfs_key *prev_key)
2362 {
2363 	struct btrfs_fs_info *fs_info = leaf->fs_info;
2364 	u32 expected_item_size;
2365 	int ret;
2366 
2367 	ret = check_free_space_common_key(leaf, key, slot, prev_key);
2368 	if (unlikely(ret < 0))
2369 		return ret;
2370 
2371 	/*
2372 	 * The item must hold exactly the right number of bitmap bytes for the
2373 	 * range described by key->offset.  A mismatch means the item was
2374 	 * truncated or the key is corrupt; either way the bitmap data is not
2375 	 * safe to access.
2376 	 */
2377 	expected_item_size = DIV_ROUND_UP(key->offset >> fs_info->sectorsize_bits,
2378 					  BITS_PER_BYTE);
2379 	if (unlikely(btrfs_item_size(leaf, slot) != expected_item_size)) {
2380 		generic_err(leaf, slot,
2381 			    "invalid item size for free space bitmap, has %u expect %u",
2382 			    btrfs_item_size(leaf, slot), expected_item_size);
2383 		return -EUCLEAN;
2384 	}
2385 	return 0;
2386 }
2387 
2388 /*
2389  * Common point to switch the item-specific validation.
2390  */
2391 static enum btrfs_tree_block_status check_leaf_item(struct extent_buffer *leaf,
2392 						    struct btrfs_key *key,
2393 						    int slot,
2394 						    struct btrfs_key *prev_key,
2395 						    struct saved_inode_info *inode_info)
2396 {
2397 	int ret = 0;
2398 	struct btrfs_chunk *chunk;
2399 
2400 	switch (key->type) {
2401 	case BTRFS_EXTENT_DATA_KEY:
2402 		ret = check_extent_data_item(leaf, key, slot, prev_key, inode_info);
2403 		break;
2404 	case BTRFS_EXTENT_CSUM_KEY:
2405 		ret = check_csum_item(leaf, key, slot, prev_key);
2406 		break;
2407 	case BTRFS_DIR_ITEM_KEY:
2408 	case BTRFS_DIR_INDEX_KEY:
2409 	case BTRFS_XATTR_ITEM_KEY:
2410 		ret = check_dir_item(leaf, key, prev_key, slot);
2411 		break;
2412 	case BTRFS_INODE_REF_KEY:
2413 		ret = check_inode_ref(leaf, key, prev_key, slot);
2414 		break;
2415 	case BTRFS_INODE_EXTREF_KEY:
2416 		ret = check_inode_extref(leaf, key, prev_key, slot);
2417 		break;
2418 	case BTRFS_BLOCK_GROUP_ITEM_KEY:
2419 		ret = check_block_group_item(leaf, key, slot);
2420 		break;
2421 	case BTRFS_CHUNK_ITEM_KEY:
2422 		chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
2423 		ret = check_leaf_chunk_item(leaf, chunk, key, slot);
2424 		break;
2425 	case BTRFS_DEV_ITEM_KEY:
2426 		ret = check_dev_item(leaf, key, slot);
2427 		break;
2428 	case BTRFS_DEV_EXTENT_KEY:
2429 		ret = check_dev_extent_item(leaf, key, slot, prev_key);
2430 		break;
2431 	case BTRFS_INODE_ITEM_KEY:
2432 		ret = check_inode_item(leaf, key, slot, inode_info);
2433 		break;
2434 	case BTRFS_ROOT_ITEM_KEY:
2435 		ret = check_root_item(leaf, key, slot);
2436 		break;
2437 	case BTRFS_ROOT_REF_KEY:
2438 	case BTRFS_ROOT_BACKREF_KEY:
2439 		ret = check_root_ref(leaf, key, slot);
2440 		break;
2441 	case BTRFS_EXTENT_ITEM_KEY:
2442 	case BTRFS_METADATA_ITEM_KEY:
2443 		ret = check_extent_item(leaf, key, slot, prev_key);
2444 		break;
2445 	case BTRFS_TREE_BLOCK_REF_KEY:
2446 	case BTRFS_SHARED_DATA_REF_KEY:
2447 	case BTRFS_SHARED_BLOCK_REF_KEY:
2448 		ret = check_simple_keyed_refs(leaf, key, slot);
2449 		break;
2450 	case BTRFS_EXTENT_DATA_REF_KEY:
2451 		ret = check_extent_data_ref(leaf, key, slot);
2452 		break;
2453 	case BTRFS_RAID_STRIPE_KEY:
2454 		ret = check_raid_stripe_extent(leaf, key, slot);
2455 		break;
2456 	case BTRFS_FREE_SPACE_INFO_KEY:
2457 		ret = check_free_space_info(leaf, key, slot);
2458 		break;
2459 	case BTRFS_FREE_SPACE_EXTENT_KEY:
2460 		ret = check_free_space_extent(leaf, key, slot, prev_key);
2461 		break;
2462 	case BTRFS_FREE_SPACE_BITMAP_KEY:
2463 		ret = check_free_space_bitmap(leaf, key, slot, prev_key);
2464 		break;
2465 	case BTRFS_IDENTITY_REMAP_KEY:
2466 	case BTRFS_REMAP_KEY:
2467 	case BTRFS_REMAP_BACKREF_KEY:
2468 		ret = check_remap_key(leaf, key, slot);
2469 		break;
2470 	}
2471 
2472 	if (unlikely(ret))
2473 		return BTRFS_TREE_BLOCK_INVALID_ITEM;
2474 	return BTRFS_TREE_BLOCK_CLEAN;
2475 }
2476 
2477 enum btrfs_tree_block_status __btrfs_check_leaf(struct extent_buffer *leaf)
2478 {
2479 	struct btrfs_fs_info *fs_info = leaf->fs_info;
2480 	struct saved_inode_info inode_info = { 0 };
2481 	/* No valid key type is 0, so all key should be larger than this key */
2482 	struct btrfs_key prev_key = {0, 0, 0};
2483 	struct btrfs_key key;
2484 	u32 nritems = btrfs_header_nritems(leaf);
2485 	int slot;
2486 
2487 	if (unlikely(btrfs_header_level(leaf) != 0)) {
2488 		generic_err(leaf, 0,
2489 			"invalid level for leaf, have %d expect 0",
2490 			btrfs_header_level(leaf));
2491 		return BTRFS_TREE_BLOCK_INVALID_LEVEL;
2492 	}
2493 
2494 	if (unlikely(!btrfs_header_flag(leaf, BTRFS_HEADER_FLAG_WRITTEN))) {
2495 		generic_err(leaf, 0, "invalid flag for leaf, WRITTEN not set");
2496 		return BTRFS_TREE_BLOCK_WRITTEN_NOT_SET;
2497 	}
2498 
2499 	/*
2500 	 * Extent buffers from a relocation tree have a owner field that
2501 	 * corresponds to the subvolume tree they are based on. So just from an
2502 	 * extent buffer alone we can not find out what is the id of the
2503 	 * corresponding subvolume tree, so we can not figure out if the extent
2504 	 * buffer corresponds to the root of the relocation tree or not. So
2505 	 * skip this check for relocation trees.
2506 	 */
2507 	if (nritems == 0 && !btrfs_header_flag(leaf, BTRFS_HEADER_FLAG_RELOC)) {
2508 		u64 owner = btrfs_header_owner(leaf);
2509 
2510 		/* These trees must never be empty */
2511 		if (unlikely(owner == BTRFS_ROOT_TREE_OBJECTID ||
2512 			     owner == BTRFS_CHUNK_TREE_OBJECTID ||
2513 			     owner == BTRFS_DEV_TREE_OBJECTID ||
2514 			     owner == BTRFS_FS_TREE_OBJECTID ||
2515 			     owner == BTRFS_DATA_RELOC_TREE_OBJECTID)) {
2516 			generic_err(leaf, 0,
2517 			"invalid root, root %llu must never be empty",
2518 				    owner);
2519 			return BTRFS_TREE_BLOCK_INVALID_NRITEMS;
2520 		}
2521 
2522 		/* Unknown tree */
2523 		if (unlikely(owner == 0)) {
2524 			generic_err(leaf, 0,
2525 				"invalid owner, root 0 is not defined");
2526 			return BTRFS_TREE_BLOCK_INVALID_OWNER;
2527 		}
2528 
2529 		/* EXTENT_TREE_V2 can have empty extent trees. */
2530 		if (btrfs_fs_incompat(fs_info, EXTENT_TREE_V2))
2531 			return BTRFS_TREE_BLOCK_CLEAN;
2532 
2533 		if (unlikely(owner == BTRFS_EXTENT_TREE_OBJECTID)) {
2534 			generic_err(leaf, 0,
2535 			"invalid root, root %llu must never be empty",
2536 				    owner);
2537 			return BTRFS_TREE_BLOCK_INVALID_NRITEMS;
2538 		}
2539 
2540 		return BTRFS_TREE_BLOCK_CLEAN;
2541 	}
2542 
2543 	if (unlikely(nritems == 0))
2544 		return BTRFS_TREE_BLOCK_CLEAN;
2545 
2546 	/*
2547 	 * Check the following things to make sure this is a good leaf, and
2548 	 * leaf users won't need to bother with similar sanity checks:
2549 	 *
2550 	 * 1) key ordering
2551 	 * 2) item offset and size
2552 	 *    No overlap, no hole, all inside the leaf.
2553 	 * 3) item content
2554 	 *    If possible, do comprehensive sanity check.
2555 	 *    NOTE: All checks must only rely on the item data itself.
2556 	 */
2557 	for (slot = 0; slot < nritems; slot++) {
2558 		u32 item_end_expected;
2559 		u64 item_data_end;
2560 		enum btrfs_tree_block_status ret;
2561 
2562 		btrfs_item_key_to_cpu(leaf, &key, slot);
2563 
2564 		/* Make sure the keys are in the right order */
2565 		if (unlikely(btrfs_comp_cpu_keys(&prev_key, &key) >= 0)) {
2566 			generic_err(leaf, slot,
2567 	"bad key order, prev " BTRFS_KEY_FMT " current " BTRFS_KEY_FMT,
2568 				    BTRFS_KEY_FMT_VALUE(&prev_key),
2569 				    BTRFS_KEY_FMT_VALUE(&key));
2570 			return BTRFS_TREE_BLOCK_BAD_KEY_ORDER;
2571 		}
2572 
2573 		item_data_end = (u64)btrfs_item_offset(leaf, slot) +
2574 				btrfs_item_size(leaf, slot);
2575 		/*
2576 		 * Make sure the offset and ends are right, remember that the
2577 		 * item data starts at the end of the leaf and grows towards the
2578 		 * front.
2579 		 */
2580 		if (slot == 0)
2581 			item_end_expected = BTRFS_LEAF_DATA_SIZE(fs_info);
2582 		else
2583 			item_end_expected = btrfs_item_offset(leaf,
2584 								 slot - 1);
2585 		if (unlikely(item_data_end != item_end_expected)) {
2586 			generic_err(leaf, slot,
2587 				"unexpected item end, have %llu expect %u",
2588 				item_data_end, item_end_expected);
2589 			return BTRFS_TREE_BLOCK_INVALID_OFFSETS;
2590 		}
2591 
2592 		/*
2593 		 * Check to make sure that we don't point outside of the leaf,
2594 		 * just in case all the items are consistent to each other, but
2595 		 * all point outside of the leaf.
2596 		 */
2597 		if (unlikely(item_data_end > BTRFS_LEAF_DATA_SIZE(fs_info))) {
2598 			generic_err(leaf, slot,
2599 			"slot end outside of leaf, have %llu expect range [0, %u]",
2600 				item_data_end, BTRFS_LEAF_DATA_SIZE(fs_info));
2601 			return BTRFS_TREE_BLOCK_INVALID_OFFSETS;
2602 		}
2603 
2604 		/* Also check if the item pointer overlaps with btrfs item. */
2605 		if (unlikely(btrfs_item_ptr_offset(leaf, slot) <
2606 			     btrfs_item_nr_offset(leaf, slot) + sizeof(struct btrfs_item))) {
2607 			generic_err(leaf, slot,
2608 		"slot overlaps with its data, item end %lu data start %lu",
2609 				btrfs_item_nr_offset(leaf, slot) +
2610 				sizeof(struct btrfs_item),
2611 				btrfs_item_ptr_offset(leaf, slot));
2612 			return BTRFS_TREE_BLOCK_INVALID_OFFSETS;
2613 		}
2614 
2615 		/* Check if the item size and content meet other criteria. */
2616 		ret = check_leaf_item(leaf, &key, slot, &prev_key, &inode_info);
2617 		if (unlikely(ret != BTRFS_TREE_BLOCK_CLEAN))
2618 			return ret;
2619 
2620 		prev_key.objectid = key.objectid;
2621 		prev_key.type = key.type;
2622 		prev_key.offset = key.offset;
2623 	}
2624 
2625 	return BTRFS_TREE_BLOCK_CLEAN;
2626 }
2627 
2628 int btrfs_check_leaf(struct extent_buffer *leaf)
2629 {
2630 	enum btrfs_tree_block_status ret;
2631 
2632 	ret = __btrfs_check_leaf(leaf);
2633 	if (unlikely(ret != BTRFS_TREE_BLOCK_CLEAN))
2634 		return -EUCLEAN;
2635 	return 0;
2636 }
2637 ALLOW_ERROR_INJECTION(btrfs_check_leaf, ERRNO);
2638 
2639 enum btrfs_tree_block_status __btrfs_check_node(struct extent_buffer *node)
2640 {
2641 	struct btrfs_fs_info *fs_info = node->fs_info;
2642 	unsigned long nr = btrfs_header_nritems(node);
2643 	struct btrfs_key key, next_key;
2644 	int slot;
2645 	int level = btrfs_header_level(node);
2646 	u64 bytenr;
2647 
2648 	if (unlikely(!btrfs_header_flag(node, BTRFS_HEADER_FLAG_WRITTEN))) {
2649 		generic_err(node, 0, "invalid flag for node, WRITTEN not set");
2650 		return BTRFS_TREE_BLOCK_WRITTEN_NOT_SET;
2651 	}
2652 
2653 	if (unlikely(level <= 0 || level >= BTRFS_MAX_LEVEL)) {
2654 		generic_err(node, 0,
2655 			"invalid level for node, have %d expect [1, %d]",
2656 			level, BTRFS_MAX_LEVEL - 1);
2657 		return BTRFS_TREE_BLOCK_INVALID_LEVEL;
2658 	}
2659 	if (unlikely(nr == 0 || nr > BTRFS_NODEPTRS_PER_BLOCK(fs_info))) {
2660 		btrfs_crit(fs_info,
2661 "corrupt node: root=%llu block=%llu, nritems too %s, have %lu expect range [1,%u]",
2662 			   btrfs_header_owner(node), node->start,
2663 			   nr == 0 ? "small" : "large", nr,
2664 			   BTRFS_NODEPTRS_PER_BLOCK(fs_info));
2665 		return BTRFS_TREE_BLOCK_INVALID_NRITEMS;
2666 	}
2667 
2668 	for (slot = 0; slot < nr - 1; slot++) {
2669 		bytenr = btrfs_node_blockptr(node, slot);
2670 		btrfs_node_key_to_cpu(node, &key, slot);
2671 		btrfs_node_key_to_cpu(node, &next_key, slot + 1);
2672 
2673 		if (unlikely(!bytenr)) {
2674 			generic_err(node, slot,
2675 				"invalid NULL node pointer");
2676 			return BTRFS_TREE_BLOCK_INVALID_BLOCKPTR;
2677 		}
2678 		if (unlikely(!IS_ALIGNED(bytenr, fs_info->sectorsize))) {
2679 			generic_err(node, slot,
2680 			"unaligned pointer, have %llu should be aligned to %u",
2681 				bytenr, fs_info->sectorsize);
2682 			return BTRFS_TREE_BLOCK_INVALID_BLOCKPTR;
2683 		}
2684 
2685 		if (unlikely(btrfs_comp_cpu_keys(&key, &next_key) >= 0)) {
2686 			generic_err(node, slot,
2687 	"bad key order, current " BTRFS_KEY_FMT " next " BTRFS_KEY_FMT,
2688 				    BTRFS_KEY_FMT_VALUE(&key),
2689 				    BTRFS_KEY_FMT_VALUE(&next_key));
2690 			return BTRFS_TREE_BLOCK_BAD_KEY_ORDER;
2691 		}
2692 	}
2693 	return BTRFS_TREE_BLOCK_CLEAN;
2694 }
2695 
2696 int btrfs_check_node(struct extent_buffer *node)
2697 {
2698 	enum btrfs_tree_block_status ret;
2699 
2700 	ret = __btrfs_check_node(node);
2701 	if (unlikely(ret != BTRFS_TREE_BLOCK_CLEAN))
2702 		return -EUCLEAN;
2703 	return 0;
2704 }
2705 ALLOW_ERROR_INJECTION(btrfs_check_node, ERRNO);
2706 
2707 int btrfs_check_eb_owner(const struct extent_buffer *eb, u64 root_owner)
2708 {
2709 	const bool is_subvol = btrfs_is_fstree(root_owner);
2710 	const u64 eb_owner = btrfs_header_owner(eb);
2711 
2712 	/*
2713 	 * Skip dummy fs, as selftests don't create unique ebs for each dummy
2714 	 * root.
2715 	 */
2716 	if (btrfs_is_testing(eb->fs_info))
2717 		return 0;
2718 	/*
2719 	 * There are several call sites (backref walking, qgroup, and data
2720 	 * reloc) passing 0 as @root_owner, as they are not holding the
2721 	 * tree root.  In that case, we can not do a reliable ownership check,
2722 	 * so just exit.
2723 	 */
2724 	if (root_owner == 0)
2725 		return 0;
2726 	/*
2727 	 * These trees use key.offset as their owner, our callers don't have
2728 	 * the extra capacity to pass key.offset here.  So we just skip them.
2729 	 */
2730 	if (root_owner == BTRFS_TREE_LOG_OBJECTID ||
2731 	    root_owner == BTRFS_TREE_RELOC_OBJECTID)
2732 		return 0;
2733 
2734 	if (!is_subvol) {
2735 		/* For non-subvolume trees, the eb owner should match root owner */
2736 		if (unlikely(root_owner != eb_owner)) {
2737 			btrfs_crit(eb->fs_info,
2738 "corrupted %s, root=%llu block=%llu owner mismatch, have %llu expect %llu",
2739 				btrfs_header_level(eb) == 0 ? "leaf" : "node",
2740 				root_owner, btrfs_header_bytenr(eb), eb_owner,
2741 				root_owner);
2742 			return -EUCLEAN;
2743 		}
2744 		return 0;
2745 	}
2746 
2747 	/*
2748 	 * For subvolume trees, owners can mismatch, but they should all belong
2749 	 * to subvolume trees.
2750 	 */
2751 	if (unlikely(is_subvol != btrfs_is_fstree(eb_owner))) {
2752 		btrfs_crit(eb->fs_info,
2753 "corrupted %s, root=%llu block=%llu owner mismatch, have %llu expect [%llu, %llu]",
2754 			btrfs_header_level(eb) == 0 ? "leaf" : "node",
2755 			root_owner, btrfs_header_bytenr(eb), eb_owner,
2756 			BTRFS_FIRST_FREE_OBJECTID, BTRFS_LAST_FREE_OBJECTID);
2757 		return -EUCLEAN;
2758 	}
2759 	return 0;
2760 }
2761 
2762 int btrfs_verify_level_key(struct extent_buffer *eb,
2763 			   const struct btrfs_tree_parent_check *check)
2764 {
2765 	struct btrfs_fs_info *fs_info = eb->fs_info;
2766 	int found_level;
2767 	struct btrfs_key found_key;
2768 	int ret;
2769 
2770 	found_level = btrfs_header_level(eb);
2771 	if (unlikely(found_level != check->level)) {
2772 		DEBUG_WARN();
2773 		btrfs_err(fs_info,
2774 "tree level mismatch detected, bytenr=%llu level expected=%u has=%u",
2775 			  eb->start, check->level, found_level);
2776 		return -EUCLEAN;
2777 	}
2778 
2779 	if (!check->has_first_key)
2780 		return 0;
2781 
2782 	/*
2783 	 * For live tree block (new tree blocks in current transaction),
2784 	 * we need proper lock context to avoid race, which is impossible here.
2785 	 * So we only checks tree blocks which is read from disk, whose
2786 	 * generation <= fs_info->last_trans_committed.
2787 	 */
2788 	if (btrfs_header_generation(eb) > btrfs_get_last_trans_committed(fs_info))
2789 		return 0;
2790 
2791 	/* We have @first_key, so this @eb must have at least one item */
2792 	if (unlikely(btrfs_header_nritems(eb) == 0)) {
2793 		btrfs_err(fs_info,
2794 		"invalid tree nritems, bytenr=%llu nritems=0 expect >0",
2795 			  eb->start);
2796 		DEBUG_WARN();
2797 		return -EUCLEAN;
2798 	}
2799 
2800 	if (found_level)
2801 		btrfs_node_key_to_cpu(eb, &found_key, 0);
2802 	else
2803 		btrfs_item_key_to_cpu(eb, &found_key, 0);
2804 
2805 	ret = btrfs_comp_cpu_keys(&check->first_key, &found_key);
2806 	if (unlikely(ret)) {
2807 		DEBUG_WARN();
2808 		btrfs_err(fs_info,
2809 "tree first key mismatch detected, bytenr=%llu parent_transid=%llu key expected=(%llu,%u,%llu) has=(%llu,%u,%llu)",
2810 			  eb->start, check->transid, check->first_key.objectid,
2811 			  check->first_key.type, check->first_key.offset,
2812 			  found_key.objectid, found_key.type,
2813 			  found_key.offset);
2814 	}
2815 	return ret;
2816 }
2817