Adopt Brent's algorithm for cycle detection #746
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
The previous cycle detection algorithm (a naive check against the largest possible tail list) is simple and gets the job done, but has the potential to take a very long time on disks with many blocks. Brent's algorithm, on the other hand, takes at most 2x the number of blocks in the tail list.
The naive cycle detection algorithm was originally chosen as I was only aware of Floyd's algorithm at the time (the classic tortoise+hare cycle detection). Floyd's algorithm is a poor fit for littlefs as it requires managing two desynced traversals of the tail list, which comes with quite a bit of complexity+code cost. But Brent's algorithm is very well suited for littlefs, requiring only an additional mdir pointer in RAM.
The benefit of adopting Brent's algorithm is not just to speed up cycle detection, but to make cycle detection distinguishable from an infinite loop.
Also added a warning message to help debug when there is an infinite loop. Though this should never happen unless 1. there's a bug in littlefs, or 2. the image on disk is malicious.