oyama / pico-vfs

Thin virtual file system for Raspberry Pi Pico
Other
13 stars 4 forks source link

Support file system statistics #60

Open Slion opened 4 weeks ago

Slion commented 4 weeks ago

Would be great to be able to get statistics from the file system. For littlefs this is done through lfs_fs_stat and lfs_fs_size.

See: https://github.com/littlefs-project/littlefs/issues/45

Slion commented 4 weeks ago

Thankfully, using our knowledge to that the littlefs struct is at offset zero in our fs context we can conveniently call littlefs functions like that:

#include <stdio.h>
#include <string.h>
#include <hardware/clocks.h>
#include <hardware/flash.h>
#include <pico/filesystem.h>
#include <pico/filesystem/blockdevice/flash.h>
#include <pico/filesystem/blockdevice/sd.h>
#include <pico/filesystem/filesystem/fat.h>
#include <pico/filesystem/filesystem/littlefs.h>
#include <pico/btstack_flash_bank.h>
#include <lfs.h>

blockdevice_t* flash;
filesystem_t *lfs;

/// @brief Print our file system info
/// Looks like littlefs does not need one sector per file.
/// It is likely capable of packing multiple files per sector.
/// This is going to be very useful.
void fs_log_info()
{
    struct lfs_fsinfo fsinfo;
    memset(&fsinfo,0,sizeof(fsinfo));
    lfs_fs_stat(lfs->context,&fsinfo);
    lfs_size_t usedBlockCount = lfs_fs_size(lfs->context);
    printf("FS: block count: %d\n",fsinfo.block_count);
    printf("FS: used / total: %dkB / %dkB\n", (usedBlockCount * fsinfo.block_size)/1024, (fsinfo.block_count * fsinfo.block_size)/1024);
    printf("FS: %dkB available from %d blocks\n", (fsinfo.block_count * fsinfo.block_size - usedBlockCount * fsinfo.block_size)/1024, fsinfo.block_count - usedBlockCount);
}

bool fs_init(void)
{
    // Don't overwrite btstack storage
    size_t eof = PICO_FLASH_BANK_STORAGE_OFFSET;
    size_t size = FLASH_SECTOR_SIZE * 10u;
    flash = blockdevice_flash_create(eof-size, size);
    lfs = filesystem_littlefs_create(500, 16);

    int err = fs_mount("/", lfs, flash);
    if (err!=0)
    {
        printf("FS: formatting \n");
        fs_format(lfs,flash);
        err = fs_mount("/", lfs, flash);
    }

    printf("FS: fs_mount: %d :%s\n", err, fs_strerror(err));

    if (err==0)
    {
        fs_log_info();
        return true;
    }

    return false;
}