Skip to content

Commit c663c55

Browse files
Free space of overwritten files in LittleFS (#7434)
* Free space of overwritten files in LittleFS Fixes #7426 LittleFS doesn't update the on-flash data structures when a file is reopened as O_TRUNC until the file is closed. This means the space of the original, inaccessible file cannot be used, causing OOS errors in cases when a large file is being overwritten. Explicitly call the file sync operation to update the on-flash metadata as soon as a file is opened. For normal files it's a no-op, but for O_TRUNC modes it will free the space, allowing full overwrite of large files. * Add host test case for change
1 parent d979b57 commit c663c55

File tree

2 files changed

+23
-0
lines changed

2 files changed

+23
-0
lines changed

libraries/LittleFS/src/LittleFS.cpp

+1
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,7 @@ FileImplPtr LittleFSImpl::open(const char* path, OpenMode openMode, AccessMode a
8787
// a directory whose name we are carrying around but which cannot be read or written
8888
return std::make_shared<LittleFSFileImpl>(this, path, nullptr, flags, creation);
8989
} else if (rc == 0) {
90+
lfs_file_sync(&_lfs, fd.get());
9091
return std::make_shared<LittleFSFileImpl>(this, path, fd, flags, creation);
9192
} else {
9293
DEBUGV("LittleFSDirImpl::openFile: rc=%d fd=%p path=`%s` openMode=%d accessMode=%d err=%d\n",

tests/host/fs/test_fs.inc

+22
Original file line numberDiff line numberDiff line change
@@ -198,6 +198,28 @@ TEST_CASE(TESTPRE "seek() pase EOF returns error (#7323)", TESTPAT)
198198
f.close();
199199
}
200200

201+
TEST_CASE(TESTPRE "Rewriting file frees space immediately (#7426)", TESTPAT)
202+
{
203+
FS_MOCK_DECLARE(64, 8, 512, "");
204+
REQUIRE(FSTYPE.begin());
205+
FSInfo inf;
206+
FSTYPE.info(inf);
207+
// Calculate the size to write per-FS, due to differing overheads
208+
int kbToWrite = (inf.totalBytes - inf.usedBytes - 8192) / 1024;
209+
// Create and overwrite a file >50% of spaceA (48/64K)
210+
for (auto x = 0; x < 2; x++) {
211+
auto f = FSTYPE.open("/file1.bin", "w");
212+
REQUIRE(f);
213+
uint8_t buff[1024];
214+
memset(buff, 0xaa, 1024);
215+
for (auto i = 0; i < kbToWrite; i++) {
216+
REQUIRE(f.write(buff, 1024));
217+
}
218+
f.close();
219+
FSTYPE.info(inf);
220+
}
221+
}
222+
201223
#ifdef FS_HAS_DIRS
202224

203225
#if FSTYPE != SDFS

0 commit comments

Comments
 (0)