littlefs-project / littlefs

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

Add lfs_fs_grow to enable limited resizing of the filesystem #872

Closed geky closed 9 months ago

geky commented 10 months ago

Originally proposed by @kaetemi, this API allows you to change the size of the filesystem on disk to take advantage of additional space if it becomes available:

  cfg.block_count = 1024;

  int err = lfs_mount(lfs, cfg);
  if (err) {
      return err;
  }

  struct lfs_fsstat fsstat;
  err = lfs_fs_stat(lfs, &fsstat);
  if (err) {
      return err;
  }
  printf("block_count: %d\n", fsstat.block_count); // prints 1024

  err = lfs_fs_grow(lfs, 2048);
  if (err) {
      return err;
  }

  struct lfs_fsstat fsstat;
  err = lfs_fs_stat(lfs, &fsstat);
  if (err) {
      return err;
  }
  printf("block_count: %d\n", fsstat.block_count); // prints 2048

If you want to automatically resize littlefs to the full disk size every mount, this can be done by using these two calls as your "mount" operation:

  lfs_size_t required_block_count = DISK_SIZE / BLOCK_SIZE;

  // unknown block_count
  cfg.block_count = 0;

  // mount and resize if disk has grown
  int err = lfs_mount(lfs, cfg);
  if (err) {
      return err;
  }

  err = lfs_fs_grow(lfs, required_block_count);
  if (err) {
      return err;
  }

See https://github.com/littlefs-project/littlefs/pull/702, https://github.com/littlefs-project/littlefs/issues/279, and https://github.com/littlefs-project/littlefs/pull/753 for related discussions.

This depends on https://github.com/littlefs-project/littlefs/pull/866, which makes block_size optional

geky-bot commented 10 months ago
Tests passed ✓, Code: 16810 B (+0.8%), Stack: 1432 B (+0.0%), Structs: 800 B (+1.5%) | | Code | Stack | Structs | | Coverage | |:--|-----:|------:|--------:|:--|---------:| | Default | 16810 B (+0.8%) | 1432 B (+0.0%) | 800 B (+1.5%) | Lines | 2346/2522 lines (+0.2%) | | Readonly | 6130 B (+0.1%) | 448 B (+0.0%) | 800 B (+1.5%) | Branches | 1200/1526 branches (-0.0%) | | Threadsafe | 17670 B (+0.9%) | 1432 B (+0.0%) | 808 B (+1.5%) | | **Benchmarks** | | Multiversion | 16870 B (+0.7%) | 1432 B (+0.0%) | 804 B (+1.5%) | Readed | 29369693876 B (+0.0%) | | Migrate | 18486 B (+0.7%) | 1736 B (+0.0%) | 804 B (+1.5%) | Proged | 1482874766 B (+0.0%) | | Error-asserts | 17470 B (+0.9%) | 1424 B (+0.0%) | 800 B (+1.5%) | Erased | 1568888832 B (+0.0%) |