littlefs-project / littlefs

A little fail-safe filesystem designed for microcontrollers
BSD 3-Clause "New" or "Revised" License
4.9k stars 771 forks source link

Questions regarding lfs_tag_splice(), `LFS_TYPE_SPLICE`, tempcount #903

Closed andriyndev closed 6 months ago

andriyndev commented 6 months ago

I'm trying to investigate the source code of littlefs. From what I understand, LFS_TYPE_SPLICE is the type1 for LFS_TYPE_CREATE and LFS_TYPE_DELETE, and for LFS_TYPE_CREATE lfs_tag_splice() returns 1 while for LFS_TYPE_DELETE it returns 0xff but I cannot understand what's the actual meaning of these values. For example, this return value is used in the following piece of code:

if (lfs_tag_type1(tag) == LFS_TYPE_NAME) {
                // increase count of files if necessary
                if (lfs_tag_id(tag) >= tempcount) {
                    tempcount = lfs_tag_id(tag) + 1;
                }
            } else if (lfs_tag_type1(tag) == LFS_TYPE_SPLICE) {
                tempcount += lfs_tag_splice(tag);

                if (tag == (LFS_MKTAG(LFS_TYPE_DELETE, 0, 0) |
                        (LFS_MKTAG(0, 0x3ff, 0) & tempbesttag))) {
                    tempbesttag |= 0x80000000;
                } else if (tempbesttag != -1 &&
                        lfs_tag_id(tag) <= lfs_tag_id(tempbesttag)) {
                    tempbesttag += LFS_MKTAG(0, lfs_tag_splice(tag), 0);
                }
            } else if (lfs_tag_type1(tag) == LFS_TYPE_TAIL) {

which I cannot understand so far. My assumption is that tempcount holds the currently calculated number of files in the directory but I'm not sure since in the line

tempcount += lfs_tag_splice(tag);

from what I understand, we add 1 for LFS_TYPE_CREATE, and 0xff for LFS_TYPE_DELETE that makes no sense to me. Also, in lines

                if (lfs_tag_id(tag) >= tempcount) {
                    tempcount = lfs_tag_id(tag) + 1;
                }

Does this mean that the number of files in the directory is always bigger than the number of the biggest tag id in the directory?

andriyndev commented 6 months ago

I already figured it out. Initially, I didn't pay attention that the 0xff value is cast to int8_t, i.e. it's turned into -1.

geky commented 6 months ago

Ah yes, the theory here is we could at some point add "splice" tags with deletions to the mdir larger >1. But I think this is unlikely to ever actually happen....