在flash上格式化一个文件系统
int lfs_format(lfs_t *lfs, const struct lfs_config *cfg) {
int err = 0;
{
/* 初始化lfs结构 */
err = lfs_init(lfs, cfg);
if (err) {
LFS_TRACE("lfs_format -> %d", err);
return err;
}
// create free lookahead
/* 创建lookahead buffer,用于分配free block */
memset(lfs->free.buffer, 0, lfs->cfg->lookahead_size);
lfs->free.off = 0;
/* lookahead buffer是bitmap,因此此处会*8,并和littlefs包含的block count比较 */
lfs->free.size = lfs_min(8*lfs->cfg->lookahead_size,
lfs->cfg->block_count);
lfs->free.i = 0;
/* 对ack赋值为block count,表示所有的block都可以分配 */
lfs_alloc_ack(lfs);
// create root dir
lfs_mdir_t root;
/* 分配根目录,即两个metadata pair */
err = lfs_dir_alloc(lfs, &root);
if (err) {
goto cleanup;
}
// write one superblock
lfs_superblock_t superblock = {
.version = LFS_DISK_VERSION,
.block_size = lfs->cfg->block_size,
.block_count = lfs->cfg->block_count,
.name_max = lfs->name_max,
.file_max = lfs->file_max,
.attr_max = lfs->attr_max,
};
lfs_superblock_tole32(&superblock);
/* 把superblock写入到flash上,根目录对应的metadata pair中会至少包含3个tag,分别是LFS_TYPE_CREATE,
* LFS_TYPE_SUPERBLOCK和LFS_TYPE_INLINESTRUCT。其中LFS_TYPE_SUPERBLOCK tag存放『littlefs』字符串
* 而LFS_TYPE_INLINESTRUCT存放superblock结构体
*/
err = lfs_dir_commit(lfs, &root, LFS_MKATTRS(
{LFS_MKTAG(LFS_TYPE_CREATE, 0, 0), NULL},
{LFS_MKTAG(LFS_TYPE_SUPERBLOCK, 0, 8), "littlefs"},
{LFS_MKTAG(LFS_TYPE_INLINESTRUCT, 0, sizeof(superblock)),
&superblock}));
if (err) {
goto cleanup;
}
// sanity check that fetch works
/* 把metadata pair 0 和 1中的内容读取打root */
err = lfs_dir_fetch(lfs, &root, (const lfs_block_t[2]){0, 1});
if (err) {
goto cleanup;
}
// force compaction to prevent accidentally mounting any
// older version of littlefs that may live on disk
root.erased = false;
/* 强制提交和压缩一次,防止flash上存在旧的文件系统 */
err = lfs_dir_commit(lfs, &root, NULL, 0);
if (err) {
goto cleanup;
}
}
cleanup:
lfs_deinit(lfs);
LFS_TRACE("lfs_format -> %d", err);
return err;
}