trv: Moved cycle detection tortoise into the shrub leaf

This forces our cycle detection tortoise (previously trv.u.mtortoise),
into the unused shrub leaf via pointer shenanigans.

This reclaims the remaining stack (and apparently code) we theoretically
gained from the btree traversal rework, up until the compiler got in the
way:

           code          stack          ctx
  before: 36876           2384          684
  after:  36852 (-0.1%)   2368 (-0.7%)  684 (+0.0%)

And it only required some _questionably_ defined behavior.

---

It's probably not well-defined behavior, but trying to understand what
the standard actually means on this is giving me a headache. I think I
have to agree C99+strict-aliasing lost the plot on this one. Note
mtortoise is only ever written/read through the same type.

What I want:

  lfs3_trv_t:          lfs3_bshrub_t:       lfs3_handle_t:
  .---+---+---+---. .. .---+---+---+---. .. .---+---+---+---.
  |     handle    |    |     handle    |    |     handle    |
  |               |    |               |    |               |
  +---+---+---+---+    +---+---+---+---+ .. '---+---+---+---'
  |   root rbyd   |    |   root rbyd   |
  |               |    |               |    lfs3_mtortoise_t:
  +---+---+---+---+    +---+---+---+---+ .. .---+---+---+---.
  |   leaf rbyd   |    |   leaf rbyd   |    |   mtortoise   |
  |               |    |               |    |               |
  +---+---+---+---+    +---+---+---+---+ .. '---+---+---+---'
  | staging rbyd  |    | staging rbyd  |
  |               |    |               |
  +---+---+---+---+ .. '---+---+---+---'
  |               |
  :               :

But I'm starting to think this is simply not possible in modern C.

At least this shows what is theoretically possible if we didn't have to
fight the compiler.
This commit is contained in:
Christopher Haster
2025-07-22 11:50:30 -05:00
parent 70872b5703
commit fadf0cbd0e
2 changed files with 34 additions and 27 deletions
+3 -11
View File
@@ -771,20 +771,12 @@ typedef struct lfs3_dir {
// littlefs traversal type
typedef struct lfs3_trv {
// mdir/bshrub/btree state, this also includes our traversal
// state machine
// state machine and cycle detection state
lfs3_bshrub_t b;
// opened file state
lfs3_handle_t *h;
union {
// cycle detection state, only valid when traversing the mroot chain
struct {
lfs3_block_t blocks[2];
lfs3_block_t step;
uint8_t power;
} mtortoise;
// btree traversal state
lfs3_sbid_t bid;
} u;
// bshrub/btree traversal state
lfs3_sbid_t bid;
// recalculate gcksum when traversing with ckmeta
uint32_t gcksum;