Commit Graph

316 Commits

Author SHA1 Message Date
Christopher Haster cf90398197 Some small tweaks to mdir functions
- Added lfsr_mdir_lookupnext, for iteration through only a single mid.
  This is useful for MOVE attributes.

- Renamed LFSR_MDIR_MROOTANCHOR -> LFSR_MROOTANCHOR.

- Renamed functions that operate on mdir blocks lfsr_mdir_* ->
  lfsr_mblocks_*.

- Reordered arguments in lfsr_mdir_fetch.

- Renamed mrid_bits/mbid_weight -> mbits/mweight.
2023-09-05 10:10:33 -05:00
Christopher Haster f7900edc1c Updated dbg scripts with changes, adopted mbid.mrid in debug prints
This format for mids is a compromise in readability vs debugability.

For example, if our mbid weight is 256 (4KiB blocks), the 19th entry
in the second mdir would be the raw integer 275. With this mid format,
we would print it as 256.19.

The idea is to make it easy to see it's the 19th entry in the mdir while
still making it relatively easy to see that 256.19 and 275 are
equivalent when debugging.

---

The scripts also took some tweaking due to the mid change. Tried to keep
the names consistent, but I don't think it's worthwhile to change too
much of the scripts while they are working.
2023-09-05 10:10:30 -05:00
Christopher Haster a9b81820b0 Adopted rid-bound-dependent compressed mids.
This adopts a previously discarded idea for compressed mids with a few
tweaks to avoiding decoding the bid/rid portions as much as possible.

The idea of compressed mids is to shove both the mid bid and mid rid
into a single integer, saving RAM and potentially helping filesystem
integration where a unique per-file integer is useful.

Unfortunately this has proven tricky. littlefs fundamentally needs two
ids, one "bid" to lookup which mdir our entry resides on, and one "rid"
to lookup the entry in the mdir. It's tempting to use two half-sized
integers (16-bit for example), but this risks surprising limitations
around the number of files when blocks are either really large or
really small.

Optimally, we'd limit the number of bits reserved for the rid to the
upper bound of number of rids that can fit in a single mdir. This would
allows for more bids when the block size is small, and more rids when
the block size is large. This should roughly approximate the limits of
a per-file integer.

With a bit of math we can estimate the upper bound to be <=block_size/16
with our current compaction strategy.

This idea was previously discarded due to the overhead of extracting the
bids/rids when we need them, but the RAM savings and file-to-integer
mapping is too useful to give up. When it became clear half-width
integers wasn't really going to work, compressed mids became the new
plan:

  0bbbbbbb bbbbbbbb bbbbbbbb rrrrrrrr
  ^'-----------+-----------' '---+--'
  '------------|-----------------|---- sign-bit, reserved for driver
               |                 '---- nlog2(bs/16) bits for rid
               |                       (8-bits for 4KiB blocks)
               '---------------------- remaining bits for bid
                                       (23-bits for 4KiB blocks)

To reduce the overhead of encoding/decode bids/rids a few extra features
were added to the internal mdir APIs:

1. The mtree has been changed to store mids directly. Giving each mdir
   the upper bound as a weight. This allows direct lookup of mids
   without any sort of bid decoding, though does bake the upper bound
   estimate into the metadata of the filesystem, which isn't the
   cleanest design, but if it works it works.

   On the plus side, with this upper bound baked in to the filesystems,
   GRMs can be encoded in a single leb128, which is nice. This may have
   other savings if we ever store mids anywhere else in the filesystem.

2. rids are now mid relative in lfsr_mdir_lookup when non-negative. This
   is implemented with a simple condition that is hopefully optimized
   out when inlined, though there may be some room for improvement here.

3. rids are now mid relative in lfsr_mdir_commit. This was a bit tricky,
   but we can leverage the existing mechanisms for bid-relative rids
   used in the btree implementation.

The above changes make it so you can pass the mid around directly for
most of the mdir functions, hopefully reducing the mid decoding
overhead. This savings should only grow as more high-level filesystem
APIs are added.

Here is the resulting code/RAM changes for this entire change (from
before we adopted the mroot bit):

            code          stack          structs
  before:  20590           1784              908
  after:   20890 (+1.4%)   1744 (-2.3%)      864 (-5.1%)
2023-08-31 14:34:54 -05:00
Christopher Haster 2ea569c746 Fixed inlined mid -1/0 equivalence issue, made mid.bid left-leaning
We weren't comparing mid=-1/mid=0 correctly in lfsr_mdir_commit, which
can happend now thanks to inlining mids in our mroot. This went
unnoticed because we were just copying mroot.mid in our tests so we
never actually tested with mid=0. This is fixed now and the tests test
with a literal mid=0.

This also changes the mbids to be left-leaning, carving out an
mrid-sized number of bits from the mbid, making the route to compressed
mids easier.
2023-08-31 13:57:18 -05:00
Christopher Haster 19f2b24161 Dropped mroot bit, rely on context to determine mroots
This greatly simplifies mid handling at the cost of increased subtlety
around determining if a given mdir is an mroot.

Fortunately it turns out we can rely on context to determine if an mdir
is an mroot or not:

1. If an mdir's mid.bid == -1, it's an mroot. This is always true for
   fake mroots, since they can't hold any inlined mids.

2. If the mtree is inlined (mtree.weight == 0), all mdirs are mroots.
   This lets us use mid.bid=0 for inlined mids. We just need to check
   if the mtree is inlined before deciding if the mdir is an mroot or
   not.

The makes it so that for any non-mroot mdir, mid.bid=-1 is always a
reserved value. Which is very useful for compressed mids.
2023-08-31 13:45:24 -05:00
Christopher Haster 94941806c7 Changed mtree to be weighted by mdir upper bound
More on this when explaining compressed mids, but basically the idea is
instead of just storing all mdirs in our mtree as single element
entries, store each mdir in as a weighted entry, where the weight is a
known upper bound on the possible number of mid entries in a single
mdir.

With the current mid representation, this just complicates things
without much benefits. But with compressed mids it allows us to lookup
mdirs with the mid directly, and avoid decoding the bid from the mid in
some cases.

The mid-per-mdir upper bound is derived from the block size. We know:

1. Each tag needs <=2 alts+null with our current compaction strategy
2. Each tag/alt encodes to a minimum of 4 bytes

This gives us ~4*4 or ~16 bytes per mid at minimum. If we cram an mdir
with the smallest possible mids, this gives us at most ~block_size/16
mids in a single mdir before the mdir runs out of space.

Note we can't assume ~1/2 block utilization here, as an mdir may
temporarily fill with more mids before compaction occurs.
2023-08-31 13:32:21 -05:00
Christopher Haster 9f18b1fd50 Tweaked mid to use sign-bit to indicate mroots
This is an intermediate commit as a part of a tangent into compressed
mids.

The idea here, is instead of using bid=-1 as a special value for mroots,
use only the top bit to indicate mroots. This allows you to compare
against the grm/other uninlined mids by masking instead of signed
comparison.

This is valuable for compressed mids since extracting bids relies on
knowledge of the block size, and becomes quite a bit more expensive.

            mroot bid                             mroot cmp
  before:  0xffffffff  lfs_smax32(a, 0) == lfs_smax32(b, 0)
  after:   0x80000000  (a & 0x7fffffff) == (b & 0x7fffffff)

The implementation here is a bit clumsy. I think GCC may be not that
great at optimizing out copies of structs being passed around via
inlined functions. But this is only a proof-of-concept.
2023-08-31 13:15:58 -05:00
Christopher Haster 256430213d Dropped separate BTREE/BRANCH encodings
There is a bit of redundancy here, as we already know the weights of
btree's inner-branches from their parents. But in theory sharing the
same encoding for both the top level btree reference and inner-branches
should offer more chance for deduplication and hopefully less code.

This also moves some members around in the btree encoding so that the
redund blocks are at the beginning. This _might_ simplify decoding of
the variable-length redund blocks at some point.

Current btree encoding:

  .----+----+----+----.
  |       blocks    ...  redund leb128s (1-20 bytes)
  :                   :
  |----+----+----+----|
  |       trunk     ...  1 leb128 (1-5 bytes)
  |----+----+----+----|
  |       weight    ...  1 leb128 (1-5 bytes)
  |----+----+----+----|
  |       cksum       |  1 le32 (4 bytes)
  '----+----+----+----'

This also partially reverts some tag name changes:

- BNAME -> BRANCH
- DMARK -> BOOKMARK
2023-08-22 13:20:37 -05:00
Christopher Haster 20c036038a Some small tweaks to tests
- Adopted -1 as a cheap way to mark rbyds as unerased.

- Replaced literal references to alphas (alphas[0 % 26]) with their
  actual characters.
2023-08-22 00:15:23 -05:00
Christopher Haster bacd09a673 Implicitly set the rm-bit in generic grow tags
Our rbyds support changing the weight of a tag without knowing the
actual tag. This is useful for btrees, which always make weight changes
without knowing if the leading tag is a name or a branch (it depends on
the type of btree).

But to make this work, it needs the rm-bit to be set. This is because
internally the rm-bit indicates we don't want to write-out a tag. Which
we don't for grow tags, because, well, they're not real tags.

Previously this was done by putting LFSR_TAG_GROW(RM) everywhere a
generic grow as needed, but since this is so common we might as well
just set the rm-bit in LFSR_TAG_GROW.

Note that LFSR_TAG_GROW(tag) (the macro) does not set the rm-bit.

This makes the code a bit more readable at the risk of an unintuitive
relationship between LFSR_TAG_GROW and LFSR_TAG_GROW(tag).
2023-08-19 14:49:18 -05:00
Christopher Haster 256488d4b4 Added tests for nasty btree drop conditions and fixed related bug
Thanks to lazy merging, our btree nodes can drop to zero weight at
pretty much any time. Unfortunately, we can't really represent non-root
zero weight btree nodes, so things break. (Though even if we could,
those nodes would become unreachable).

Previously we relied on fuzz testing to try to catch these cases, but
that turned out to be insufficient.

This adds explicit tests covering the cases where btree drops can occur,
thanks to the realy-big-attr trick used in similar mtree tests.

Sure enough this revealed a bug that can occur when we split a btree
node at the same time one of the siblings goes to zero weight. (Remember
splits carried out before playing attr-lists).

---

Fortunately this is pretty easy to fix. We can just reroute our split
code to the normal commit/compact recursion handling if one of our
siblings drops to zero, at the cost of some spaghetti.

xkcd.com/292 seems relevant here.
2023-08-19 14:07:44 -05:00
Christopher Haster b710769dda Moved *_get functions into tests
With the introduction of lfsr_data_t, these stopped being useful
functions for littlefs internally.

Maybe these tests should be rewritten to use the *_lookup functions
directly? Unfortunately with the quantity of tests we have now this adds
non-trivial amount of work with questionable benefit.
2023-08-19 12:33:16 -05:00
Christopher Haster d09a3646aa Moved lfsr_btree_push/set/pop/split into the tests
These functions are no longer needed in lfs.c. They are still needed for
the tests as they are written, but that's not a reason to pollute the
littlefs source code.

Maybe these tests should be rewritten to use lfsr_btree_commit directly?
Unfortunately with the quantity of tests we have now this adds
non-trivial amount of work with questionable benefit.
2023-08-19 12:33:03 -05:00
Christopher Haster fb2fdb536c Adopted lfsr_btree_commit, replacing all other btree operations.
Note this required changing the INLINED tag to REG in most of the tests,
because our mtree now explicitly requires some sort of NAME tag.

We can also finally see the impact on code and RAM from this restructure:

                                 code          stack
  before (push/set/pop/split):  21750           1928
  after (commit):               20970 (-3.7%)   1744 (-10.6%)

Not too shabby if I say so myself.
2023-08-19 12:17:11 -05:00
Christopher Haster a4c3a12f68 Merged lfsr_btree_commit/lfsr_btree_commit__, related cleanup
This was a temporary hack to make refactoring easier. These are really
the same function.
2023-08-19 12:16:06 -05:00
Christopher Haster f5436caf24 Extended appendall to adjust bid-relative attrs, made attr-lists const again
This adds an extra bid parameter to lfsr_rbyd_appendall so that attrs
relative to a bid can be adjusted correctly.

This allows us to make attr-lists const again, which is generally a good
things. Passing around complex mutable state is just asking for bugs.

Though since these attr-lists are generally just passed as temporary
arguments, maybe it's not that bad?
2023-08-19 12:10:17 -05:00
Christopher Haster 9b2f3cd5bb Rerouted all btree mutation through attr-list parser
The idea here: Instead of having unique functionality for each
individual btree operation (push/set/pop/split), we treat btrees sort of
like rbyds, with a single commit entry point that operates on attr-lists.

This adds code cost, due to needing to parse the attr-list for properties
that can affect inlined btrees (tag changes mostly), but, in theory, comes
with some advantages:

1. A single btree commit entry point with all of the inlined/uninlining
   logic should offer better chances for code deduplication, vs
   spreading this logic out in each btree operation.

2. Higher-levels should know what the current weight of the branch is,
   so we may be able to avoid the implicit math needed to calculate
   deltas.

3. Higher-levels have more knowledge about the state of the btree in
   general, so there may be other shortcuts. The mtree, for example,
   only operates on weight=1 entries, which greatly simplifies a lot of
   the related math.

Note that btrees still have strict limits in what's possible in an
attr-list. Btree operations can't cross leaf-rbyd boundaries for
example.

---

A notable omission in this change is the loss of reinlining btrees.

This wase dropped for a couple reasons. It may be worth adding back at a
later time, maybe after we actually have files implemented, but for now
does not seem worth it:

1. Reinlining adds code cost. Reinlining is more complex than you might
   expect because we only reinline on compaction. And because we compact
   before playing out our attr-list, we need to know if a commit makes
   the btree inlinable before committing to the btree.

   This is still doable with our attr-lists. We already derive the
   change in tags, since we need this to know when to uninline. But it
   adds a kind of complex bailing out of btree commits.

2. The benefits of reinlining may not be that great. In most systems, a
   tree that is uninlined once is likely to be uninlined again. It's
   only if there is a bigger state change in a system that it makes
   sense to reinline.

   Though, to be fair, waiting for compaction to reinline handled this
   quite well. Only reinlining when all erased storage is used up...

3. Thanks to our roots did entry, our mtree can never reinline.

   It would be nice to change this, but this would require explicit
   handling in lfsr_mdir_commit. Future work?

4. Files are another can of worms, with more complex interactions with
   inlinability thanks to (at least on paper right now) always having
   inlined data even when uninlined.

   If reinlining is valuable for files this can change during that work.

5. Even if files never support reinlinability, truncating files (via
   either lfsr_file_truncate or LFSR_O_TRUNC) should give the file a
   blank slate, effectively reinlining the file in that case.

---

The current implementation also changes the attr-list to be mutable so
we can adjust attr-list based on the current btree node. This is a
temporary hack! We should add the appropriate functionality to our rbyd
utilities to revert this eventually.
2023-08-19 11:41:36 -05:00
Christopher Haster 3dbc986752 Added explicit tests over btree reinlining
These tests, and this feature really, is a bit tricky since our btrees
reinline "lazily". That is, our btrees only check if they can inline
during compaction, allowing potentially inlinable btrees to remain
uninlined.

This better utilizes any erased storage in the btree's rbyd, but adds
some corner cases we need to be concerned about.

Added because of some ongoing btree rewrite work, where it did catch
incorrect behavior.
2023-08-19 11:40:10 -05:00
Christopher Haster d069fed3ed Adopted more macro concatenation in tag defines
This cleans up the code a bit, and means we no longer need to define all
of the LFSR_TAG_RMGROWWIDEREG permutations.
2023-08-11 01:35:07 -05:00
Christopher Haster f1f1a5aaf8 Unionized mtree traversal's tortoise state and btree traversal state
Realistically, because our btree is protected by CoW checksums, the only
place we can end up with a cycle is in our mroot chain.

This is convenient, as we don't need our btree traversal state when
traversing the mroot chain, so we can put both the tortoise state and
btree traversal state into a union, theoretically saving some RAM.

Unfortunately stack measurements show no change, even though our mtree
traversal in on the hot path. I'm not sure why this is. My best guess is
that the RAM savings is beneath the compilation noise floor, since we
currently only ever create one of these structs.
2023-08-11 01:29:33 -05:00
Christopher Haster d8f988a8fc Made data read functions "consume" their data pointers
Composable parsing functions always feel a bit weird to me in C. I don't
know if this is because of something C lacks, such as multiple return
values, or if composable parsers are just inherently awkward to describe
in procedural languages because of the different levels of state.

But I think the API here is pretty ok. The main idea is that data
parsers can be added as functions in the lfsr_data_* namespace that take
lfsr_data_t as a mutable reference, updating the lfsr_data_t's internal
state as data is parsed.

In practice you only need a couple of primitives, bytes, le32s, leb128s,
that touch the internals of lfsr_data_t, and the other parsers can be
built using these.

This leverages the pointer-like abstraction of lfsr_data_t, and avoids
needing to keep track of offsets. And thanks to lfsr_data_t being
relatively cheap to make copies, this API is relatively flexible.

Some other tweaks:

- Signed leb128 overflow detection is moved up into lfs_fromleb128.
  littlefs now assumes _all_ leb128s are 31-bits, which is useful for
  leveraging the sign bit internally.

  This also fixes the an issue in overflow detection in lfs_fromleb128
  which wouldn't catch overflows in the last byte of a >32-bit leb128.

- Most lfsr_data_t functions now take a pointer. This offered a small
  bit of code savings and feels more natural in C. Though most functions
  that accept lfsr_data_t still take a copy. Most of these functions
  would need to make a copy anyways now that the parsers are consuming,
  and these copies avoid concerns about shared state.

  At 3-words, lfsr_data_t is right at that boundary of questionable
  reasonableness for copying, but copying is a very useful feature of
  this struct.

This ends up with some decent code/stack savings:

            code          stack
  before:  22118           2048
  after:   21722 (-1.8%)   1992 (-2.7%)
2023-08-10 11:13:14 -05:00
Christopher Haster 78a199b59b Reworked LFSR_ATTR macros to support extensions better
Generally the more creative you get with C macros, the more
unmaintainable your codebase becomes, but in this case I think a small
bit of macro sugar for the attribute lists in littlefs goes a long way
for making the internals flexible and readable.

Attribute lists generally look like this:

  LFSR_ATTRS(
      LFSR_ATTR(id, TAG, delta, DATA(data)),
      LFSR_ATTR(id, TAG, delta, DATA(data)),
        ...
      LFSR_ATTR(id, TAG, delta, DATA(data)))

Which more-or-less gets expanded to this:

  ((const lfsr_attr_t[]){
      ((lfsr_attr_t){id, LFSR_TAG_TAG, delta, LFSR_DATA_DATA(data)}),
      ((lfsr_attr_t){id, LFSR_TAG_TAG, delta, LFSR_DATA_DATA(data)}),
        ...
      ((lfsr_attr_t){id, LFSR_TAG_TAG, delta, LFSR_DATA_DATA(data)}),}),
  attr_count

Note the use of preprocessor concatenation to put the TAG and DATA
identifiers in their respective namespaces. These can end up invoking
other macros, which allows attrs to be rather extensible.

Previously there were also LFSR_ATTR_ (note the trailing underscore)
macros to allow passing of variable tags/datas. This is replaced with
redundant macros which sort of "unwrap" themselves as a part of macro
expansion. This avoids a bunch of duplicate macro definitions.

  #define LFSR_TAG_TAG(tag) (tag)
  #define LFSR_DATA_DATA(data) (data)

So:

  LFSR_ATTR(id, TAG(tag), delta, DATA(data))

Becomes:

  ((lfsr_attr_t){id, LFSR_TAG_TAG(tag), delta, LFSR_DATA_DATA(data)})

Becomes:

  ((lfsr_attr_t){id, tag, delta, data})
2023-08-08 22:23:10 -05:00
Christopher Haster d2f2b53262 Renamed fcksum -> ecksum
This checksum is used to keep track of if we have erased, and not yet
touched, the unused bytes trailing our current commit in the rbyd.

The working theory is that if any prog attempt is made, it will, most
likely, change the checksum of the contents, allowing littlefs to
determine if trailing erased-state is safe to use, even under powerloss.
littlefs can also perturb future data by a single bit, to force this
checksum to always be invalidated during normal operation.

The original name, "forward erased-state checksums (fcksum)", came from the
idea that the checksum "looks forward" into the next commit.

But after using them for a bit, I think the name is unnecessarily
confusing. It, uh, also looks a lot like a swear word. I think
shortening the name to just "erased-state checksums (ecksum)", even
though the previous name is already in use in  a release, is reasonable.

---

It's probably hard to believe but the name change from fcrc -> ecrc
really was unrelated to the crc -> cksum change. But boy is it
convenient for avoiding an awkward name. A lot of these name changes
involved sed scripts, so I didn't notice how awkward fcksum would be to
use until writing this commit message.
2023-08-07 14:34:47 -05:00
Christopher Haster 7031d6e1b3 Changed most references to crc/csum -> cksum
The reason for this is to move away from the idea that littlefs is
strictly bound to CRCs and make the code more welcoming to other
checksum types, such as SHA256, etc.

Of course, changing the name doesn't really do anything. littlefs
actually _is_ strictly bound to CRCs in a couple ways that other
filesystems aren't. These would need to have workarounds for other
checksum types:

- We leverage the parity-preserving nature of (some) CRCs to not have
  to also calculate the parity of metadata in rbyd commits.

- We leverage the linearity of CRCs to retroactively flip the
  perturb bit in the cksum tag without needing to recalculate the
  checksum. Though the fact we need to do this is because of how we
  use parity above, so this may just not be needed for non-CRC
  checksums.

- The plans for global-CRCs (not yet implemented) rely heavily on the
  mathematical properties of CRC polynomials. This doesn't mean
  global-CRCs can't work with other checksums, you would just need to
  find a different type of polynomial.
2023-08-07 14:18:37 -05:00
Christopher Haster d77a173d5c Changed source to consistently use rid for rbyd ids
Originally it made sense to name the rbyd ids, well, ids, at least in
the internals of the rbyd functions. But this doesn't work well outside
of the rbyd code, where littlefs has to juggle several different id
types with different purposes:

- rid => rbyd-id, 31-bit index into an rbyd
- bid => btree-id, 31-bit index into a btree
- mid => mdir-id, 15-bit+15-bit index into the mtree
- did => directory-id, 31-bit unique identifier for directories

Even though context makes it clear which id the id refers to in the rbyd
internals, updating the name to rid makes it clearer that these are the
same type of id when looking at code both inside and outside the rbyd
functions.
2023-08-07 14:10:09 -05:00
Christopher Haster 64a1b46ea2 Renamed a couple directory related things
- dstart -> bookmark
- *dnamelookup -> *namelookup
2023-08-07 14:00:44 -05:00
Christopher Haster c37bab6040 Reworked rbyd/btree/mdir structs again so redund blocks are at the end
For a couple reasons:

1. Organizing the overlaps this way avoid potential undefined behavior.
   It turns out C does define the overlap the "initial sequence" of
   union members, as long as the types are the same. But when we
   overlapped the block with the size/tag fields in lfsr_btree_t, it was
   probably undefined behavior.

   At the very least, it would introduce a need for quite a bit of
   preprocessing to make it work with different integer sizes and
   redundancy levels.

2. Overlapping the blocks at the end of the rbyd struct means our block
   array is natural ordered such that the first block is the "active"
   block, i.e. the block with the most recent revision count that passes
   checksums.

   This has been useful as a debugging tool, so I would like to continue
   the pattern. It is possible to mostly preserve this order with the
   previous method by intentional reversing the block array when
   logging or writing to disk, but it's a bit cumbersome.

2. It's unlikely we'll be able to use readonly variants of the rbyd/mdir
   structs for RAM savings. Unfortunately C makes this too cumbersome.
   Though if we do this should be revisited.

Here are the new overlaps. Note it's no longer possible to truncate the
types when readonly. If readonly struct are useful this will need to be
revisited again:

   lfsr_rbyd_t            lfsr_btree_t           lfsr_mdir_t
                                                  8b   8b   8b   8b
                                                .----+----+----+----.
    8b   8b   8b   8b      8b   8b   8b   8b    | mid.bid | mid.rid |
  .----+----+----+----.  .----+----+----+----.  |----+----+----+----|
  |       weight      |.>|       weight      |  |       weight      |
  |----+----+----+----|  |----+----+----+----|  |----+----+----+----|
  |       trunk       |  |   tag   |   size  |  |       trunk       |
  |----+----+----+----|  |----+----+----+----|  |----+----+----+----|
  |        off        |  |    inlined data   |  |        off        |
  |----+----+----+----|  |         |         |  |----+----+----+----|
  |        crc        |  |         v         |  |        crc        |
  |----+----+----+----|  |                   |  |----+----+----+----|
  |       block       |..|                   |.>|       blocks      |
  '----+----+----+----'  '----+----+----+----'  |                   |
                                                |                   |
                                                '----+----+----+----'
2023-08-06 23:40:32 -05:00
Christopher Haster fe941ef443 Reworked rbyd/btree/mdir structs to allow better access to subcomponents
This turned out to be tricky.

At littlefs's core, we have the lfsr_rbyd_t struct. It is really
important this is as small as possible since littlefs creates many rbyd
copies in order to track state of metadata on disk.

Wrapping rbyd, we have the lfsr_btree_t struct, which can alternatively
contain a single inlined entry, accomplished by overlapping the width
field in both cases. And the lfsr_mdir_t struct, which tracks any redundant
blocks, and would be nice if the blocks lined up as neighbors so all blocks
involved in the mdir could be passed around as an array. Both of these
wrappers attempt to overlap fields of the lfsr_rbyd_t struct, which presents
a bit of a problem.

The solution here is to put the rbyd block field at the beginning of the
lfsr_rbyd_t struct, and use exactly 32-bits of padding in lfsr_btree_t
to overlap the width field even though it is not at the beginning of the
struct. To avoid inflating the lfsr_btree_t size, we sneak the inlined
size and tag into the overlapping padding. This will need special
handling if the size of these fields change, but saves a decent amount
of RAM:

   lfsr_rbyd_t            lfsr_btree_t           lfsr_mdir_t
                                                  8b   8b   8b   8b
                                                .----+----+----+----.
                                                | mid.bid | mid.rid |
                                                |----+----+----+----|
    8b   8b   8b   8b      8b   8b   8b   8b    |       blocks      |
  .----+----+----+----.  .----+----+----+----.  |                   |
  |       block       |..|   tag   |size|padd|.>|                   |
  |----+----+----+----|  |----+----+----+----|  |----+----+----+----|
  |       weight      |.>|       weight      |  |       weight      |
  |----+----+----+----|  |----+----+----+----|  |----+----+----+----|
  |       trunk       |  |    inlined data   |  |       trunk       |
  |----+----+----+----|  |         |         |  |----+----+----+----|
  |        off        |  |         v         |  |        off        |
  |----+----+----+----|  |                   |  |----+----+----+----|
  |        crc        |  |                   |  |        crc        |
  '----+----+----+----'  '----+----+----+----'  '----+----+----+----'

Also tried to reduce the amount of mdir usage in lfsr_mdir_commit by
better using only the arrays of relevant mdir blocks, to limited success.
2023-08-06 23:40:28 -05:00
Christopher Haster da4e86abac Split test_dirs into test_dtree and test_dseek
- test_dtree - Pure directory creation/deletion/move functionality
  testing. This ends up testing the core of littlefs file entry
  manipulation, since directories is all we need for that.

- test_dseek - Tests more of the corner cases specific to directory
  iteration and seeking. This involves an annoying amount of
  interactions with concurrent updates to the filesystem that are
  complicated to test for.

Also generally renaming the "fstree" concept to "dtree". This only
changes dbglfs.py as far as I'm aware. It's useful to have a name for
this thing and "directory tree" fits a bit better than "filesystem tree"
which could be ambiguous when we also have the "metadata tree" as a
different concept.
2023-08-04 14:17:42 -05:00
Christopher Haster 4efb55e0d7 In tests/benches, renamed cfg -> CFG
This is to better indicate this is a runner generated variable.
2023-08-04 14:05:07 -05:00
Christopher Haster 5be7bae518 Replaced tn/bn prefixes with an actual dependency system in tests/benches
The previous system of relying on test name prefixes for ordering was
simple, but organizing tests by dependencies and topologically sorting
during compilation is 1. more flexible and 2. simplifies test names,
which get typed a lot.

Note these are not "hard" dependencies, each test suite should work fine
in isolation. These "after" dependencies just hint an ordering when all
tests are ran.

As such, it's worth noting the tests should NOT error of a dependency is
missing. This unfortunately makes it a bit hard to catch typos, but
allows faster compilation of a subset of tests.

---

To make this work the way tests are linked has changed from using custom
linker section (fun linker magic!) to a weakly linked array appended to
every source file (also fun linker magic!).

At least with this method test.py has strict control over the test
ordering, and doesn't depend on 1. the order in which the linker merges
sections, and 2. the order tests are passed to test.py. I didn't realize
the previous system was so fragile.
2023-08-04 13:33:00 -05:00
Christopher Haster 2835b17d14 Attempted to merge the mid's bid and rid into a single integer
This didn't really work out as well as I had hoped. There were a few
ideas on how to encode the bid/rid tuple without sacrificing the
(currently 31-bit) integer limit, but these just introduced too much
complexity.

Ideas:

1. In theory, as the mdirs increase in size, the quantity of mdirs needed
   for a given number of files decreases. If we say the number of files
   fits in an integer of a given size, than we can model the mapping to
   mdirs and rids roughly as the number of bits in that integer split
   between the two.

   Since the block_size is known, the we can find a rather conservative,
   yet useful, estimate of the upper bound of rids, which ends up
   being ~16 bytes ((2 alts + 1 null + 1 tag) * 4 bytes).

   And since our btrees are perfectly balanced, this encoding should only
   waste 1 or 2 bits due to rounding to rounding and sign encoding for
   special values.

     bbbbbbbb bbbbbbbb bbbbbbbr rrrrrrrr
     '-----------+-----------''----+---'
                 |                 '-- log2(block_size/32)-bit rid
                 '-------------------- remaining-bit bid

   Unfortunately, while this works ok on paper, and maximize the use of
   the bits we have available for the mid, the implementation ended up
   awkward and difficult to use.

   We need to either calculate the relatively complciated log2 of the
   block_size on the fly, or cache the value, and use it to shift the
   mid around to extract the bid/rid when needed.

   Unfortunately, perhaps due to the it being easy to use the bid/rid
   directly, we use and mutate the bid/rid quite a bit. We mutate when
   updating the mdirs, when decoding grms, when seeking mdirs, etc. If
   anything, updating the mid in total is rarer than updating the
   bid/rid component in complicated situations.

   Note to mention this required access to the lfs config to even begin
   decoding, complicating the API and making the result less efficient.

   Initial (unoptimized, and not even tested) code size showed ~+800
   bytes. So I decided to scrap this.

   Maybe it will be worth investigating dynamic rid sizes later, to
   increase the possible mtree size for a given mid width. Not sure.

2. Probably one of the worst ideas I've had so far, but it would solve
   the mid encoding problem, is to use some form a floating point to
   encode the bid/rid pair:

                          .----------.
                          v         .+-.
     bbbbbbbb bbbbbbbb bbbrrrrr rrrrssss
     '-----------+-------''----+---''-+'
                 |             |      '-- rid bits
                 |             '--------- variable rid
                 '----------------------- variable bid

    An even worse idea would be to use IEEE floating point here. Yes it
    would work, and probably work annoyingly well, but we it risk
    bringing in a lot of standard conforming backbending that we really
    don't care about.

    The idea here is to sacrifice some bits to encode the ratio of rid
    bits to bid bits. The value of this over the using the block_size is
    that we can decode the bid and rid using all of the bits in the
    integer alone. Avoiding memory access (and worse debugging) to load
    any external constants.

    As a plus, all mids in the system would have the same exponent,
    simplifying comparisons and other operations.

    But this is just trying to solve complexity by adding more
    complexity, so I'm not even going to try implementing it.

    Still, it's an interesting idea...

In the end I've gone with the KISS implementation. Use half-width
integers, in this case uint16s, for both the bid and rid:

  bbbbbbbb bbbbbbbb rrrrrrrr rrrrrrrr
  '-------+-------' '-------+-------'
          |                 '-- 16-bit rid
          '-------------------- 16-bit bid

This suffers from weakened limits around the number of rids in a block
and number of mdirs in the mtree, which is unfortunate. Still it is
probably worth the tradeoff for the RAM savings and encoding simplicity.

If the mdir is reasonably sized, this does probably approach a decent
distribution of rids and bids in 32-bits. But for outlier cases with
very small and very large mdirs, it risks premature out of bounds
errors.

To protect against mtree errors, we will probably need an additional
configuration option in the form of an mdir limit. Conveniently this
would also provide a way to enforce 2-block mode.

rid errors, on the other hand, depend on block_size/32, so we may not
need another configuration option and can rely on the block_size
to determine if the rids can overflow.

This is probably worth revisiting in the future. Fortunately, with
mdir_limit and block_size configuration options, it should be possible
to increase these limits in the future if this mid bid/rid design
changes.

            code          stack
  before:  22126           2136
  after:   22326 (+0.9%)   2088 (-2.2%)

This code size increase was unexpected. Maybe non-32-bit-aligned integers
cost more to load in thumb? Unsure.
2023-08-03 09:30:58 -05:00
Christopher Haster 5bdb55abec Fiddled with how opened mdirs are tracked and updated
The main intention here was to make the tracking of opened mdirs,
mostly opened lfsr_dir_t structs, simpler and more resilient to weird
corner cases. I'm not entirely sure this was successful.

The main changes:

- lfsr_dir_t now contains a full mdir for the dstart entry.

  This makes it so that dstarts are not a special case when it comes
  to mdir updates, though the fact that directories have 2 mdirs is
  still an awkward case on its own.

  I considered using two entries in the opened linked-list for this, but
  it wouldn't have worked out that well. Both entries need to update the
  directory position, so it would have required a third file type. We
  would also have needed to make sure removed mdirs mark both mdirs as
  removed, otherwise the position mdir would move around arbitrary into
  possibly erronous values.

  Instead the current solution treats the directory mdirs as a small
  array of 2 mdirs, which is as hacky as it is hacky, but does get the
  job done with little code duplication.

- Directory positions are updated a bit more intellegently.

  Instead of checking if in range before updating, which requires access
  to both mdirs and duplicate mid/rid comparison logic, position is
  updated without regard for the beginning of the directory, and
  un-updated if it was actually out of range of the directory.

  This means we only need to compare the mids/rids for each mdir once.

This changes make it so that lfsr_dir_rewind is much cheaper, and
doesn't even need to go to disk. Though I'm not sure it's worth the RAM
increase...

Expanding the lfsr_dir_t dstart entry to a full mdir does a lot for
making mdir updates more consistent, but increases the lfsr_dir_t size
from 52 bytes to 76 bytes (+46.2%).
2023-08-01 23:40:25 -05:00
Christopher Haster d8d8d1e2ac Dropped special LFSR_MID_RM mid
This is mostly to make it easier to merge mids/rids. Having a special
constant here is tricky when the mid/rid split point is dynamic.

Currently using rbyd.trunk=0 to indicate when an mdir is dropped. This
is nice as it preserves the last mid/rid, which is needed by the readdir
code, and it implicitly returns NOENT to all queries in
lfsr_rbyd_lookup.
2023-08-01 12:48:45 -05:00
Christopher Haster 18e1eb0b41 Moved rid into the mdir struct
When updating any opened mdirs to keep things in sync, we need to know
what rid the mdir is targeting in order to know which on-disk mdir it
should follow in the case of splits. Making this rid an actual member of
the mdir struct simplifies things.

This adds some RAM cost, though the plan is to merge the mid/rid into a
single integer, which requires this change and should actually save RAM
in the long run.

            code          stack
  before:  22342
  after:   22204 (-0.6%)   2144 (+1.1%)
2023-07-31 18:19:58 -05:00
Christopher Haster 9d0edea7e3 Reworked lfsr_rbyd_estimate to be a bit simpler
Instead of reading eagerly and retreating with the hopes of terminating
early (which almost never happens when compacting, since we need to find
the split_id). lfsr_rbyd_estimate now works inward from the first and
last id to find both the dsize and split_id.

One thing that helps this is the addition of a separate per-id
lfsr_rbyd_estimate, which will be useful for checking if the quantity of
file attributes overflows our mdir limitations.

lfsr_rbyd_estimate also now ignores the -1 id for split_id calculation,
since -1 ids are always cleaned up during splitting, though it does
include it in the calculated dsize so that the condition to split is
determined correctly.

---

This also required rebalance changes. Fortunately, one improvement here
is that we can make a simplifying assumption tha the number of tags
can't exceed the maximum possible number of tags in the calculated
dsize. So worst case, if every tag is empty, the maximum possible dsize
becomes 4*(2*log2(dsize/4))+dsize.

Though it's still unclear if rebalance is worth keeping. Current
comparison:
                  code          stack
  rebalance:     22362           2120
  no_rebalance:  21922 (-2.0%)   2120 (+0.0%)
2023-07-30 17:12:33 -05:00
Christopher Haster adcf9924fe Deduplicated uninling/split routes in lfsr_mdir_commit
This means no special case for uninling-but-not-splitting, but allows
the entire split route to be deduplicated, simplifying things.

The main downside is that for littlefs to go from a single inlined mdir
filesystem to an mtree filesystem it requires a minimum of 2 mdir
allocations (4 blocks) in all cases. This can be avoided, but I think is
worth the tradeoff since it generally occurs once in a filesystem's
lifetime.

This does make 4 block block devices a bit awkward, but those geometries
are always going to be a bit awkward with littlefs's design. At least
this implementation avoids an unecessary B-tree node where possible...

            code          stack
  before:  22586           2320
  after:   22414 (-0.8%)   2120 (-8.6%)

I _think_, but haven't verified, the significant stack saving comes from
the fact that since there's one route through lfsr_mtree_split_,
lfsr_mtree_split_ can be inlined into lfsr_mdir_commit. This avoids the
marshalling of all its arguments for the function call, which I've
noticed can have a surprising cost.

---

Also fixed a bug where dstart was not updated with mid changes after
splits/drops. The mdir commit cleanup code has a lot of duplication now,
makes me wonder if there's a better way to structure this.
2023-07-30 16:23:45 -05:00
Christopher Haster 2ce6567683 Found+fixed a bug where arbitrary dir seeks can return unrelated entries
It turned out our dir-read-idempotent test never created non-dstart
neighbors. This was a bit of a problem since we relied on dstart entries
to know when our dir read terminates. If we seek to an invalid position
(in theory undefined behavior, but easily possible with concurrent
modifications to the directory), we can end up reading an unrealted,
non-dstart entry, and incorrectly reporting that entry as in our current
dir.

This fix reintroduces the did into the lfsr_dir_t struct and uses the
did to determine end-of-dir. This adds some RAM cost, but is more
resilient to any seeks that overshoot the end of the directory.

Using did is also a stronger guarantee we will never accidentally report
unrelated entries as a part of the current directory.
2023-07-29 01:21:49 -05:00
Christopher Haster e08ff99d50 Made grm a special attribute, moved encoding into mdir commit
This is entirely a pragmatic change, lfsr_mdir_commit already does
several hairy things with grm tags, decoding, fixing, reencoding, etc,
so it makes sense to move all the encoding logic into lfsr_mdir_commit.

This leads to a couple optimizations:

- We don't need to decode the grm to apply any last minute fixes.

- By allowing the grm arugment to be mutated (they are just sitting on
  the stack anyways, we need a copy in case we back out of change due to
  error), we can apply and save any grm fixes in the grm argument
  itself.

  This means we only need to fix the grm at most once, after any mtree
  modifications.

Which in turn saves some code and stack cost:

            code          stack
  before:  22930           2392
  after:   22706 (-1.0%)   2344 (-2.0%)
2023-07-28 16:04:43 -05:00
Christopher Haster 4cf5509c91 Reverted most of dir offset changes, dirs to follow dstart when open
Unfortunately the previous attempt to fix the dir seek system didn't
really work. Using a packed mid/rid integer for the offset is tempting,
but since mid/rid can change with any metadata id change in the
filesystem, dir tell offsets would become invalidated if you modified
files in unrelated directories, which isn't great and likely to catch
users by surprise.

This solution builds on the previous dir offset design, which tracks the
dstart-relative position independently from the current mid/rid in our
directory. To update this correctly when there are unrelated changes to
the filesystem, we need to know if metadata id changes are in the range
between our directories dstart and current mid/rid. This in turn means
we need to track our dstart. So our opened directories need three
separate pointers we need to update on every mdir commit:

             dir->pos
                |
        .-------+-------.
  a b c d e f g h i j k l m n o p
        ^               ^
        |               |
    dir->dstart     dir->mdir

This has quite a few moving parts, which I was hoping to avoid.
Fortunately we don't need a second mdir, so the RAM cost is pretty
small.

We can also drop dir->did, since the dstart mid/rid render it redundant,
which is interesting.
2023-07-28 12:58:16 -05:00
Christopher Haster edd12e1f93 Changed how dir offsets in tell/seek are encoded
This is an attempt to fix issues with dir seeking in a filesystem
undergoing changes. The problem with the previous dstart-relative
position encoding is that if we deleted/created new entries outside of
our current directory, we didn't if they were inside or outside of the
current directory, so we couldn't always update our position correctly.

Instead of using a dstart-relative position, this solution crams both
the mid and rid into a single 31-bit integer. Things get a bit tight
here, so we use the current block_size as a heuristic for how many
possible rids we can ever have in a single mdir. The idea is the larger
the rid encoding needs to be, the smaller the mid encoding needs to be,
and we should, _roughly_, approach the same encoding limitation we would
have to dstart-relative position anyways.

Making some assumptions about the maximum possible number of rids in a
block gives us at most ~block_size/8 rids per mdir.

So for 4096 byte blocks (note the exact encoding is dynamic):

  sbbbbbbb bbbbbbbb bbbbbbbr rrrrrrrr
  ^'-----------+----------''----+---'
  '------------|----------------|----- sign bit (used for errors)
               '----------------|----- 22-bit metadata bid
                                '----- 9-bit metadata rid

Note this introduced as new, significant limitation on the number of
total mdirs in the system. Normally I would be against this solution for
that reason, however if we adopt this encoding elsewhere in the system it
may improve some RAM cost and in general simplify things by being able to
store any mid in a single integer. More work needs to be done here...

This approach needs some fleshing out and has its own issues (the
offset returned by tell quickly becomes out of date if the filesystem
is modified, but is that really a problem?), but it improves over the
previous implementation by making tell always correct at that moment.
2023-07-27 16:59:34 -05:00
Christopher Haster d931c19dda Added more aggressive tests with dirs reads under mutation 2023-07-25 15:51:46 -05:00
Christopher Haster 51c4dadbe3 Added more dir test around really niche corner cases, fixed related bugs
- Prevented removing and renaming of the root directory. This is done by
  repurposing the INVAL error in lfsr_mtree_lookup to indicate the
  found entry is the root.

  The root entry has special behavior in almost every function, owing to
  the fact it doesn't really have an mid/rid. So I think this is a
  reasonable approach.

- Added support for lfsr_stat of the root directory.

- Fixed off-by-two in lfsr_dir_seek thanks to the "." and ".." entries.

  Humorously there is a comment noting this but the code didn't
  actually match the comment.
2023-07-25 14:01:24 -05:00
Christopher Haster a27c7d9ddd Added tests over recursive mvs and limited pl testing a bit
Unfortunately the powerloss testing risks being a big time sink.
Figuring out the best scale of powerloss testing during normal testing
is probably going to be a constant balancing act.
2023-07-25 13:59:24 -05:00
Christopher Haster a3579ec3e2 More tests over rename behavior and fixed bugs
Mainly trying to match the tests over mkdir/rm, which seem to have a
good amount of coverage.

- Fixed issue where move's desination rid wasn't updated correctly if
  the destination split.

- Prevented renaming into nonexistant directories.

- Fixed neighboring rid adjustment in rename (+1 not -1 silly).

- Fixed erronously updating the grm's rid during lfsr_fs_fixgrm. In the
  "I can't believe this ever worked" category, it seems this usually
  didn't cause issues since mid was often marked as removed, making the
  erronously updated rid ignored.
2023-07-25 13:51:51 -05:00
Christopher Haster ee37f8c7a6 Implemented lfsr_rename
Only simple tests right now, but the theory is sound.

This mainly required the addition of the fancy in-device move attribute,
which copies all tags associated with an rid from one rbyd to another in
a single transaction.

This is a carryover from the previous littlefs implementation, though it
is easier to implement here since it is effectively a range query on the
rbyd tree, which trees are really good at. This was intentional.

Oh and I suppose this also required implementing lfsr_rename, which has
a few corner cases to watch out for.

It is nice that both lfsr_remove and lfsr_rename can rely on
lfsr_fs_fixgrm to finish all of the removes, which wasn't previously
reasonable due to the overhead of deorphaning.
2023-07-25 13:45:26 -05:00
Christopher Haster e8b68c4e88 Tweaked how recursive removes interact with dir read again
Hopefully third times the charm.

The previous solution pretty bluntly did not work outside of the
recursive remove case, because the moment we mark the rid as deleted,
the directory positions no longer get updates. It's not possible to
update the directory position because we don't know how it maps into our
mtree without a full seek from the dstart.

After staring at it a bit, I think this solution should work:

1. Instead of marking the mid/rid as removed when dropping an mdir, we
   set the weight to zero and the trunk to zero, causing mdir lookups to
   return NOENT without actually going to disk.

   This is very important since later mdirs could be allocated on the
   same block, and going to disk can result in a corrupted lookup.

2. Eagerly seek to the next mid/rid after every lfsr_dir_read call. This
   puts us in a position where rid can be >= the current mdir weight
   without issues, and avoids degenerate cases that may be caused by
   recursive removes.

3. If we remove an opened dir, instead of marking the mdir as deleted,
   move the rid to the next rid. If the mdir was dropped, this leaves us
   with rid == mdir weight, and the mdir trunk == 0.

   The rid == mdir weight also occurs when we are creating a new file, so
   we have a bit of common behavior we can rely on. We just need to make
   sure that mdir updates respect the rid == mdir weight situation.

4. On each lfsr_dir_read call, we do an mtree seek of zero. This just
   serves to fix our mdir if our rid == mdir weight, without much
   additional code (yay for code reuse).

The use of weight=0, trunk=0, for a dropped mdir here is key, and makes
me wonder if this is a better indicator of a dropped mdir than another
reserved mid value. This probably deserves some investigation later.
2023-07-25 13:19:39 -05:00
Christopher Haster b1187595d6 Added support for recursive removes in directories
"Recursion" here just refers to the ability to remove entries in a
directory while iterating over it. This is very useful when you just
want a directory gone, and can be extended to a "true" recursive remove
straightforwardly. This mainly tests that mid/rid updates in opened
mdirs are correct.

To make this work, we need to update opened dirs differently than files,
since opened dirs do not get marked as removed when its rid is removed
and contain an additional position in the dir that needs to be updated.

To keep track of the different types, littlefs now contains 2
linked-lists for opened mdirs. Maybe these should be correctly typed,
but by hiding the specific types behind an array of mdir linked-lists,
we can more efficiently iterate over both lists when necessary.

We should probably compare this approach to the type-tagged approach in
the previous littlefs implementation, but I think the idea of an array
of type-hidden linked-lists just didn't come to me then. There was also
a bit more room in the mdir structs to hide a 1-bit type field. The mdir
structs here are getting pretty squeezed since they are used everywhere.
2023-07-25 12:54:49 -05:00
Christopher Haster 0ddd851f6f Added more dir remove tests
These mirror the lfsr_mkdir tests, but backwards.

It's interesting to note the rm powerloss testing is much slower than
mkdir powerloss testing. This is because the rm tests can make
significant backwards progress if power is lost (these tests both make
and remove dirs), but mkdir tests always make forward progress (by only
making dirs).
2023-07-25 12:52:52 -05:00
Christopher Haster 53a4da13f5 Added lfsr_remove
In theory this is pretty much the same as lfsr_mkdir, but backwards.

The main work was making the interactions between removing mids/rids and
the grm correct. This ends up meaning we just need to update the grm on
any mid/rid update the same way we update the list of opened mdirs.

On the plus side, it turned out to be possible to deduplicate the mdir
uninlining route a bit, by adding range argument to lfsr_mdir_commit_
and changing the write of the newly uninlined mtree/mdir to marking
mtree as dirty and then joining the common path.

This lets us move the pre-commit round of grm updates into a single
location in lfsr_mdir_commit, removing and extra function definition and
the related state marshalling while also simplifying the control-flow.

This also raises the question, can more lfsr_mdir_commit be deduplicated
more? Uninlining is a infrequent operation we don't really need to
optimize for.

---

Testing lfsr_remove also found a bug related to incorrect propagation of
when the mroot becomes "unerased" (when rbyd overflows). This raises the
concern that we're not propagating unerased-states very rigorously, and
unexpected errors may not allow the filesystem to resume.

This has never been in a very good place for littlefs, but would be
worth improving in the future.
2023-07-25 12:32:06 -05:00