2 * The little filesystem
4 * Copyright (c) 2022, The littlefs authors.
5 * Copyright (c) 2017, Arm Limited. All rights reserved.
6 * SPDX-License-Identifier: BSD-3-Clause
21 // Software library version
22 // Major (top-nibble), incremented on backwards incompatible changes
23 // Minor (bottom-nibble), incremented on feature additions
24 #define LFS_VERSION 0x00020009
25 #define LFS_VERSION_MAJOR (0xffff & (LFS_VERSION >> 16))
26 #define LFS_VERSION_MINOR (0xffff & (LFS_VERSION >> 0))
28 // Version of On-disk data structures
29 // Major (top-nibble), incremented on backwards incompatible changes
30 // Minor (bottom-nibble), incremented on feature additions
31 #define LFS_DISK_VERSION 0x00020001
32 #define LFS_DISK_VERSION_MAJOR (0xffff & (LFS_DISK_VERSION >> 16))
33 #define LFS_DISK_VERSION_MINOR (0xffff & (LFS_DISK_VERSION >> 0))
39 typedef uint32_t lfs_size_t
;
40 typedef uint32_t lfs_off_t
;
42 typedef int32_t lfs_ssize_t
;
43 typedef int32_t lfs_soff_t
;
45 typedef uint32_t lfs_block_t
;
47 // Maximum name size in bytes, may be redefined to reduce the size of the
48 // info struct. Limited to <= 1022. Stored in superblock and must be
49 // respected by other littlefs drivers.
51 #define LFS_NAME_MAX 255
54 // Maximum size of a file in bytes, may be redefined to limit to support other
55 // drivers. Limited on disk to <= 2147483647. Stored in superblock and must be
56 // respected by other littlefs drivers.
58 #define LFS_FILE_MAX 2147483647
61 // Maximum size of custom attributes in bytes, may be redefined, but there is
62 // no real benefit to using a smaller LFS_ATTR_MAX. Limited to <= 1022. Stored
63 // in superblock and must be respected by other littlefs drivers.
65 #define LFS_ATTR_MAX 1022
68 // Possible error codes, these are negative to allow
69 // valid positive return values
71 LFS_ERR_OK
= 0, // No error
72 LFS_ERR_IO
= -5, // Error during device operation
73 LFS_ERR_CORRUPT
= -84, // Corrupted
74 LFS_ERR_NOENT
= -2, // No directory entry
75 LFS_ERR_EXIST
= -17, // Entry already exists
76 LFS_ERR_NOTDIR
= -20, // Entry is not a dir
77 LFS_ERR_ISDIR
= -21, // Entry is a dir
78 LFS_ERR_NOTEMPTY
= -39, // Dir is not empty
79 LFS_ERR_BADF
= -9, // Bad file number
80 LFS_ERR_FBIG
= -27, // File too large
81 LFS_ERR_INVAL
= -22, // Invalid parameter
82 LFS_ERR_NOSPC
= -28, // No space left on device
83 LFS_ERR_NOMEM
= -12, // No more memory available
84 LFS_ERR_NOATTR
= -61, // No data/attr available
85 LFS_ERR_NAMETOOLONG
= -36, // File name too long
94 // internally used types
95 LFS_TYPE_SPLICE
= 0x400,
96 LFS_TYPE_NAME
= 0x000,
97 LFS_TYPE_STRUCT
= 0x200,
98 LFS_TYPE_USERATTR
= 0x300,
99 LFS_TYPE_FROM
= 0x100,
100 LFS_TYPE_TAIL
= 0x600,
101 LFS_TYPE_GLOBALS
= 0x700,
102 LFS_TYPE_CRC
= 0x500,
104 // internally used type specializations
105 LFS_TYPE_CREATE
= 0x401,
106 LFS_TYPE_DELETE
= 0x4ff,
107 LFS_TYPE_SUPERBLOCK
= 0x0ff,
108 LFS_TYPE_DIRSTRUCT
= 0x200,
109 LFS_TYPE_CTZSTRUCT
= 0x202,
110 LFS_TYPE_INLINESTRUCT
= 0x201,
111 LFS_TYPE_SOFTTAIL
= 0x600,
112 LFS_TYPE_HARDTAIL
= 0x601,
113 LFS_TYPE_MOVESTATE
= 0x7ff,
114 LFS_TYPE_CCRC
= 0x500,
115 LFS_TYPE_FCRC
= 0x5ff,
117 // internal chip sources
118 LFS_FROM_NOOP
= 0x000,
119 LFS_FROM_MOVE
= 0x101,
120 LFS_FROM_USERATTRS
= 0x102,
124 enum lfs_open_flags
{
126 LFS_O_RDONLY
= 1, // Open a file as read only
128 LFS_O_WRONLY
= 2, // Open a file as write only
129 LFS_O_RDWR
= 3, // Open a file as read and write
130 LFS_O_CREAT
= 0x0100, // Create a file if it does not exist
131 LFS_O_EXCL
= 0x0200, // Fail if a file already exists
132 LFS_O_TRUNC
= 0x0400, // Truncate the existing file to zero size
133 LFS_O_APPEND
= 0x0800, // Move to end of file on every write
136 // internally used flags
138 LFS_F_DIRTY
= 0x010000, // File does not match storage
139 LFS_F_WRITING
= 0x020000, // File has been written since last flush
141 LFS_F_READING
= 0x040000, // File has been read since last flush
143 LFS_F_ERRED
= 0x080000, // An error occurred during write
145 LFS_F_INLINE
= 0x100000, // Currently inlined in directory entry
149 enum lfs_whence_flags
{
150 LFS_SEEK_SET
= 0, // Seek relative to an absolute position
151 LFS_SEEK_CUR
= 1, // Seek relative to the current file position
152 LFS_SEEK_END
= 2, // Seek relative to the end of the file
156 // Configuration provided during initialization of the littlefs
158 // Opaque user provided context that can be used to pass
159 // information to the block device operations
162 // Read a region in a block. Negative error codes are propagated
164 int (*read
)(const struct lfs_config
*c
, lfs_block_t block
,
165 lfs_off_t off
, void *buffer
, lfs_size_t size
);
167 // Program a region in a block. The block must have previously
168 // been erased. Negative error codes are propagated to the user.
169 // May return LFS_ERR_CORRUPT if the block should be considered bad.
170 int (*prog
)(const struct lfs_config
*c
, lfs_block_t block
,
171 lfs_off_t off
, const void *buffer
, lfs_size_t size
);
173 // Erase a block. A block must be erased before being programmed.
174 // The state of an erased block is undefined. Negative error codes
175 // are propagated to the user.
176 // May return LFS_ERR_CORRUPT if the block should be considered bad.
177 int (*erase
)(const struct lfs_config
*c
, lfs_block_t block
);
179 // Sync the state of the underlying block device. Negative error codes
180 // are propagated to the user.
181 int (*sync
)(const struct lfs_config
*c
);
183 #ifdef LFS_THREADSAFE
184 // Lock the underlying block device. Negative error codes
185 // are propagated to the user.
186 int (*lock
)(const struct lfs_config
*c
);
188 // Unlock the underlying block device. Negative error codes
189 // are propagated to the user.
190 int (*unlock
)(const struct lfs_config
*c
);
193 // Minimum size of a block read in bytes. All read operations will be a
194 // multiple of this value.
195 lfs_size_t read_size
;
197 // Minimum size of a block program in bytes. All program operations will be
198 // a multiple of this value.
199 lfs_size_t prog_size
;
201 // Size of an erasable block in bytes. This does not impact ram consumption
202 // and may be larger than the physical erase size. However, non-inlined
203 // files take up at minimum one block. Must be a multiple of the read and
205 lfs_size_t block_size
;
207 // Number of erasable blocks on the device. Defaults to block_count stored
208 // on disk when zero.
209 lfs_size_t block_count
;
211 // Number of erase cycles before littlefs evicts metadata logs and moves
212 // the metadata to another block. Suggested values are in the
213 // range 100-1000, with large values having better performance at the cost
214 // of less consistent wear distribution.
216 // Set to -1 to disable block-level wear-leveling.
217 int32_t block_cycles
;
219 // Size of block caches in bytes. Each cache buffers a portion of a block in
220 // RAM. The littlefs needs a read cache, a program cache, and one additional
221 // cache per file. Larger caches can improve performance by storing more
222 // data and reducing the number of disk accesses. Must be a multiple of the
223 // read and program sizes, and a factor of the block size.
224 lfs_size_t cache_size
;
226 // Size of the lookahead buffer in bytes. A larger lookahead buffer
227 // increases the number of blocks found during an allocation pass. The
228 // lookahead buffer is stored as a compact bitmap, so each byte of RAM
229 // can track 8 blocks.
230 lfs_size_t lookahead_size
;
232 // Threshold for metadata compaction during lfs_fs_gc in bytes. Metadata
233 // pairs that exceed this threshold will be compacted during lfs_fs_gc.
234 // Defaults to ~88% block_size when zero, though the default may change
237 // Note this only affects lfs_fs_gc. Normal compactions still only occur
240 // Set to -1 to disable metadata compaction during lfs_fs_gc.
241 lfs_size_t compact_thresh
;
243 // Optional statically allocated read buffer. Must be cache_size.
244 // By default lfs_malloc is used to allocate this buffer.
247 // Optional statically allocated program buffer. Must be cache_size.
248 // By default lfs_malloc is used to allocate this buffer.
251 // Optional statically allocated lookahead buffer. Must be lookahead_size.
252 // By default lfs_malloc is used to allocate this buffer.
253 void *lookahead_buffer
;
255 // Optional upper limit on length of file names in bytes. No downside for
256 // larger names except the size of the info struct which is controlled by
257 // the LFS_NAME_MAX define. Defaults to LFS_NAME_MAX or name_max stored on
261 // Optional upper limit on files in bytes. No downside for larger files
262 // but must be <= LFS_FILE_MAX. Defaults to LFS_FILE_MAX or file_max stored
263 // on disk when zero.
266 // Optional upper limit on custom attributes in bytes. No downside for
267 // larger attributes size but must be <= LFS_ATTR_MAX. Defaults to
268 // LFS_ATTR_MAX or attr_max stored on disk when zero.
271 // Optional upper limit on total space given to metadata pairs in bytes. On
272 // devices with large blocks (e.g. 128kB) setting this to a low size (2-8kB)
273 // can help bound the metadata compaction time. Must be <= block_size.
274 // Defaults to block_size when zero.
275 lfs_size_t metadata_max
;
277 // Optional upper limit on inlined files in bytes. Inlined files live in
278 // metadata and decrease storage requirements, but may be limited to
279 // improve metadata-related performance. Must be <= cache_size, <=
280 // attr_max, and <= block_size/8. Defaults to the largest possible
281 // inline_max when zero.
283 // Set to -1 to disable inlined files.
284 lfs_size_t inline_max
;
286 #ifdef LFS_MULTIVERSION
287 // On-disk version to use when writing in the form of 16-bit major version
288 // + 16-bit minor version. This limiting metadata to what is supported by
289 // older minor versions. Note that some features will be lost. Defaults to
290 // to the most recent minor version when zero.
291 uint32_t disk_version
;
295 // File info structure
297 // Type of the file, either LFS_TYPE_REG or LFS_TYPE_DIR
300 // Size of the file, only valid for REG files. Limited to 32-bits.
303 // Name of the file stored as a null-terminated string. Limited to
304 // LFS_NAME_MAX+1, which can be changed by redefining LFS_NAME_MAX to
305 // reduce RAM. LFS_NAME_MAX is stored in superblock and must be
306 // respected by other littlefs drivers.
307 char name
[LFS_NAME_MAX
+1];
310 // Filesystem info structure
313 uint32_t disk_version
;
315 // Size of a logical block in bytes.
316 lfs_size_t block_size
;
318 // Number of logical blocks in filesystem.
319 lfs_size_t block_count
;
321 // Upper limit on the length of file names in bytes.
324 // Upper limit on the size of files in bytes.
327 // Upper limit on the size of custom attributes in bytes.
331 // Custom attribute structure, used to describe custom attributes
332 // committed atomically during file writes.
334 // 8-bit type of attribute, provided by user and used to
335 // identify the attribute
338 // Pointer to buffer containing the attribute
341 // Size of attribute in bytes, limited to LFS_ATTR_MAX
345 // Optional configuration provided during lfs_file_opencfg
346 struct lfs_file_config
{
347 // Optional statically allocated file buffer. Must be cache_size.
348 // By default lfs_malloc is used to allocate this buffer.
351 // Optional list of custom attributes related to the file. If the file
352 // is opened with read access, these attributes will be read from disk
353 // during the open call. If the file is opened with write access, the
354 // attributes will be written to disk every file sync or close. This
355 // write occurs atomically with update to the file's contents.
357 // Custom attributes are uniquely identified by an 8-bit type and limited
358 // to LFS_ATTR_MAX bytes. When read, if the stored attribute is smaller
359 // than the buffer, it will be padded with zeros. If the stored attribute
360 // is larger, then it will be silently truncated. If the attribute is not
361 // found, it will be created implicitly.
362 struct lfs_attr
*attrs
;
364 // Number of custom attributes in the list
365 lfs_size_t attr_count
;
369 /// internal littlefs data structures ///
370 typedef struct lfs_cache
{
377 typedef struct lfs_mdir
{
388 // littlefs directory type
389 typedef struct lfs_dir
{
390 struct lfs_dir
*next
;
399 // littlefs file type
400 typedef struct lfs_file
{
401 struct lfs_file
*next
;
417 const struct lfs_file_config
*cfg
;
420 typedef struct lfs_superblock
{
422 lfs_size_t block_size
;
423 lfs_size_t block_count
;
429 typedef struct lfs_gstate
{
434 // The littlefs filesystem type
441 struct lfs_mlist
*next
;
452 struct lfs_lookahead
{
460 const struct lfs_config
*cfg
;
461 lfs_size_t block_count
;
465 lfs_size_t inline_max
;
473 /// Filesystem functions ///
476 // Format a block device with the littlefs
478 // Requires a littlefs object and config struct. This clobbers the littlefs
479 // object, and does not leave the filesystem mounted. The config struct must
480 // be zeroed for defaults and backwards compatibility.
482 // Returns a negative error code on failure.
483 int lfs_format(lfs_t
*lfs
, const struct lfs_config
*config
);
488 // Requires a littlefs object and config struct. Multiple filesystems
489 // may be mounted simultaneously with multiple littlefs objects. Both
490 // lfs and config must be allocated while mounted. The config struct must
491 // be zeroed for defaults and backwards compatibility.
493 // Returns a negative error code on failure.
494 int lfs_mount(lfs_t
*lfs
, const struct lfs_config
*config
);
496 // Unmounts a littlefs
498 // Does nothing besides releasing any allocated resources.
499 // Returns a negative error code on failure.
500 int lfs_unmount(lfs_t
*lfs
);
502 /// General operations ///
505 // Removes a file or directory
507 // If removing a directory, the directory must be empty.
508 // Returns a negative error code on failure.
509 int lfs_remove(lfs_t
*lfs
, const char *path
);
513 // Rename or move a file or directory
515 // If the destination exists, it must match the source in type.
516 // If the destination is a directory, the directory must be empty.
518 // Returns a negative error code on failure.
519 int lfs_rename(lfs_t
*lfs
, const char *oldpath
, const char *newpath
);
522 // Find info about a file or directory
524 // Fills out the info structure, based on the specified file or directory.
525 // Returns a negative error code on failure.
526 int lfs_stat(lfs_t
*lfs
, const char *path
, struct lfs_info
*info
);
528 // Get a custom attribute
530 // Custom attributes are uniquely identified by an 8-bit type and limited
531 // to LFS_ATTR_MAX bytes. When read, if the stored attribute is smaller than
532 // the buffer, it will be padded with zeros. If the stored attribute is larger,
533 // then it will be silently truncated. If no attribute is found, the error
534 // LFS_ERR_NOATTR is returned and the buffer is filled with zeros.
536 // Returns the size of the attribute, or a negative error code on failure.
537 // Note, the returned size is the size of the attribute on disk, irrespective
538 // of the size of the buffer. This can be used to dynamically allocate a buffer
539 // or check for existence.
540 lfs_ssize_t
lfs_getattr(lfs_t
*lfs
, const char *path
,
541 uint8_t type
, void *buffer
, lfs_size_t size
);
544 // Set custom attributes
546 // Custom attributes are uniquely identified by an 8-bit type and limited
547 // to LFS_ATTR_MAX bytes. If an attribute is not found, it will be
548 // implicitly created.
550 // Returns a negative error code on failure.
551 int lfs_setattr(lfs_t
*lfs
, const char *path
,
552 uint8_t type
, const void *buffer
, lfs_size_t size
);
556 // Removes a custom attribute
558 // If an attribute is not found, nothing happens.
560 // Returns a negative error code on failure.
561 int lfs_removeattr(lfs_t
*lfs
, const char *path
, uint8_t type
);
565 /// File operations ///
567 #ifndef LFS_NO_MALLOC
570 // The mode that the file is opened in is determined by the flags, which
571 // are values from the enum lfs_open_flags that are bitwise-ored together.
573 // Returns a negative error code on failure.
574 int lfs_file_open(lfs_t
*lfs
, lfs_file_t
*file
,
575 const char *path
, int flags
);
577 // if LFS_NO_MALLOC is defined, lfs_file_open() will fail with LFS_ERR_NOMEM
578 // thus use lfs_file_opencfg() with config.buffer set.
581 // Open a file with extra configuration
583 // The mode that the file is opened in is determined by the flags, which
584 // are values from the enum lfs_open_flags that are bitwise-ored together.
586 // The config struct provides additional config options per file as described
587 // above. The config struct must remain allocated while the file is open, and
588 // the config struct must be zeroed for defaults and backwards compatibility.
590 // Returns a negative error code on failure.
591 int lfs_file_opencfg(lfs_t
*lfs
, lfs_file_t
*file
,
592 const char *path
, int flags
,
593 const struct lfs_file_config
*config
);
597 // Any pending writes are written out to storage as though
598 // sync had been called and releases any allocated resources.
600 // Returns a negative error code on failure.
601 int lfs_file_close(lfs_t
*lfs
, lfs_file_t
*file
);
603 // Synchronize a file on storage
605 // Any pending writes are written out to storage.
606 // Returns a negative error code on failure.
607 int lfs_file_sync(lfs_t
*lfs
, lfs_file_t
*file
);
609 // Read data from file
611 // Takes a buffer and size indicating where to store the read data.
612 // Returns the number of bytes read, or a negative error code on failure.
613 lfs_ssize_t
lfs_file_read(lfs_t
*lfs
, lfs_file_t
*file
,
614 void *buffer
, lfs_size_t size
);
617 // Write data to file
619 // Takes a buffer and size indicating the data to write. The file will not
620 // actually be updated on the storage until either sync or close is called.
622 // Returns the number of bytes written, or a negative error code on failure.
623 lfs_ssize_t
lfs_file_write(lfs_t
*lfs
, lfs_file_t
*file
,
624 const void *buffer
, lfs_size_t size
);
627 // Change the position of the file
629 // The change in position is determined by the offset and whence flag.
630 // Returns the new position of the file, or a negative error code on failure.
631 lfs_soff_t
lfs_file_seek(lfs_t
*lfs
, lfs_file_t
*file
,
632 lfs_soff_t off
, int whence
);
635 // Truncates the size of the file to the specified size
637 // Returns a negative error code on failure.
638 int lfs_file_truncate(lfs_t
*lfs
, lfs_file_t
*file
, lfs_off_t size
);
641 // Return the position of the file
643 // Equivalent to lfs_file_seek(lfs, file, 0, LFS_SEEK_CUR)
644 // Returns the position of the file, or a negative error code on failure.
645 lfs_soff_t
lfs_file_tell(lfs_t
*lfs
, lfs_file_t
*file
);
647 // Change the position of the file to the beginning of the file
649 // Equivalent to lfs_file_seek(lfs, file, 0, LFS_SEEK_SET)
650 // Returns a negative error code on failure.
651 int lfs_file_rewind(lfs_t
*lfs
, lfs_file_t
*file
);
653 // Return the size of the file
655 // Similar to lfs_file_seek(lfs, file, 0, LFS_SEEK_END)
656 // Returns the size of the file, or a negative error code on failure.
657 lfs_soff_t
lfs_file_size(lfs_t
*lfs
, lfs_file_t
*file
);
660 /// Directory operations ///
663 // Create a directory
665 // Returns a negative error code on failure.
666 int lfs_mkdir(lfs_t
*lfs
, const char *path
);
671 // Once open a directory can be used with read to iterate over files.
672 // Returns a negative error code on failure.
673 int lfs_dir_open(lfs_t
*lfs
, lfs_dir_t
*dir
, const char *path
);
677 // Releases any allocated resources.
678 // Returns a negative error code on failure.
679 int lfs_dir_close(lfs_t
*lfs
, lfs_dir_t
*dir
);
681 // Read an entry in the directory
683 // Fills out the info structure, based on the specified file or directory.
684 // Returns a positive value on success, 0 at the end of directory,
685 // or a negative error code on failure.
686 int lfs_dir_read(lfs_t
*lfs
, lfs_dir_t
*dir
, struct lfs_info
*info
);
688 // Change the position of the directory
690 // The new off must be a value previous returned from tell and specifies
691 // an absolute offset in the directory seek.
693 // Returns a negative error code on failure.
694 int lfs_dir_seek(lfs_t
*lfs
, lfs_dir_t
*dir
, lfs_off_t off
);
696 // Return the position of the directory
698 // The returned offset is only meant to be consumed by seek and may not make
699 // sense, but does indicate the current position in the directory iteration.
701 // Returns the position of the directory, or a negative error code on failure.
702 lfs_soff_t
lfs_dir_tell(lfs_t
*lfs
, lfs_dir_t
*dir
);
704 // Change the position of the directory to the beginning of the directory
706 // Returns a negative error code on failure.
707 int lfs_dir_rewind(lfs_t
*lfs
, lfs_dir_t
*dir
);
710 /// Filesystem-level filesystem operations
712 // Find on-disk info about the filesystem
714 // Fills out the fsinfo structure based on the filesystem found on-disk.
715 // Returns a negative error code on failure.
716 int lfs_fs_stat(lfs_t
*lfs
, struct lfs_fsinfo
*fsinfo
);
718 // Finds the current size of the filesystem
720 // Note: Result is best effort. If files share COW structures, the returned
721 // size may be larger than the filesystem actually is.
723 // Returns the number of allocated blocks, or a negative error code on failure.
724 lfs_ssize_t
lfs_fs_size(lfs_t
*lfs
);
726 // Traverse through all blocks in use by the filesystem
728 // The provided callback will be called with each block address that is
729 // currently in use by the filesystem. This can be used to determine which
730 // blocks are in use or how much of the storage is available.
732 // Returns a negative error code on failure.
733 int lfs_fs_traverse(lfs_t
*lfs
, int (*cb
)(void*, lfs_block_t
), void *data
);
736 // Attempt to make the filesystem consistent and ready for writing
738 // Calling this function is not required, consistency will be implicitly
739 // enforced on the first operation that writes to the filesystem, but this
740 // function allows the work to be performed earlier and without other
741 // filesystem changes.
743 // Returns a negative error code on failure.
744 int lfs_fs_mkconsistent(lfs_t
*lfs
);
748 // Attempt any janitorial work
751 // 1. Calls mkconsistent if not already consistent
752 // 2. Compacts metadata > compact_thresh
753 // 3. Populates the block allocator
755 // Though additional janitorial work may be added in the future.
757 // Calling this function is not required, but may allow the offloading of
758 // expensive janitorial work to a less time-critical code path.
760 // Returns a negative error code on failure. Accomplishing nothing is not
762 int lfs_fs_gc(lfs_t
*lfs
);
766 // Grows the filesystem to a new size, updating the superblock with the new
769 // Note: This is irreversible.
771 // Returns a negative error code on failure.
772 int lfs_fs_grow(lfs_t
*lfs
, lfs_size_t block_count
);
777 // Attempts to migrate a previous version of littlefs
779 // Behaves similarly to the lfs_format function. Attempts to mount
780 // the previous version of littlefs and update the filesystem so it can be
781 // mounted with the current version of littlefs.
783 // Requires a littlefs object and config struct. This clobbers the littlefs
784 // object, and does not leave the filesystem mounted. The config struct must
785 // be zeroed for defaults and backwards compatibility.
787 // Returns a negative error code on failure.
788 int lfs_migrate(lfs_t
*lfs
, const struct lfs_config
*cfg
);