[PATCH 2/2] lib/btree: stop btree_get_prev() from wrapping around below key 0
From: Jyun-An Chen
Date: Sat Dec 05 2026 - 18:07:42 EST
When btree_get_prev() finds no smaller key in the leaf it descended to,
it retries the search below retry_key, the key of the last inner node
entry it followed. Inner node keys are not updated when entries are
removed, and find_level() lowers the rightmost inner key to the key it
looks for, so that key can be 0 while the tree has no entry with key 0:
after key 0 was removed, or after btree_remove() was called for a key 0
that was not in the tree. dec_key() then wraps it around to the
largest possible key, and the search starts over at the end of the
tree. A btree_for_each_safe*() loop that reaches the bottom of such a
tree never terminates.
For example, with keys 0..51 in a btree32, removing key 0 and then
walking the tree with btree_last() and btree_get_prev() returns 51..1,
then 51..1 again, without end.
There is no key below 0, so stop when retry_key is 0.
Fixes: 5db53f3e80de ("[LogFS] add new flash file system")
Signed-off-by: Jyun-An Chen <jun930436@xxxxxxxxx>
---
I used an AI coding assistant (Claude Code) to write simple tests
to check that this change works.
lib/btree.c | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/lib/btree.c b/lib/btree.c
index 3c2560173c62..c245a14c31bf 100644
--- a/lib/btree.c
+++ b/lib/btree.c
@@ -346,7 +346,7 @@ void *btree_get_prev(struct btree_head *head, struct btree_geo *geo,
}
}
miss:
- if (retry_key) {
+ if (retry_key && !keyzero(geo, retry_key)) {
longcpy(key, retry_key, geo->keylen);
retry_key = NULL;
goto retry;