littlefs_open: sync the file only when O_TRUNC is specified

Because sync is a rather expensive operation.

While I'm here, improve the comment after the recent discussion
in https://github.com/apache/nuttx/pull/2913.

IMHO, we should not perform the sync even for O_TRUNC.
But I'm not going to propose the change for now.

Signed-off-by: YAMAMOTO Takashi <yamamoto@midokura.com>
This commit is contained in:
YAMAMOTO Takashi
2025-04-10 12:23:42 +09:00
committed by Xiang Xiao
parent db91b3b53c
commit b59373b270

View File

@@ -424,11 +424,26 @@ static int littlefs_open(FAR struct file *filep, FAR const char *relpath,
}
}
/* Sync here in case of O_TRUNC haven't actually done immediately,
* e.g. total 8M, fileA 6M, O_TRUNC re-wrting fileA 6M, meet error.
/* In case of O_TRUNC, sync to commit the truncation.
*
* For example, consider a 6MB file on an 8MB filesystem.
* Open the file with O_TRUNC and (re)write some data until it grows
* to 6MB. Without this sync, it ends up with ENOSPC because
* littlefs doesn't commit the updates until sync/close and thus
* doesn't recycle the truncated space. Although it's normal for
* filesystems like littlefs, we automatically sync the truncation
* here to allow such a sequence to succeed, assuming it's what many
* of NuttX users expect.
*
* CAVEAT: On the other hand, this might surprise users who are familiar
* with the bare littlefs semantics.
*/
lfs_file_sync(&fs->lfs, &priv->file);
if (oflags & LFS_O_TRUNC)
{
lfs_file_sync(&fs->lfs, &priv->file);
}
nxmutex_unlock(&fs->lock);
/* Attach the private date to the struct file instance */