text
stringlengths
1
3.82k
__index_level_0__
int64
0
366
Virtual Filesystem Component Overview Virtual filesystem (VFS) component provides a unified interface for drivers which can perform operations on file-like objects. These can be real filesystems (FAT, SPIFFS, etc.) or device drivers which provide a file-like interface. This component allows C library functions, such as fopen and fprintf, to work with FS drivers. At a high level, each FS driver is associated with some path prefix. When one of C library functions needs to open a file, the VFS component searches for the FS driver associated with the file path and forwards the call to that driver. VFS also forwards read, write, and other calls for the given file to the same FS driver. For example, one can register a FAT filesystem driver with the ``/fat`` prefix and call ``fopen("/fat/file.txt", "w")``. Then the VFS component calls the function ``open`` of the FAT driver and pass the argument ``/file.txt`` to it together with appropriate mode flags. All subsequent calls to C library functions for the returned ``FILE*`` stream will also be forwarded to the FAT driver.
64
FS Registration To register an FS driver, an application needs to define an instance of the :cpp:type:`esp_vfs_t` structure and populate it with function pointers to FS APIs: .. highlight:: c :: esp_vfs_t myfs = { .flags = ESP_VFS_FLAG_DEFAULT, .write = &myfs_write, .open = &myfs_open, .fstat = &myfs_fstat, .close = &myfs_close, .read = &myfs_read, }; ESP_ERROR_CHECK(esp_vfs_register("/data", &myfs, NULL)); Depending on the way how the FS driver declares its API functions, either ``read``, ``write``, etc., or ``read_p``, ``write_p``, etc., should be used. Case 1: API functions are declared without an extra context pointer (the FS driver is a singleton):: ssize_t myfs_write(int fd, const void * data, size_t size); // In definition of esp_vfs_t: .flags = ESP_VFS_FLAG_DEFAULT, .write = &myfs_write, // ... other members initialized // When registering FS, context pointer (third argument) is NULL: ESP_ERROR_CHECK(esp_vfs_register("/data", &myfs, NULL)); Case 2: API functions are declared with an extra context pointer (the FS driver supports multiple instances):: ssize_t myfs_write(myfs_t* fs, int fd, const void * data, size_t size); // In definition of esp_vfs_t: .
64
flags = ESP_VFS_FLAG_CONTEXT_PTR, .write_p = &myfs_write, // ... other members initialized // When registering FS, pass the FS context pointer into the third argument // (hypothetical myfs_mount function is used for illustrative purposes) myfs_t* myfs_inst1 = myfs_mount(partition1->offset, partition1->size); ESP_ERROR_CHECK(esp_vfs_register("/data1", &myfs, myfs_inst1)); // Can register another instance: myfs_t* myfs_inst2 = myfs_mount(partition2->offset, partition2->size); ESP_ERROR_CHECK(esp_vfs_register("/data2", &myfs, myfs_inst2)); Synchronous Input/Output Multiplexing Synchronous input/output multiplexing by :cpp:func:`select` is supported in the VFS component. The implementation works in the following way. Non-Socket VFS Drivers """""""""""""""""""""" If you want to use :cpp:func:`select` with a file descriptor belonging to a non-socket VFS driver, then you need to register the driver with functions :cpp:func:`start_select` and :cpp:func:`end_select` similarly to the following example: .
64
. highlight:: c :: // In definition of esp_vfs_t: .start_select = &uart_start_select, .end_select = &uart_end_select, // ... other members initialized :cpp:func:`start_select` is called for setting up the environment for detection of read/write/error conditions on file descriptors belonging to the given VFS driver. :cpp:func:`end_select` is called to stop/deinitialize/free the environment which was setup by :cpp:func:`start_select`. .. note:: :cpp:func:`end_select` might be called without a previous :cpp:func:`start_select` call in some rare circumstances. :cpp:func:`end_select` should fail gracefully if this is the case (i.e., should not crash but return an error instead). Please refer to the reference implementation for the UART peripheral in :component_file:`esp_driver_uart/src/uart_vfs.c` and most particularly to the functions :cpp:func:`uart_vfs_dev_register`, :cpp:func:`uart_start_select`, and :cpp:func:`uart_end_select` for more information. Please check the following examples that demonstrate the use of :cpp:func:`select` with VFS file descriptors: - :example:`peripherals/uart/uart_select` - :example:`system/select` Socket VFS Drivers """""""""""""""""" A socket VFS driver is using its own internal implementation of :cpp:func:`select` and non-socket VFS drivers notify it upon read/write/error conditions.
64
A socket VFS driver needs to be registered with the following functions defined: .. highlight:: c :: // In definition of esp_vfs_t: .socket_select = &lwip_select, .get_socket_select_semaphore = &lwip_get_socket_select_semaphore, .stop_socket_select = &lwip_stop_socket_select, .stop_socket_select_isr = &lwip_stop_socket_select_isr, // ... other members initialized :cpp:func:`socket_select` is the internal implementation of :cpp:func:`select` for the socket driver. It works only with file descriptors belonging to the socket VFS. :cpp:func:`get_socket_select_semaphore` returns the signalization object (semaphore) which is used in non-socket drivers to stop the waiting in :cpp:func:`socket_select`. :cpp:func:`stop_socket_select` call is used to stop the waiting in :cpp:func:`socket_select` by passing the object returned by :cpp:func:`get_socket_select_semaphore`. :cpp:func:`stop_socket_select_isr` has the same functionality as :cpp:func:`stop_socket_select` but it can be used from ISR.
64
Please see :component_file:`lwip/port/esp32xx/vfs_lwip.c` for a reference socket driver implementation using LWIP. .. note:: If you use :cpp:func:`select` for socket file descriptors only then you can disable the :ref:`CONFIG_VFS_SUPPORT_SELECT` option to reduce the code size and improve performance. You should not change the socket driver during an active :cpp:func:`select` call or you might experience some undefined behavior. Paths Each registered FS has a path prefix associated with it. This prefix can be considered as a "mount point" of this partition. In case when mount points are nested, the mount point with the longest matching path prefix is used when opening the file. For instance, suppose that the following filesystems are registered in VFS: - FS 1 on /data - FS 2 on /data/static Then: - FS 1 will be used when opening a file called ``/data/log.txt`` - FS 2 will be used when opening a file called ``/data/static/index.html`` - Even if ``/index.html"`` does not exist in FS 2, FS 1 will **not** be searched for ``/static/index.
64
html``. As a general rule, mount point names must start with the path separator (``/``) and must contain at least one character after path separator. However, an empty mount point name is also supported and might be used in cases when an application needs to provide a "fallback" filesystem or to override VFS functionality altogether. Such filesystem will be used if no prefix matches the path given. VFS does not handle dots (``.``) in path names in any special way. VFS does not treat ``..`` as a reference to the parent directory. In the above example, using a path ``/data/static/../log.txt`` will not result in a call to FS 1 to open ``/log.txt``. Specific FS drivers (such as FATFS) might handle dots in file names differently. When opening files, the FS driver receives only relative paths to files. For example: VFS does not impose any limit on total file path length, but it does limit the FS path prefix to ``ESP_VFS_PATH_MAX`` characters. Individual FS drivers may have their own filename length limitations.
64
File Descriptors File descriptors are small positive integers from ``0`` to ``FD_SETSIZE - 1``, where ``FD_SETSIZE`` is defined in ``sys/select.h``. The largest file descriptors (configured by ``CONFIG_LWIP_MAX_SOCKETS``) are reserved for sockets. The VFS component contains a lookup-table called ``s_fd_table`` for mapping global file descriptors to VFS driver indexes registered in the ``s_vfs`` array. Standard IO Streams (``stdin``, ``stdout``, ``stderr``) If the menuconfig option ``UART for console output`` is not set to ``None``, then ``stdin``, ``stdout``, and ``stderr`` are configured to read from, and write to, a UART. It is possible to use UART0 or UART1 for standard IO. By default, UART0 is used with 115200 baud rate; TX pin is GPIO1; RX pin is GPIO3. These parameters can be changed in menuconfig. Writing to ``stdout`` or ``stderr`` sends characters to the UART transmit FIFO. Reading from ``stdin`` retrieves characters from the UART receive FIFO. By default, VFS uses simple functions for reading from and writing to UART.
64
Writes busy-wait until all data is put into UART FIFO, and reads are non-blocking, returning only the data present in the FIFO. Due to this non-blocking read behavior, higher level C library calls, such as ``fscanf("%d\n", &var);``, might not have desired results. Applications which use the UART driver can instruct VFS to use the driver's interrupt driven, blocking read and write functions instead. This can be done using a call to the :cpp:func:`uart_vfs_dev_use_driver` function. It is also possible to revert to the basic non-blocking functions using a call to :cpp:func:`uart_vfs_dev_use_nonblocking`. VFS also provides an optional newline conversion feature for input and output. Internally, most applications send and receive lines terminated by the LF (''\n'') character. Different terminal programs may require different line termination, such as CR or CRLF. Applications can configure this separately for input and output either via menuconfig, or by calls to the functions :cpp:func:`uart_vfs_dev_port_set_rx_line_endings` and :cpp:func:`uart_vfs_dev_port_set_tx_line_endings`.
64
Standard Streams and FreeRTOS Tasks ``FILE`` objects for ``stdin``, ``stdout``, and ``stderr`` are shared between all FreeRTOS tasks, but the pointers to these objects are stored in per-task ``struct _reent``. The following code is transferred to ``fprintf(__getreent()->_stderr, "42\n");`` by the preprocessor: .. highlight:: c :: fprintf(stderr, "42\n"); The ``__getreent()`` function returns a per-task pointer to ``struct _reent`` in newlib libc. This structure is allocated on the TCB of each task. When a task is initialized, ``_stdin``, ``_stdout``, and ``_stderr`` members of ``struct _reent`` are set to the values of ``_stdin``, ``_stdout``, and ``_stderr`` of ``_GLOBAL_REENT`` (i.e., the structure which is used before FreeRTOS is started). Such a design has the following consequences: - It is possible to set ``stdin``, ``stdout``, and ``stderr`` for any given task without affecting other tasks, e.g., by doing ``stdin = fopen("/dev/uart/1", "r")``. - Closing default ``stdin``, ``stdout``, or ``stderr`` using ``fclose`` closes the ``FILE`` stream object, which will affect all other tasks.
64
- To change the default ``stdin``, ``stdout``, ``stderr`` streams for new tasks, modify ``_GLOBAL_REENT->_stdin`` (``_stdout``, ``_stderr``) before creating the task. ``eventfd()`` ``eventfd()`` call is a powerful tool to notify a ``select()`` based loop of custom events. The ``eventfd()`` implementation in ESP-IDF is generally the same as described in `man(2) eventfd `_ except for: - ``esp_vfs_eventfd_register()`` has to be called before calling ``eventfd()`` - Options ``EFD_CLOEXEC``, ``EFD_NONBLOCK`` and ``EFD_SEMAPHORE`` are not supported in flags. - Option ``EFD_SUPPORT_ISR`` has been added in flags. This flag is required to read and write the eventfd in an interrupt handler. Note that creating an eventfd with ``EFD_SUPPORT_ISR`` will cause interrupts to be temporarily disabled when reading, writing the file and during the beginning and the ending of the ``select()`` when this file is set. API Reference .. include-build-file:: inc/esp_vfs.inc .. include-build-file:: inc/esp_vfs_dev.
64
inc .. include-build-file:: inc/uart_vfs.inc .. include-build-file:: inc/esp_vfs_eventfd.inc
64
.. include:: /../../components/nvs_flash/nvs_partition_tool/README.rst
65
:orphan: .. linked from fatfs.rst Generating and Parsing FATFS on Host This document is intended mainly for developers of Python tools :component_file:`fatfsgen.py ` and :component_file:`fatfsparse.py `, and people with special interest in these tools and implementation of the FAT file system in ESP-IDF. If you are interested in using these tools, please refer to the user guide at :ref:`fatfs-partition-generator`. The FAT file system is composed of various logical units. The units are used to store general information about the file system, allocations, content of files and directories, and file's metadata. The tools ``fatfsgen.py`` and ``fatfsparse.py`` are used to implement the FAT file system while considering all these logical units, and they also provide support for wear levelling. FAT File System Generator and Parser Design This section describes particular units of the FAT file system generator and parser design. The implementation aims to create a valid model of the FAT structure with a focus on macro operations, generating and parsing the whole partition without modifying it in the run (mounting).
66
.. figure:: ../../../_static/classes_fatfsgen.svg :align: center :alt: Class diagram FAT File System Generator and Parser Design Architecture Class FATFS This is the most general entity responsible for modeling the FAT file system. It is composed of **FATFSState** (holding metadata and boot sector), **FAT** (holding file allocation table), and **Directory** (representing the root directory required by FAT12 and FAT16). The class processes all the requirements for the partition, analyses the local folder dedicated to transforming it into a binary image, and generates an internal representation of the local folder. Then, the class can generate a binary image from the internal FAT file system model. Class WLFATFS The class extends the functionality of the class **FATFS**. It implements an encapsulation of the file system into the wear levelling, by adding the "dummy" sector for balancing the load (a redundant sector, see the section :ref:`fafsgen-wear-levelling`), configuration sector and state sector.
66
This class generates a binary FATFS partition with initialized wear levelling layer. For further analysis, it also provides an option to remove the wear levelling completely. The class is instantiated and invoked by the ``wl_fatfsgen.py`` script. Class BootSectorState The instance of this class contains the metadata required for building a boot sector and BPB (BIOS Parameter Block). Boot sector is basically implemented for the cross-platform compatibility, i.e., when ESP chipsets are connected with other platforms, it will always follow all the FAT file system standards. However, during partition generation, chip does not consume the data in this boot sector and all the other data needed, as the data is constant. In other words, changing the fields with the prefix "BS" is usually unnecessary and often does not work. If you want to add new features, please focus on fields with the prefix "BPB". Another critical role of this class is to share access to the metadata and binary image over the whole class system.
66
Because of this, every class in the system can access this singleton. Class FATFSState The class **FATFSState** might be obsolete in the future, so developers could transfer its functionality into the **BootSectorState**. The class contains a reference to the **BootSectorState** and extends the data with some unknown information when creating a boot sector or unnecessary for the boot sector, such as the information generated when the file system supports long file names. Class FAT FAT represents the File Allocation Table. FAT is a sequence of bytes spread over one or more sectors. The number of sectors is determined by the number of clusters and is calculated by the function ``get_fat_sectors_count`` in ``utils.py``. The aim is to have as few sectors for one FAT as possible when you refer to every physical cluster in the file system. The FAT works as follows: For every physical cluster at ``i * some_constant`` address, FAT contains an entry at the ``i``-th location which represents next address of the clusters in the file chain.
66
Each version of the FAT file system uses a different size for FAT entries. FAT12 uses 12 bits per entry, thus 2 entries span 3 bytes. FAT16 uses 16 bits per entry, thus 1 entry spans 2 bytes. FAT32 uses 32 bits per FAT entry, thus one entry spans 4 bytes. All entries are in little-endian byte order. All zeros at the ``i``-th entry indicates that corresponding cluster is free, while all ones at the ``i``-th entry indicates that corresponding cluster is occupied and is the last cluster in the file chain. The other number at ``ith``-th entry determines the next cluster's address in the file chain. These clusters are not necessarily stored adjacent to one another in the memory but instead are often fragmented throughout the data region. For partition generation, the file is divided into several parts to fit the cluster. Notice that the structure allocation of the files is a linked list. Every cluster in the file allocation chain has entry in the FAT which refers to the next cluster or the information about the last cluster in the file chain.
66
As mentioned, FAT12 uses 12 bits per FAT entry, thus it can sets a maximum number of 4096 clusters, as with 12 bits (one and a half bytes), it can enumerate 4096 clusters at most. However, because of other overhead, FAT12 can have 4085 clusters at most. Similarly, FAT16 can have 65525 clusters at most and for FAT32 can have 268435445 clusters at most (as practically only 28 bits out of 32 bits are used to denote each FAT entry). The current implementation doesn't allow forcibly redefining the FAT file system with less than 4085 clusters to FAT16, even though the documentation claims it is possible. Notice that it would be meaningless to define it vice versa, i.e., to FAT12 with more than 4085 clusters (which implies clusters on higher addresses being inaccessible). Class Cluster The **Cluster** class is responsible for accessing the FAT entries and the corresponding physical cluster. The class **FAT** is an aggregation of a particular number of **Cluster** instances. Every cluster is uniquely defined by the ID, which also determines its position in FAT and corresponding sectors in the data region.
66
When the cluster is allocated, it includes a reference to a file or directory. It happens only if the cluster is the first in the allocation chain. The cluster contains information about whether it is empty and the last in the file allocation linked list. If not, it includes a reference to the next cluster in the linked list. In practical usage, the cluster doesn't need to access its file, but the other way around. The **File** or **Directory** accesses its cluster, to retrieve the entire content that might be chained. .. figure:: ../../../_static/fat_table.svg :align: center :alt: Table diagram Class Directory This class represents the file system directory. An instance of **Directory** contains the reference to the corresponding instance of **Cluster**, which has the first cluster in the allocation chain for the directory given. The root directory is a special case with a different count of sectors and a slightly different instantiation process. However, the root directory is still an instance of this class and is the only **Directory** instance associated with the class **FATFS** and **WLFATFS** respectively.
66
The class **Directory** (except for the root directory) has one-to-one association with the class **Entry** that defines its entry in the parent directory. It also has an aggregation associated with the class **Entry**, because every directory contains multiple entries that consist of the actual directory's content (for example, aliases, files, and directories). Class File Similar to the class **Directory**, **File** represents single file in the file system. This class has one-to-one association with its first cluster in the allocation chain. Through this cluster, the **File** class may access the corresponding physical address and thus modifying its content. Every file also has one-to-one association with **Entry** instance belonging to its parent directory. Class Entry **Entry** encapsulates information about the file/directory name in the data region of corresponding parent directory. Every file system entity (File/Directory) has an entry. In case of the symlink, the entity can have multiple entries.
66
The directory uses entries to access its descendant files and sub-directories, and enables traversing the tree structure. Except for that, **Entry** holds the name, extension, size, and information regarding the used file name size (long file names or file names 8.3), etc. .. figure:: ../../../_static/tree_fatfs.svg :align: center :alt: Tree diagram ``fatfsgen.py`` :component_file:`fatfsgen.py ` generates FAT file systems on the host. ``fatfsgen.py`` recursively traverses the given folder's directory structure and adds files and/or directories inside the binary partition. Users can set if the script generates the partition with wear levelling support, long file names support, and support for preserving the modification date and time from the original folder on the host. The ``./fatfsgen.py Espressif`` command generates a simple binary partition with the default settings. Here ``Espressif`` is the local folder (containing files and/or sub-directories) from which binary image is generated.
66
There exist two scripts for that purpose, :component_file:`fatfsgen.py ` and :component_file:`wl_fatfsgen.py `. The difference is that ``wl_fatfsgen.py`` firstly uses ``fatfsgen.py`` for generating the partition and then initializes wear leveling. The script command line arguments are as follows:: fatfsgen.py [-h] [--output_file OUTPUT_FILE] [--partition_size PARTITION_SIZE] [--sector_size {4096}] [--long_name_support] [--use_default_datetime] input_directory --output_file: path to the generated binary partition --partition_size: defines the size of the binary partition (decimal, hexa or binary number) --sector_size: the size of the sector --long_name_support: flag for supporting long file names --use_default_datetime: this flag forces using default dates and times (date == 0x2100, time == 0x0000), not using argument to preserve the original file system metadata input_directory: required argument, name of the directory being encoded to the binary fat-compatibile partition ``fatfsparse.
66
py`` :component_file:`fatfsparse.py ` translates the binary image into the internal representation and generates the folder with equivalent content on the host. If user requires a parsing partition with initialized wear levelling, the ``fatfsparse.py`` will remove the wear levelling sectors using the function ``remove_wl`` provided by ``wl_fatfsgen.py``. After the sectors are removed, parsing of the partition is the same as with no initial wear levelling. ``./fatfsparse.py fatfs_image.img`` command yields the directory with the equivalent content as the binary data image ``fatfs_image.img``. The script command line arguments are as follows:: fatfsparse.py [-h] [--wl-layer {detect,enabled,disabled}] input_image --wl-layer: indicates if wear leveling is enabled, disabled or should be detected (detection is ambiguous) input_image: path to binary image The long file names can be detected automatically. However, the wear leveling cannot be 100\% detected, because one partition can be valid either with or without wear leveling, according to the user's context.
66
When the script finds wear leveling sectors (cfg and state), it assumes wear leveling is enabled, however it might be a false positive. Features FAT12/FAT16 The supported FAT types are FAT12 and FAT16. For smaller partitions, FAT12 is sufficient. The type is detected according to the count of clusters, and cannot be changed by the user. If there are less than 4085 clusters, the selected type is FAT12 (FAT's entries have 12 bits). For partitions with 4085 to 65526 clusters (with 4085 and 65526 excluded), the type is FAT16. Currently ``fatfsgen.py`` or ``fatfsparse.py`` cannot process file systems with more than 65525 clusters. .. _fafsgen-wear-levelling: Wear Levelling There are two types of operations related to the wear levelling layer, initializing wear leveling records and removing wear leveling records during generation and parsing of the FAT file system image. When a new image with wear leveling support is generated, the script initializes few extra sectors necessary for the wear leveling function.
66
- The dummy sector: This is an empty sector placed at the beginning of the partition and it will be ignored when file system is being mounted. The dummy sector copies the content of the next sector and then swaps its position with the next sector (or the first sector in case dummy sector was the last) after particular number of erase cycles. In this way, each FAT file system sector traverses across the whole range of flash partition, and thus the erase cycles corresponding to this sector gets distributed across the entire flash. - The state sector: State sector has 64 byte data stored. - pos: position of the dummy sector - max_pos: number of sectors in the partition (excluding config and state sectors) - move_count: indicates how many times dummy sector traversed through the entire flash - access_count: count of sector erase cycles after which dummy sector will swap its position - max_count: equal to wl_config_t::updaterate - block_size: equal to wl_config_t::page_size - version: equal to wl_config_t::version - device_id: generated randomly when the state is first initialized - reserved: 7 x 32-bit words, set to 0 - crc32: crc32 of all the previous fields, including reserved Also, the state sector will be appended by 16-byte ``pos update record`` for every value of ``pos``.
66
Thus, this record will help us to determine the position of the dummy sector. Since ``erase + write`` operation of the state sector is not atomic, we may lose the data if the power is cut off between "erase" and "write". However, two copies of the state are maintained to recover the state after the power outage. On each update, both copies are updated. Thus, after power outage, we can revert the original valid state. - The config sector: This sector contains the information about the partition used by the wear leveling layer. - start_addr: start address of partition (always 0) - full_mem_size: size of the partition, including data, dummy, state x 2, config sectors. Value is in bytes - page_size: equal to sector size (generally 4096) - sector_size: always 4096 for the types of NOR flash supported by ESP-IDF - updaterate: ESP-IDF always sets this to 16. Could be made a config option at some point - wr_size: always set to 16 - version: current version is 2 - temp_buff_size: always set to 32 (This shouldn't actually have been stored in flash) - crc: crc32 of all the previous values While removing wear leveling records, we have to find the position of the dummy sector, and the original and valid orders of the partition (because traversing the dummy sector shuffles the partition).
66
The script can remove other wear leveling sectors from the partition. Steps to remove wear leveling records are given below: - Find the ``pos``, position of the dummy sector, which will be determined by the number of ``pos update records`` in the state sector. - Create the new image by removing dummy sector and merging remaining sectors before and after dummy sector. - Then remove the wear leveling state sectors and config sector which are placed at the end of the partition. - Reorder the new image to get its original order. ``move_count`` helps us to find the beginning of the partition. The partition will start at the position ``end_of_partition - move_count``. Thus the beginning of the partition after removing wear leveling sectors will be ``partition[end_of_partition - (move_count*page_size)]``. File Names Encoding The protocol FAT supports two types of file names. Short File Names (SFN) The SFN is mandatory for the implementation of file names. SFN refer to the 8.
66
3 file name convention, with 8 characters for the file name and 3 characters for the extension. This pattern is case-insensitive, however, all file names are changed to uppercase in the inner representation of the generator. The entry describing the short file names is 32 bytes long and its structure is as follows:: Offset: 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F 0x000000: 46 49 4C 45 4E 41 4D 45 45 58 54 20 18 00 00 00 FILENAMEEXT..... 0x000010: 21 00 21 00 00 00 00 00 21 00 02 00 1E 00 00 00 !.!.....!....... The entry denotes the file with 8.3 file name ("FILENAME.EXT") __(0x00/00-0A)__ of size 0x1E = 30 bytes __(0x10/0x0C)__, with default times of modification and creation (0x0021) __(0x10/00,02 and 08)__. The relevant cluster for the file is located at __0x02 (0x10/0A)__. Please notice that a character is encoded using one byte (e.g., __0x46 == 'F'__) Long File Names (LFN) The LFN supports 255 characters excluding the trailing ``NULL``. The LFN supports any character as short file names with an additional period ``.
66
`` and the following special characters: ``+ , ; = [ ]``. LFN uses UNICODE, so the character is encoded using 2 bytes. The structure of one name encoded using LFN is as follows:: 00003000: 42 65 00 2E 00 74 00 78 00 74 00 0F 00 43 FF FF Be...t.x.t...C.. 00003010: FF FF FF FF FF FF FF FF FF FF 00 00 FF FF FF FF ................ 00003020: 01 74 00 68 00 69 00 73 00 69 00 0F 00 43 73 00 .t.h.i.s.i...Cs. 00003030: 6C 00 6F 00 6E 00 67 00 66 00 00 00 69 00 6C 00 l.o.n.g.f...i.l. 00003040: 54 48 49 53 49 53 7E 31 54 58 54 20 00 00 D6 45 THISIS~1TXT...VE 00003050: 26 55 26 55 00 00 D6 45 26 55 02 00 1C 00 00 00 &U&U..VE&U...... The above example encodes a file name ``thisislongfile.txt``. The record is composed of multiple entries. The first entry contains metadata and is equivalent to the SFN entry. This entry might be final if the file name conforms to the 8.3 file name convention. In such scenarios, the SFN pattern is used. Otherwise, the generator adds various entries with the LFN structure above the SFN entry.
66
These entries hold information about the file name and its checksum for consistency. Every LFN record can hold 13 characters (26 bytes). The file name is firstly cut into some amount of 13-character substrings and these are added above the SFN entry. We add LFN entries in reversed order, so the first entry in the directory is the last part of the file name and the last is SFN entry. In the above example, we can see that the first entry contains text ``e.txt``, while the others contain the beginning of the name ``thisislongfil``. The first byte in LFN entries denotes an order or the sequence number (numbered from 1). To determine the first entry of the LFN, the first byte is masked with 0x40 (``first_byte =| 0x40``). The specification says that the last entry value will be ORed with 0x40 and it is the mark for the last entry. For example, when the record is the second and also the last in the LFN entry, its first byte is ``0x42``. The LFN entry is signed at field **DIR_Attr** with value ``ATTR_READ_ONLY | ATTR_HIDDEN | ATTR_SYSTEM | ATTR_VOLUME_ID`` (see the file ``long_filename_utils.
66
py``). The SFN entry (possibly also within LFN) contains either ``ATTR_DIRECTORY`` or ``ATTR_ARCHIVE`` in this field for directory or file respectively. The LFN entry is tagged at the field **DIR_NTRes** with the value ``0x00``. This is a sign of the SFN entry in the LFN record, if the entry is a whole SFN record, the value is ``0x18``. As you can see in the first example, the value at this field is ``0x18``, because the name **"FILENAME.EXT"** fits the SFN. However, the recent example showing **"thisislongfile.txt"** has value ``0x00`` at field **DIR_NTRes** in the last entry, since it is a LFN. The SFN needs to be unique. For that purpose, the ``fatfsgen.py`` uses the first 6 characters from the file name, concatenating with ``~`` and with ID denoting the order of the name with the same prefix. The ID is between 0 to 127, which is the maximal amount of files with the same prefix. Calculation of the checksum is described and implemented in the ``utils.py`` by function ``lfn_checksum``.
66
The ``fatfsparse.py`` assumes that the LFN entries might not be right next to each other, but it assumes the relative order is preserved. The approach is first to find the SFN belonging to some LFN record (using **DIR_NTRes** field). From then, the script starts to search by moving upwards to the beginning of the respective sector, until it finds the last entry in the LFN record (the one with the first half byte equal to 4). The entries are distinguished by their checksums. When finished, the file name can be composed. Date and Time in FAT File System The FAT file system protocol used by ESP-IDF does not preserve the date or time on the chips' media, so all the images extracted from the device have the same default timestamp for all the FAT-specified date-time fields (creation and the last modification timestamp as well as creation, last modification and last access dates). There are a couple of fields in the SFN entry describing time, such as **DIR_CrtTime** and **DIR_WrtTime**. Some fields are ignored by the FAT implementation used by ESP-IDF (see the file ``entry.
66
py``). However, changes in the fields **DIR_WrtTime** and **DIR_WrtDate** are preserved in the chip. Both time and data entry are 16-bit, where the granularity of the time is 2 seconds.
66
.. include:: /../../components/nvs_flash/nvs_partition_generator/README.rst
67
Partitions API Overview The ``esp_partition`` component has higher-level API functions which work with partitions defined in the :doc:`/api-guides/partition-tables`. These APIs are based on lower level API provided by :doc:`/api-reference/peripherals/spi_flash/index`. .. _flash-partition-apis: Partition Table API ESP-IDF projects use a partition table to maintain information about various regions of SPI flash memory (bootloader, various application binaries, data, filesystems). More information can be found in :doc:`/api-guides/partition-tables`. This component provides API functions to enumerate partitions found in the partition table and perform operations on them. These functions are declared in ``esp_partition.h``: - :cpp:func:`esp_partition_find` checks a partition table for entries with specific type, returns an opaque iterator. - :cpp:func:`esp_partition_get` returns a structure describing the partition for a given iterator. - :cpp:func:`esp_partition_next` shifts the iterator to the next found partition.
68
- :cpp:func:`esp_partition_iterator_release` releases iterator returned by :cpp:func:`esp_partition_find`. - :cpp:func:`esp_partition_find_first` is a convenience function which returns the structure describing the first partition found by :cpp:func:`esp_partition_find`. - :cpp:func:`esp_partition_read`, :cpp:func:`esp_partition_write`, :cpp:func:`esp_partition_erase_range` are equivalent to :cpp:func:`esp_flash_read`, :cpp:func:`esp_flash_write`, :cpp:func:`esp_flash_erase_region`, but operate within partition boundaries. See Also - :doc:`../../api-guides/partition-tables` - :doc:`../system/ota` provides high-level API for updating applications stored in flash. - :doc:`nvs_flash` provides a structured API for storing small pieces of data in SPI flash. .. _api-reference-partition-table: API Reference - Partition Table .. include-build-file:: inc/esp_partition.inc
68
.. include:: /../../tools/mass_mfg/docs/README.rst
69
Non-Volatile Storage Library Introduction Non-volatile storage (NVS) library is designed to store key-value pairs in flash. This section introduces some concepts used by NVS. Underlying Storage Currently, NVS uses a portion of main flash memory through the :ref:`esp_partition ` API. The library uses all the partitions with ``data`` type and ``nvs`` subtype. The application can choose to use the partition with the label ``nvs`` through the :cpp:func:`nvs_open` API function or any other partition by specifying its name using the :cpp:func:`nvs_open_from_partition` API function. Future versions of this library may have other storage backends to keep data in another flash chip (SPI or I2C), RTC, FRAM, etc. .. note:: if an NVS partition is truncated (for example, when the partition table layout is changed), its contents should be erased. ESP-IDF build system provides a ``idf.py erase-flash`` target to erase all contents of the flash chip. .. note:: NVS works best for storing many small values, rather than a few large values of the type 'string' and 'blob'.
70
If you need to store large blobs or strings, consider using the facilities provided by the FAT filesystem on top of the wear levelling library. Keys and Values NVS operates on key-value pairs. Keys are ASCII strings; the maximum key length is currently 15 characters. Values can have one of the following types: - integer types: ``uint8_t``, ``int8_t``, ``uint16_t``, ``int16_t``, ``uint32_t``, ``int32_t``, ``uint64_t``, ``int64_t`` - zero-terminated string - variable length binary data (blob) .. note:: String values are currently limited to 4000 bytes. This includes the null terminator. Blob values are limited to 508,000 bytes or 97.6% of the partition size - 4000 bytes, whichever is lower. Additional types, such as ``float`` and ``double`` might be added later. Keys are required to be unique. Assigning a new value to an existing key replaces the old value and data type with the value and data type specified by a write operation. A data type check is performed when reading a value.
70
An error is returned if the data type expected by read operation does not match the data type of entry found for the key provided. Namespaces To mitigate potential conflicts in key names between different components, NVS assigns each key-value pair to one of namespaces. Namespace names follow the same rules as key names, i.e., the maximum length is 15 characters. Furthermore, there can be no more than 254 different namespaces in one NVS partition. Namespace name is specified in the :cpp:func:`nvs_open` or :cpp:type:`nvs_open_from_partition` call. This call returns an opaque handle, which is used in subsequent calls to the ``nvs_get_*``, ``nvs_set_*``, and :cpp:func:`nvs_commit` functions. This way, a handle is associated with a namespace, and key names will not collide with same names in other namespaces. Please note that the namespaces with the same name in different NVS partitions are considered as separate namespaces. NVS Iterators Iterators allow to list key-value pairs stored in NVS, based on specified partition name, namespace, and data type.
70
There are the following functions available: - :cpp:func:`nvs_entry_find` creates an opaque handle, which is used in subsequent calls to the :cpp:func:`nvs_entry_next` and :cpp:func:`nvs_entry_info` functions. - :cpp:func:`nvs_entry_next` advances an iterator to the next key-value pair. - :cpp:func:`nvs_entry_info` returns information about each key-value pair In general, all iterators obtained via :cpp:func:`nvs_entry_find` have to be released using :cpp:func:`nvs_release_iterator`, which also tolerates ``NULL`` iterators. :cpp:func:`nvs_entry_find` and :cpp:func:`nvs_entry_next` set the given iterator to ``NULL`` or a valid iterator in all cases except a parameter error occured (i.e., return ``ESP_ERR_NVS_NOT_FOUND``). In case of a parameter error, the given iterator will not be modified. Hence, it is best practice to initialize the iterator to ``NULL`` before calling :cpp:func:`nvs_entry_find` to avoid complicated error checking before releasing the iterator. Security, Tampering, and Robustness .
70
. only:: not SOC_HMAC_SUPPORTED NVS is not directly compatible with the {IDF_TARGET_NAME} flash encryption system. However, data can still be stored in encrypted form if NVS encryption is used together with {IDF_TARGET_NAME} flash encryption. Please refer to :doc:`nvs_encryption` for more details. .. only:: SOC_HMAC_SUPPORTED NVS is not directly compatible with the {IDF_TARGET_NAME} flash encryption system. However, data can still be stored in encrypted form if NVS encryption is used together with {IDF_TARGET_NAME} flash encryption or with the help of the HMAC peripheral. Please refer to :doc:`nvs_encryption` for more details. If NVS encryption is not used, it is possible for anyone with physical access to the flash chip to alter, erase, or add key-value pairs. With NVS encryption enabled, it is not possible to alter or add a key-value pair and get recognized as a valid pair without knowing corresponding NVS encryption keys. However, there is no tamper-resistance against the erase operation.
70
The library does try to recover from conditions when flash memory is in an inconsistent state. In particular, one should be able to power off the device at any point and time and then power it back on. This should not result in loss of data, except for the new key-value pair if it was being written at the moment of powering off. The library should also be able to initialize properly with any random data present in flash memory. .. _nvs_encryption: NVS Encryption Please refer to the :doc:`nvs_encryption` guide for more details. NVS Partition Generator Utility This utility helps generate NVS partition binary files which can be flashed separately on a dedicated partition via a flashing utility. Key-value pairs to be flashed onto the partition can be provided via a CSV file. For more details, please refer to :doc:`nvs_partition_gen`. Instead of calling the ``nvs_partition_gen.py`` tool manually, the creation of the partition binary files can also be done directly from CMake using the function ``nvs_create_partition_image``:: nvs_create_partition_image( [FLASH_IN_PROJECT] [DEPENDS dep dep dep .
70
..]) **Positional Arguments**: .. list-table:: :header-rows: 1 - Description - Name of the NVS parition - Path to CSV file to parse **Optional Arguments**: .. list-table:: :header-rows: 1 - Description - Name of the NVS parition - Specify files on which the command depends If ``FLASH_IN_PROJECT`` is not specified, the image will still be generated, but you will have to flash it manually using ``idf.py -flash`` (e.g., if your parition name is ``nvs``, then use ``idf.py nvs-flash``). ``nvs_create_partition_image`` must be called from one of the component ``CMakeLists.txt`` files. Currently, only non-encrypted partitions are supported. Application Example You can find code examples in the :example:`storage` directory of ESP-IDF examples: :example:`storage/nvs_rw_value` Demonstrates how to read a single integer value from, and write it to NVS. The value checked in this example holds the number of the {IDF_TARGET_NAME} module restarts.
70
The value's function as a counter is only possible due to its storing in NVS. The example also shows how to check if a read/write operation was successful, or if a certain value has not been initialized in NVS. The diagnostic procedure is provided in plain text to help you track the program flow and capture any issues on the way. :example:`storage/nvs_rw_blob` Demonstrates how to read a single integer value and a blob (binary large object), and write them to NVS to preserve this value between {IDF_TARGET_NAME} module restarts. The example also shows how to implement the diagnostic procedure to check if the read/write operation was successful. :example:`storage/nvs_rw_value_cxx` This example does exactly the same as :example:`storage/nvs_rw_value`, except that it uses the C++ NVS handle class. Internals Log of Key-Value Pairs NVS stores key-value pairs sequentially, with new key-value pairs being added at the end. When a value of any given key has to be updated, a new key-value pair is added at the end of the log and the old key-value pair is marked as erased.
70
Pages and Entries NVS library uses two main entities in its operation: pages and entries. Page is a logical structure which stores a portion of the overall log. Logical page corresponds to one physical sector of flash memory. Pages which are in use have a *sequence number* associated with them. Sequence numbers impose an ordering on pages. Higher sequence numbers correspond to pages which were created later. Each page can be in one of the following states: Empty/uninitialized Flash storage for the page is empty (all bytes are ``0xff``). Page is not used to store any data at this point and does not have a sequence number. Active Flash storage is initialized, page header has been written to flash, page has a valid sequence number. Page has some empty entries and data can be written there. No more than one page can be in this state at any given moment. Full Flash storage is in a consistent state and is filled with key-value pairs. Writing new key-value pairs into this page is not possible.
70
It is still possible to mark some key-value pairs as erased. Erasing Non-erased key-value pairs are being moved into another page so that the current page can be erased. This is a transient state, i.e., page should never stay in this state at the time when any API call returns. In case of a sudden power off, the move-and-erase process will be completed upon the next power-on. Corrupted Page header contains invalid data, and further parsing of page data was canceled. Any items previously written into this page will not be accessible. The corresponding flash sector will not be erased immediately and will be kept along with sectors in **uninitialized** state for later use. This may be useful for debugging. Mapping from flash sectors to logical pages does not have any particular order. The library will inspect sequence numbers of pages found in each flash sector and organize pages in a list based on these numbers. :: ++ ++ ++ ++ | Page 1 | | Page 2 | | Page 3 | | Page 4 | | Full +---> | Full +---> | Active | | Empty | | Data (8) | | Types ++ +-> Fixed length -- | | +++++ | +> | Size(4) | ChunkCount(1)| ChunkStart(1) | Rsv(2)| Data format ---+ Blob Index +++++ | | ++++ +-> Variable length --> | Size (2) | Rsv (2) | CRC32 (4) | (Strings, Blob Data) ++++ Individual fields in entry structure have the following meanings: NS Namespace index for this entry.
70
For more information on this value, see the section on namespaces implementation. Type One byte indicating the value data type. See the :cpp:type:`ItemType` enumeration in :component_file:`nvs_flash/include/nvs_handle.hpp` for possible values. Span Number of entries used by this key-value pair. For integer types, this is equal to 1. For strings and blobs, this depends on value length. ChunkIndex Used to store the index of a blob-data chunk for blob types. For other types, this should be ``0xff``. CRC32 Checksum calculated over all the bytes in this entry, except for the CRC32 field itself. Key Zero-terminated ASCII string containing a key name. Maximum string length is 15 bytes, excluding a zero terminator. Data For integer types, this field contains the value itself. If the value itself is shorter than 8 bytes, it is padded to the right, with unused bytes filled with ``0xff``. For "blob index" entry, these 8 bytes hold the following information about data-chunks: - Size (Only for blob index.
70
) Size, in bytes, of complete blob data. - ChunkCount (Only for blob index.) Total number of blob-data chunks into which the blob was divided during storage. - ChunkStart (Only for blob index.) ChunkIndex of the first blob-data chunk of this blob. Subsequent chunks have chunkIndex incrementally allocated (step of 1). For string and blob data chunks, these 8 bytes hold additional data about the value, which are described below: - Size (Only for strings and blobs.) Size, in bytes, of actual data. For strings, this includes zero terminators. - CRC32 (Only for strings and blobs.) Checksum calculated over all bytes of data. Variable length values (strings and blobs) are written into subsequent entries, 32 bytes per entry. The ``Span`` field of the first entry indicates how many entries are used. Namespaces As mentioned above, each key-value pair belongs to one of the namespaces. Namespace identifiers (strings) are stored as keys of key-value pairs in namespace with index 0.
70
Values corresponding to these keys are indexes of these namespaces. :: ++ | NS=0 Type=uint8_t Key="wifi" Value=1 | Entry describing namespace "wifi" ++ | NS=1 Type=uint32_t Key="channel" Value=6 | Key "channel" in namespace "wifi" ++ | NS=0 Type=uint8_t Key="pwm" Value=2 | Entry describing namespace "pwm" ++ | NS=2 Type=uint16_t Key="channel" Value=20 | Key "channel" in namespace "pwm" ++ Item Hash List To reduce the number of reads from flash memory, each member of the Page class maintains a list of pairs: item index; item hash. This list makes searches much quicker. Instead of iterating over all entries, reading them from flash one at a time, `Page::findItem` first performs a search for the item hash in the hash list. This gives the item index within the page if such an item exists. Due to a hash collision, it is possible that a different item is found. This is handled by falling back to iteration over items in flash. Each node in the hash list contains a 24-bit hash and 8-bit item index.
70
Hash is calculated based on item namespace, key name, and ChunkIndex. CRC32 is used for calculation; the result is truncated to 24 bits. To reduce the overhead for storing 32-bit entries in a linked list, the list is implemented as a double-linked list of arrays. Each array holds 29 entries, for the total size of 128 bytes, together with linked list pointers and a 32-bit count field. The minimum amount of extra RAM usage per page is therefore 128 bytes; maximum is 640 bytes. API Reference .. include-build-file:: inc/nvs_flash.inc .. include-build-file:: inc/nvs.inc
70
FAT Filesystem Support ESP-IDF uses the `FatFs `_ library to work with FAT filesystems. FatFs resides in the ``fatfs`` component. Although the library can be used directly, many of its features can be accessed via VFS using the C standard library and POSIX API functions. Additionally, FatFs has been modified to support the runtime pluggable disk I/O layer. This allows mapping of FatFs drives to physical disks at runtime. Using FatFs with VFS The header file :component_file:`fatfs/vfs/esp_vfs_fat.h` defines the functions for connecting FatFs and VFS. The function :cpp:func:`esp_vfs_fat_register` allocates a ``FATFS`` structure and registers a given path prefix in VFS. Subsequent operations on files starting with this prefix are forwarded to FatFs APIs. The function :cpp:func:`esp_vfs_fat_unregister_path` deletes the registration with VFS, and frees the ``FATFS`` structure. Most applications use the following workflow when working with ``esp_vfs_fat_`` functions: #. Call :cpp:func:`esp_vfs_fat_register` to specify: - Path prefix where to mount the filesystem (e.
71
g., ``"/sdcard"``, ``"/spiflash"``) - FatFs drive number - A variable which receives the pointer to the ``FATFS`` structure #. Call :cpp:func:`ff_diskio_register` to register the disk I/O driver for the drive number used in Step 1. #. To mount the filesystem using the same drive number which was passed to :cpp:func:`esp_vfs_fat_register`, call the FatFs function :cpp:func:`f_mount`. If the filesystem is not present on the target logical drive, :cpp:func:`f_mount` will fail with the ``FR_NO_FILESYSTEM`` error. In such case, call :cpp:func:`f_mkfs` to create a fresh FatFS structure on the drive first, and then call :cpp:func:`f_mount` again. Note that SD cards need to be partitioned with :cpp:func:`f_fdisk` prior to previously described steps. For more information, see `FatFs documentation `_. #. Call the C standard library and POSIX API functions to perform such actions on files as open, read, write, erase, copy, etc. Use paths starting with the path prefix passed to :cpp:func:`esp_vfs_register` (for example, ``"/sdcard/hello.
71
txt"``). The filesystem uses `8.3 filenames `_ format (SFN) by default. If you need to use long filenames (LFN), enable the :ref:`CONFIG_FATFS_LONG_FILENAMES` option. Please refer to `FatFs filenames `_ for more details. #. Optionally, call the FatFs library functions directly. In this case, use paths without a VFS prefix, for example, ``"/hello.txt"``. #. Close all open files. #. Call the FatFs function :cpp:func:`f_mount` for the same drive number with NULL ``FATFS*`` argument to unmount the filesystem. #. Call the FatFs function :cpp:func:`ff_diskio_register` with NULL ``ff_diskio_impl_t*`` argument and the same drive number to unregister the disk I/O driver. #. Call :cpp:func:`esp_vfs_fat_unregister_path` with the path where the file system is mounted to remove FatFs from VFS, and free the ``FATFS`` structure allocated in Step 1. The convenience functions :cpp:func:`esp_vfs_fat_sdmmc_mount`, :cpp:func:`esp_vfs_fat_sdspi_mount`, and :cpp:func:`esp_vfs_fat_sdcard_unmount` wrap the steps described above and also handle SD card initialization.
71
These functions are described in the next section. .. note:: Because FAT filesystem does not support hardlinks, :cpp:func:`link` copies contents of the file instead. (This only applies to files on FatFs volumes.) Using FatFs with VFS and SD Cards The header file :component_file:`fatfs/vfs/esp_vfs_fat.h` defines convenience functions :cpp:func:`esp_vfs_fat_sdmmc_mount`, :cpp:func:`esp_vfs_fat_sdspi_mount`, and :cpp:func:`esp_vfs_fat_sdcard_unmount`. These functions perform Steps 1–3 and 7–9 respectively and handle SD card initialization, but provide only limited error handling. Developers are encouraged to check its source code and incorporate more advanced features into production applications. The convenience function :cpp:func:`esp_vfs_fat_sdmmc_unmount` unmounts the filesystem and releases the resources acquired by :cpp:func:`esp_vfs_fat_sdmmc_mount`. Using FatFs with VFS in Read-Only Mode The header file :component_file:`fatfs/vfs/esp_vfs_fat.h` also defines the convenience functions :cpp:func:`esp_vfs_fat_spiflash_mount_ro` and :cpp:func:`esp_vfs_fat_spiflash_unmount_ro`.
71
These functions perform Steps 1-3 and 7-9 respectively for read-only FAT partitions. These are particularly helpful for data partitions written only once during factory provisioning, which will not be changed by production application throughout the lifetime of the hardware. Configuration options The following configuration options are available for the FatFs component: FatFS Disk IO Layer FatFs has been extended with API functions that register the disk I/O driver at runtime. These APIs provide implementation of disk I/O functions for SD/MMC cards and can be registered for the given FatFs drive number using the function :cpp:func:`ff_diskio_register_sdmmc`. .. doxygenfunction:: ff_diskio_register .. doxygenstruct:: ff_diskio_impl_t :members: .. doxygenfunction:: ff_diskio_register_sdmmc .. doxygenfunction:: ff_diskio_register_wl_partition .. doxygenfunction:: ff_diskio_register_raw_partition .. _fatfs-partition-generator: FatFs Partition Generator We provide a partition generator for FatFs (:component_file:`wl_fatfsgen.
71
py `) which is integrated into the build system and could be easily used in the user project. The tool is used to create filesystem images on a host and populate it with content of the specified host folder. The script is based on the partition generator (:component_file:`fatfsgen.py `). Apart from generating partition, it can also initialize wear levelling. The latest version supports both short and long file names, FAT12 and FAT16. The long file names are limited to 255 characters and can contain multiple periods (``.``) characters within the filename and additional characters ``+``, ``,``, ``;``, ``=``, ``[`` and ``]``. An in-depth description of the FatFs partition generator and analyzer can be found at :doc:`Generating and parsing FAT partition on host `. Build System Integration with FatFs Partition Generator It is possible to invoke FatFs generator directly from the CMake build system by calling ``fatfs_create_spiflash_image``:: fatfs_create_spiflash_image( [FLASH_IN_PROJECT]) If you prefer generating partition without wear levelling support, you can use ``fatfs_create_rawflash_image``:: fatfs_create_rawflash_image( [FLASH_IN_PROJECT]) ``fatfs_create_spiflash_image`` respectively ``fatfs_create_rawflash_image`` must be called from project's CMakeLists.
71
txt. If you decide for any reason to use ``fatfs_create_rawflash_image`` (without wear levelling support), beware that it supports mounting only in read-only mode in the device. The arguments of the function are as follows: #. partition - the name of the partition as defined in the partition table (e.g., :example_file:`storage/fatfsgen/partitions_example.csv`). #. base_dir - the directory that will be encoded to FatFs partition and optionally flashed into the device. Beware that you have to specify the suitable size of the partition in the partition table. #. flag ``FLASH_IN_PROJECT`` - optionally, users can have the image automatically flashed together with the app binaries, partition tables, etc. on ``idf.py flash -p `` by specifying ``FLASH_IN_PROJECT``. #. flag ``PRESERVE_TIME`` - optionally, users can force preserving the timestamps from the source folder to the target image. Without preserving the time, every timestamp will be set to the FATFS default initial time (1st January 1980).
71
#. flag ``ONE_FAT`` - optionally, users can still choose to generate a FATFS volume with a single FAT (file allocation table) instead of two. This makes the free space in the FATFS volume a bit larger (by ``number of sectors used by FAT * sector size``) but also more prone to corruption. For example:: fatfs_create_spiflash_image(my_fatfs_partition my_folder FLASH_IN_PROJECT) If FLASH_IN_PROJECT is not specified, the image will still be generated, but you will have to flash it manually using ``esptool.py`` or a custom build system target. For an example, see :example:`storage/fatfsgen`. FatFs Partition Analyzer (:component_file:`fatfsparse.py `) is a partition analyzing tool for FatFs. It is a reverse tool of (:component_file:`fatfsgen.py `), i.e., it can generate the folder structure on the host based on the FatFs image. Usage:: ./fatfsparse.py [-h] [--wl-layer {detect,enabled,disabled}] [--verbose] fatfs_image.img Parameter --verbose prints detailed information from boot sector of the FatFs image to the terminal before folder structure is generated.
71
High-level API Reference .. include-build-file:: inc/esp_vfs_fat.inc
71
SPIFFS Filesystem Overview SPIFFS is a file system intended for SPI NOR flash devices on embedded targets. It supports wear levelling, file system consistency checks, and more. Notes - Currently, SPIFFS does not support directories, it produces a flat structure. If SPIFFS is mounted under ``/spiffs``, then creating a file with the path ``/spiffs/tmp/myfile.txt`` will create a file called ``/tmp/myfile.txt`` in SPIFFS, instead of ``myfile.txt`` in the directory ``/spiffs/tmp``. - It is not a real-time stack. One write operation might take much longer than another. - For now, it does not detect or handle bad blocks. - SPIFFS is able to reliably utilize only around 75% of assigned partition space. - When the filesystem is running out of space, the garbage collector is trying to find free space by scanning the filesystem multiple times, which can take up to several seconds per write function call, depending on required space. This is caused by the SPIFFS design and the issue has been reported multiple times (e.
72
g., `here `_) and in the official `SPIFFS github repository `_. The issue can be partially mitigated by the `SPIFFS configuration `_. - When garbage collector is attempting to reclaim space by scanning the entire filesystem multiple times (usually 10 times by default), during each scan, the garbage collector frees up one block if available. Therefore, if the maximum number of runs set for the garbage collector is 'n' (SPIFFS_GC_MAX_RUNS: locate this configuration option in `SPIFFS configuration `_), then n times the block size will become available for data writing. If you attempt to write data exceeding n times the block size, the write operation may fail and return an error. - When the chip experiences a power loss during a file system operation it could result in SPIFFS corruption. However the file system still might be recovered via ``esp_spiffs_check`` function. More details in the official SPIFFS `FAQ `_. Tools ``spiffsgen.py`` :component_file:`spiffsgen.py` is a write-only Python SPIFFS implementation used to create filesystem images from the contents of a host folder.
72
To use ``spiffsgen.py``, open Terminal and run:: python spiffsgen.py The required arguments are as follows: - **image_size**: size of the partition onto which the created SPIFFS image will be flashed. - **base_dir**: directory for which the SPIFFS image needs to be created. - **output_file**: SPIFFS image output file. There are also other arguments that control image generation. Documentation on these arguments can be found in the tool's help:: python spiffsgen.py --help These optional arguments correspond to a possible SPIFFS build configuration. To generate the right image, please make sure that you use the same arguments/configuration as were used to build SPIFFS. As a guide, the help output indicates the SPIFFS build configuration to which the argument corresponds. In cases when these arguments are not specified, the default values shown in the help output will be used. When the image is created, it can be flashed using ``esptool.py`` or ``parttool.py``. Aside from invoking the ``spiffsgen.
72
py`` standalone by manually running it from the command line or a script, it is also possible to invoke ``spiffsgen.py`` directly from the build system by calling ``spiffs_create_partition_image``:: spiffs_create_partition_image( [FLASH_IN_PROJECT] [DEPENDS dep dep dep...]) This is more convenient as the build configuration is automatically passed to the tool, ensuring that the generated image is valid for that build. An example of this is while the **image_size** is required for the standalone invocation, only the **partition** name is required when using ``spiffs_create_partition_image`` -- the image size is automatically obtained from the project's partition table. ``spiffs_create_partition_image`` must be called from one of the component ``CMakeLists.txt`` files. Optionally, users can opt to have the image automatically flashed together with the app binaries, partition tables, etc. on ``idf.py flash`` by specifying ``FLASH_IN_PROJECT``. For example:: spiffs_create_partition_image(my_spiffs_partition my_folder FLASH_IN_PROJECT) If FLASH_IN_PROJECT/SPIFFS_IMAGE_FLASH_IN_PROJECT is not specified, the image will still be generated, but you will have to flash it manually using ``esptool.
72
py``, ``parttool.py``, or a custom build system target. There are cases where the contents of the base directory itself is generated at build time. Users can use DEPENDS/SPIFFS_IMAGE_DEPENDS to specify targets that should be executed before generating the image:: add_custom_target(dep COMMAND ...) spiffs_create_partition_image(my_spiffs_partition my_folder DEPENDS dep) For an example, see :example:`storage/spiffsgen`. ``mkspiffs`` Another tool for creating SPIFFS partition images is `mkspiffs `_. Similar to ``spiffsgen.py``, it can be used to create an image from a given folder and then flash that image using ``esptool.py`` For that, you need to obtain the following parameters: - **Block Size**: 4096 (standard for SPI Flash) - **Page Size**: 256 (standard for SPI Flash) - **Image Size**: Size of the partition in bytes (can be obtained from a partition table) - **Partition Offset**: Starting address of the partition (can be obtained from a partition table) To pack a folder into a 1-Megabyte image, run:: mkspiffs -c [src_folder] -b 4096 -p 256 -s 0x100000 spiffs.
72
bin To flash the image onto {IDF_TARGET_NAME} at offset 0x110000, run:: python esptool.py --chip {IDF_TARGET_PATH_NAME} --port [port] --baud [baud] write_flash -z 0x110000 spiffs.bin Notes on Which SPIFFS Tool to Use ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The two tools presented above offer very similar functionality. However, there are reasons to prefer one over the other, depending on the use case. Use ``spiffsgen.py`` in the following cases: Use ``mkspiffs`` in the following cases: See Also - :doc:`Partition Table documentation ` Application Example An example of using SPIFFS is provided in the :example:`storage/spiffs` directory. This example initializes and mounts a SPIFFS partition, then writes and reads data from it using POSIX and C library APIs. See the README.md file in the example directory for more information. High-level API Reference .. include-build-file:: inc/esp_spiffs.inc
72
NVS Encryption Overview This guide provides an overview of the NVS encryption feature. NVS encryption helps to achieve secure storage on the device flash memory. Data stored in NVS partitions can be encrypted using XTS-AES in the manner similar to the one mentioned in disk encryption standard IEEE P1619. For the purpose of encryption, each entry is treated as one ``sector`` and relative address of the entry (w.r.t., partition-start) is fed to the encryption algorithm as ``sector-number``. .. only:: SOC_HMAC_SUPPORTED NVS encryption can be facilitated by enabling :ref:`CONFIG_NVS_ENCRYPTION` and :ref:`CONFIG_NVS_SEC_KEY_PROTECTION_SCHEME` > ``CONFIG_NVS_SEC_KEY_PROTECT_USING_FLASH_ENC`` or ``CONFIG_NVS_SEC_KEY_PROTECT_USING_HMAC`` depending on the scheme to be used. NVS Encryption: Flash Encryption-Based Scheme In this scheme, the keys required for NVS encryption are stored in yet another partition, which is protected using :doc:`Flash Encryption `. Therefore, enabling :doc:`Flash Encryption ` becomes a prerequisite for NVS encryption here.
73
.. only:: SOC_HMAC_SUPPORTED NVS encryption should be enabled when :doc:`../../security/flash-encryption` is enabled because the Wi-Fi driver stores credentials (like SSID and passphrase) in the default NVS partition. It is important to encrypt them if platform-level encryption is already enabled. .. only:: not SOC_HMAC_SUPPORTED NVS encryption is enabled by default when :doc:`../../security/flash-encryption` is enabled. This is done because Wi-Fi driver stores credentials (like SSID and passphrase) in the default NVS partition. It is important to encrypt them as default choice if platform-level encryption is already enabled. For using NVS encryption using this scheme, the partition table must contain the :ref:`nvs_encr_key_partition`. Two partition tables containing the :ref:`nvs_encr_key_partition` are provided for NVS encryption under the partition table option (``menuconfig`` > ``Partition Table``). They can be selected with the project configuration menu (``idf.py menuconfig``).
73
Please refer to the example :example:`security/flash_encryption` for how to configure and use the NVS encryption feature. .. _nvs_encr_key_partition: NVS Key Partition An application requiring NVS encryption support (using the Flash Encryption-based scheme) needs to be compiled with a key-partition of the type ``data`` and subtype ``key``. This partition should be marked as ``encrypted`` and its size should be the minimum partition size (4 KB). Refer to :doc:`../../api-guides/partition-tables` for more details. Two additional partition tables which contain the :ref:`nvs_encr_key_partition` are provided under the partition table option (``menuconfig`` > ``Partition Table``). They can be directly used for NVS encryption. The structure of these partitions is depicted below: .. highlight:: none :: +++++ | XTS encryption key (32) | ++ | XTS tweak key (32) | ++ | CRC32 (4) | ++ The XTS encryption keys in the :ref:`nvs_encr_key_partition` can be generated in one of the following two ways.
73
**Generate the keys on {IDF_TARGET_NAME} chip itself** .. note:: Please note that ``nvs_keys`` partition must be completely erased before you start the application in this approach. Otherwise the application may generate the :c:macro:`ESP_ERR_NVS_CORRUPT_KEY_PART` error code assuming that ``nvs_keys`` partition is not empty and contains malformatted data. You can use the following command for this: :: parttool.py --port PORT --partition-table-file=PARTITION_TABLE_FILE --partition-table-offset PARTITION_TABLE_OFFSET erase_partition --partition-type=data --partition-subtype=nvs_keys **Use a pre-generated NVS key partition** This option will be required by the user when keys in the :ref:`nvs_encr_key_partition` are not generated by the application. The :ref:`nvs_encr_key_partition` containing the XTS encryption keys can be generated with the help of :doc:`NVS Partition Generator Utility `. Then the user can store the pre-generated key partition on the flash with help of the following two commands: :: idf.
73
py partition-table partition-table-flash :: parttool.py --port PORT --partition-table-offset PARTITION_TABLE_OFFSET write_partition --partition-name="name of nvs_key partition" --input NVS_KEY_PARTITION_FILE .. note:: If the device is encrypted in flash encryption development mode and you want to renew the NVS key partition, you need to tell :component_file:`parttool.py` to encrypt the NVS key partition and you also need to give it a pointer to the unencrypted partition table in your build directory (build/partition_table) since the partition table on the device is encrypted, too. You can use the following command: :: parttool.py --esptool-write-args encrypt --port PORT --partition-table-file=PARTITION_TABLE_FILE --partition-table-offset PARTITION_TABLE_OFFSET write_partition --partition-name="name of nvs_key partition" --input NVS_KEY_PARTITION_FILE Since the key partition is marked as ``encrypted`` and :doc:`Flash Encryption ` is enabled, the bootloader will encrypt this partition using flash encryption key on the first boot.
73
It is possible for an application to use different keys for different NVS partitions and thereby have multiple key-partitions. However, it is a responsibility of the application to provide the correct key-partition and keys for encryption or decryption. .. only:: SOC_HMAC_SUPPORTED NVS Encryption: HMAC Peripheral-Based Scheme In this scheme, the XTS keys required for NVS encryption are derived from an HMAC key programmed in eFuse with the purpose :cpp:enumerator:`esp_efuse_purpose_t::ESP_EFUSE_KEY_PURPOSE_HMAC_UP`. Since the encryption keys are derived at runtime, they are not stored anywhere in the flash. Thus, this feature does not require a separate :ref:`nvs_encr_key_partition`. .. note:: This scheme enables us to achieve secure storage on {IDF_TARGET_NAME} **without enabling flash encryption**. .. important:: Please take note that this scheme uses one eFuse block for storing the HMAC key required for deriving the encryption keys. - When NVS encryption is enabled, the :cpp:func:`nvs_flash_init` API function can be used to initialize the encrypted default NVS partition.
73
The API function first checks whether an HMAC key is present at :ref:`CONFIG_NVS_SEC_HMAC_EFUSE_KEY_ID`. .. note:: The valid range for the config :ref:`CONFIG_NVS_SEC_HMAC_EFUSE_KEY_ID` is from ``0`` (:cpp:enumerator:`hmac_key_id_t::HMAC_KEY0`) to ``5`` (:cpp:enumerator:`hmac_key_id_t::HMAC_KEY5`). By default, the config is set to ``6`` (:cpp:enumerator:`hmac_key_id_t::HMAC_KEY_MAX`), which have to be configured before building the user application. - If no key is found, a key is generated internally and stored at the eFuse block specified at :ref:`CONFIG_NVS_SEC_HMAC_EFUSE_KEY_ID`. - If a key is found with the purpose :cpp:enumerator:`esp_efuse_purpose_t::ESP_EFUSE_KEY_PURPOSE_HMAC_UP`, the same is used for the derivation of the XTS encryption keys. - If the specified eFuse block is found to be occupied with a key with a purpose other than :cpp:enumerator:`esp_efuse_purpose_t::ESP_EFUSE_KEY_PURPOSE_HMAC_UP`, an error is thrown. - The API :cpp:func:`nvs_flash_init` then automatically generates the NVS keys on demand by using the :cpp:func:`nvs_flash_generate_keys_v2` API function provided by the :component_file:`nvs_flash/include/nvs_flash.
73
h`. The same keys can also be used to read the security configurations (see :cpp:func:`nvs_flash_read_security_cfg_v2`) for initializing a custom encrypted NVS partition with help of :cpp:func:`nvs_flash_secure_init_partition`. - The API functions :cpp:func:`nvs_flash_secure_init` and :cpp:func:`nvs_flash_secure_init_partition` do not generate the keys internally. When these API functions are used for initializing encrypted NVS partitions, the keys can be generated after startup using the :cpp:func:`nvs_flash_generate_keys_v2` API function or take and populate the NVS security configuration structure :cpp:type:`nvs_sec_cfg_t` with :cpp:func:`nvs_flash_read_security_cfg_v2` and feed them into the above APIs. .. note:: Users can program their own HMAC key in eFuse block beforehand by using the following command: :: espefuse.py -p PORT burn_key HMAC_UP Encrypted Read/Write The same NVS API functions ``nvs_get_*`` or ``nvs_set_*`` can be used for reading of, and writing to an encrypted NVS partition as well.
73
**Encrypt the default NVS partition** - To enable encryption for the default NVS partition, no additional step is necessary. When :ref:`CONFIG_NVS_ENCRYPTION` is enabled, the :cpp:func:`nvs_flash_init` API function internally performs some additional steps to enable encryption for the default NVS partition depending on the scheme being used (set by :ref:`CONFIG_NVS_SEC_KEY_PROTECTION_SCHEME`). - For the flash encryption-based scheme, the first :ref:`nvs_encr_key_partition` found is used to generate the encryption keys while for the HMAC one, keys are generated using the HMAC key burnt in eFuse at :ref:`CONFIG_NVS_SEC_HMAC_EFUSE_KEY_ID` (refer to the API documentation for more details). Alternatively, :cpp:func:`nvs_flash_secure_init` API function can also be used to enable encryption for the default NVS partition. **Encrypt a custom NVS partition** - To enable encryption for a custom NVS partition, :cpp:func:`nvs_flash_secure_init_partition` API function is used instead of :cpp:func:`nvs_flash_init_partition`.
73
- When :cpp:func:`nvs_flash_secure_init` and :cpp:func:`nvs_flash_secure_init_partition` API functions are used, the applications are expected to follow the steps below in order to perform NVS read/write operations with encryption enabled: - Find key partition and NVS data partition using ``esp_partition_find*`` API functions. - Populate the :cpp:type:`nvs_sec_cfg_t` struct using the :cpp:func:`nvs_flash_read_security_cfg` or :cpp:func:`nvs_flash_generate_keys` API functions. .. only:: SOC_HMAC_SUPPORTED - Set the scheme-specific config data with :cpp:type:`nvs_sec_config_hmac_t` and register the HMAC-based scheme with the API :cpp:func:`nvs_sec_provider_register_hmac` which will also populate the scheme-specific handle (see :cpp:type:`nvs_sec_scheme_t`). - Populate the :cpp:type:`nvs_sec_cfg_t` struct using the :cpp:func:`nvs_flash_read_security_cfg_v2` or :cpp:func:`nvs_flash_generate_keys_v2` API functions. .
73
. code-block:: c nvs_sec_cfg_t cfg = {}; nvs_sec_scheme_t *sec_scheme_handle = NULL; nvs_sec_config_hmac_t sec_scheme_cfg = {}; hmac_key_id_t hmac_key = HMAC_KEY0; sec_scheme_cfg.hmac_key_id = hmac_key; ret = nvs_sec_provider_register_hmac(&sec_scheme_cfg, &sec_scheme_handle); if (ret != ESP_OK) { return ret; } ret = nvs_flash_read_security_cfg_v2(sec_scheme_handle, &cfg); if (ret != ESP_OK) { if (ret == ESP_ERR_NVS_SEC_HMAC_KEY_NOT_FOUND) { ret = nvs_flash_generate_keys_v2(&sec_scheme_handle, &cfg); if (ret != ESP_OK) { ESP_LOGE(TAG, "Failed to generate NVS encr-keys!"); return ret; } } ESP_LOGE(TAG, "Failed to read NVS security cfg!
73
"); return ret; } .. only:: SOC_HMAC_SUPPORTED .. note:: While using the HMAC-based scheme, the above workflow can be used without enabling any of the config options for NVS encryption - :ref:`CONFIG_NVS_ENCRYPTION`, :ref:`CONFIG_NVS_SEC_KEY_PROTECTION_SCHEME` -> ``CONFIG_NVS_SEC_KEY_PROTECT_USING_HMAC`` and :ref:`CONFIG_NVS_SEC_HMAC_EFUSE_KEY_ID` to encrypt the default as well as custom NVS partitions with :cpp:func:`nvs_flash_secure_init` API. NVS Security Provider The component :component:`nvs_sec_provider` stores all the implementation-specific code for the NVS encryption schemes and would also accomodate any future schemes. This component acts as an interface to the :component:`nvs_flash` component for the handling of encryption keys. :component:`nvs_sec_provider` has a configuration menu of its own, based on which the selected security scheme and the corresponding settings are registered for the :component:`nvs_flash` component.
73
.. only:: SOC_HMAC_SUPPORTED This component offers factory functions with which a particular security scheme can be registered without having to worry about the APIs to generate and read the encryption keys (e.g., :cpp:func:`nvs_sec_provider_register_hmac`). Refer to the :example:`security/nvs_encryption_hmac` example for API usage. API Reference .. include-build-file:: inc/nvs_sec_provider.inc
73
.. include:: ../../../../components/wear_levelling/README.rst See Also - :doc:`./fatfs` - :doc:`../../api-guides/partition-tables` Application Example An example that combines the wear levelling driver with the FATFS library is provided in the :example:`storage/wear_levelling` directory. This example initializes the wear levelling driver, mounts FatFs partition, as well as writes and reads data from it using POSIX and C library APIs. See :example_file:`storage/wear_levelling/README.md` for more information. High-level API Reference Header Files High-level wear levelling functions :cpp:func:`esp_vfs_fat_spiflash_mount_rw_wl`, :cpp:func:`esp_vfs_fat_spiflash_unmount_rw_wl` and struct :cpp:class:`esp_vfs_fat_mount_config_t` are described in :doc:`./fatfs`. Mid-level API Reference .. include-build-file:: inc/wear_levelling.inc
74
FreeRTOS Overview Overview FreeRTOS is an open source RTOS (real-time operating system) kernel that is integrated into ESP-IDF as a component. Thus, all ESP-IDF applications and many ESP-IDF components are written based on FreeRTOS. The FreeRTOS kernel is ported to all architectures (i.e., Xtensa and RISC-V) available of ESP chips. Furthermore, ESP-IDF provides different implementations of FreeRTOS in order to support SMP (Symmetric Multiprocessing) on multi-core ESP chips. This document provides an overview of the FreeRTOS component, the different FreeRTOS implementations offered by ESP-IDF, and the common aspects across all implementations. Implementations The `official FreeRTOS `_ (henceforth referred to as Vanilla FreeRTOS) is a single-core RTOS. In order to support the various multi-core ESP targets, ESP-IDF supports different FreeRTOS implementations as listed below: ESP-IDF FreeRTOS ESP-IDF FreeRTOS is a FreeRTOS implementation based on Vanilla FreeRTOS v10.5.1, but contains significant modifications to support SMP.
75
ESP-IDF FreeRTOS only supports two cores at most (i.e., dual core SMP), but is more optimized for this scenario by design. For more details regarding ESP-IDF FreeRTOS and its modifications, please refer to the :doc:`freertos_idf` document. .. note:: ESP-IDF FreeRTOS is currently the default FreeRTOS implementation for ESP-IDF. .. only:: not esp32p4 .. _amazon_smp_freertos: Amazon SMP FreeRTOS Amazon SMP FreeRTOS is an SMP implementation of FreeRTOS that is officially supported by Amazon. Amazon SMP FreeRTOS is able to support N-cores (i.e., more than two cores). Amazon SMP FreeRTOS can be enabled via the :ref:`CONFIG_FREERTOS_SMP` option. For more details regarding Amazon SMP FreeRTOS, please refer to the `official Amazon SMP FreeRTOS documentation `_. .. warning:: The Amazon SMP FreeRTOS implementation (and its port in ESP-IDF) are currently in experimental/beta state. Therefore, significant behavioral changes and breaking API changes can occur.
75
Configuration Kernel Configuration Vanilla FreeRTOS requires that ports and applications configure the kernel by adding various ``#define config...`` macro definitions to the ``FreeRTOSConfig.h`` header file. Vanilla FreeRTOS supports a list of kernel configuration options which allow various kernel behaviors and features to be enabled or disabled. **However, for all FreeRTOS ports in ESP-IDF, the FreeRTOSConfig.h header file is considered private and must not be modified by users**. A large number of kernel configuration options in ``FreeRTOSConfig.h`` are hard-coded as they are either required/not supported by ESP-IDF. All kernel configuration options that are configurable by the user are exposed via menuconfig under ``Component Config/FreeRTOS/Kernel``. For the full list of user configurable kernel options, see :doc:`/api-reference/kconfig`. The list below highlights some commonly used kernel configuration options: - :ref:`CONFIG_FREERTOS_UNICORE` runs FreeRTOS only on Core 0.
75
Note that this is **not equivalent to running Vanilla FreeRTOS**. Furthermore, this option may affect behavior of components other than :component:`freertos`. For more details regarding the effects of running FreeRTOS on a single core, refer to :ref:`freertos-idf-single-core` (if using ESP-IDF FreeRTOS) or the official Amazon SMP FreeRTOS documentation. Alternatively, users can also search for occurrences of ``CONFIG_FREERTOS_UNICORE`` in the ESP-IDF components. .. only:: not SOC_HP_CPU_HAS_MULTIPLE_CORES .. note:: As {IDF_TARGET_NAME} is a single core SoC, the :ref:`CONFIG_FREERTOS_UNICORE` configuration is always set. - :ref:`CONFIG_FREERTOS_ENABLE_BACKWARD_COMPATIBILITY` enables backward compatibility with some FreeRTOS macros/types/functions that were deprecated from v8.0 onwards. Port Configuration All other FreeRTOS related configuration options that are not part of the kernel configuration are exposed via menuconfig under ``Component Config/FreeRTOS/Port``. These options configure aspects such as: - The FreeRTOS ports themselves (e.
75
g., tick timer selection, ISR stack size) - Additional features added to the FreeRTOS implementation or ports Using FreeRTOS Application Entry Point Unlike Vanilla FreeRTOS, users of FreeRTOS in ESP-IDF **must never call** :cpp:func:`vTaskStartScheduler` and :cpp:func:`vTaskEndScheduler`. Instead, ESP-IDF starts FreeRTOS automatically. Users must define a ``void app_main(void)`` function which acts as the entry point for user's application and is automatically invoked on ESP-IDF startup. - Typically, users would spawn the rest of their application's task from ``app_main``. - The ``app_main`` function is allowed to return at any point (i.e., before the application terminates). - The ``app_main`` function is called from the ``main`` task. .. _freertos_system_tasks: Background Tasks During startup, ESP-IDF and the FreeRTOS kernel automatically create multiple tasks that run in the background (listed in the the table below). .. list-table:: List of Tasks Created During Startup :widths: 10 75 5 5 5 :header-rows: 1 - Description - Stack Size - Affinity - Priority - An idle task (``IDLEx``) is created for (and pinned to) each core, where ``x`` is the core's number.
75
``x`` is dropped when single-core configuration is enabled. - :ref:`CONFIG_FREERTOS_IDLE_TASK_STACKSIZE` - Core x - ``0`` - FreeRTOS will create the Timer Service/Daemon Task if any FreeRTOS Timer APIs are called by the application - :ref:`CONFIG_FREERTOS_TIMER_TASK_STACK_DEPTH` - Core 0 - :ref:`CONFIG_FREERTOS_TIMER_TASK_PRIORITY` - Task that simply calls ``app_main``. This task will self delete when ``app_main`` returns - :ref:`CONFIG_ESP_MAIN_TASK_STACK_SIZE` - :ref:`CONFIG_ESP_MAIN_TASK_AFFINITY` - ``1`` - When :ref:`CONFIG_FREERTOS_UNICORE` is false, an IPC task (``ipcx``) is created for (and pinned to) each core. IPC tasks are used to implement the Inter-processor Call (IPC) feature. - :ref:`CONFIG_ESP_IPC_TASK_STACK_SIZE` - Core x - ``24`` - ESP-IDF creates the ESP Timer Task used to process ESP Timer callbacks - :ref:`CONFIG_ESP_TIMER_TASK_STACK_SIZE` - Core 0 - ``22`` .
75
. note:: Note that if an application uses other ESP-IDF features (e.g., Wi-Fi or Bluetooth), those features may create their own background tasks in addition to the tasks listed in the table above. FreeRTOS Additions ESP-IDF provides some supplemental features to FreeRTOS such as Ring Buffers, ESP-IDF style Tick and Idle Hooks, and TLSP deletion callbacks. See :doc:`freertos_additions` for more details. .. _freertos-heap: FreeRTOS Heap Vanilla FreeRTOS provides its own `selection of heap implementations `_. However, ESP-IDF already implements its own heap (see :doc:`/api-reference/system/mem_alloc`), thus ESP-IDF does not make use of the heap implementations provided by Vanilla FreeRTOS. All FreeRTOS ports in ESP-IDF map FreeRTOS memory allocation or free calls (e.g., ``pvPortMalloc()`` and ``pvPortFree()``) to ESP-IDF heap API (i.e., :cpp:func:`heap_caps_malloc` and :cpp:func:`heap_caps_free`). However, the FreeRTOS ports ensure that all dynamic memory allocated by FreeRTOS is placed in internal memory.
75
.. note:: If users wish to place FreeRTOS tasks/objects in external memory, users can use the following methods: - Allocate the task or object using one of the ``...CreateWithCaps()`` API, such as :cpp:func:`xTaskCreateWithCaps` and :cpp:func:`xQueueCreateWithCaps` (see :ref:`freertos-idf-additional-api` for more details). - Manually allocate external memory for those objects using :cpp:func:`heap_caps_malloc`, then create the objects from the allocated memory using on of the ``...CreateStatic()`` FreeRTOS functions.
75
Miscellaneous System APIs {IDF_TARGET_BASE_MAC_BLOCK: default="BLK1", esp32="BLK0"} {IDF_TARGET_CPU_RESET_DES: default="the CPU is reset", esp32="both CPUs are reset", esp32s3="both CPUs are reset", esp32p4="both CPUs are reset"} Software Reset To perform software reset of the chip, the :cpp:func:`esp_restart` function is provided. When the function is called, execution of the program stops, {IDF_TARGET_CPU_RESET_DES}, the application is loaded by the bootloader and starts execution again. Additionally, the :cpp:func:`esp_register_shutdown_handler` function can register a routine that will be automatically called before a restart (that is triggered by :cpp:func:`esp_restart`) occurs. This is similar to the functionality of ``atexit`` POSIX function. Reset Reason ESP-IDF applications can be started or restarted due to a variety of reasons. To get the last reset reason, call :cpp:func:`esp_reset_reason` function. See description of :cpp:type:`esp_reset_reason_t` for the list of possible reset reasons.
76
Heap Memory Two heap-memory-related functions are provided: Note that ESP-IDF supports multiple heaps with different capabilities. The functions mentioned in this section return the size of heap memory that can be allocated using the ``malloc`` family of functions. For further information about heap memory, see :doc:`Heap Memory Allocation `. .. _MAC-Address-Allocation: MAC Address These APIs allow querying and customizing MAC addresses for different supported network interfaces (e.g., Wi-Fi, Bluetooth, Ethernet). To fetch the MAC address for a specific network interface (e.g., Wi-Fi, Bluetooth, Ethernet), call the function :cpp:func:`esp_read_mac`. In ESP-IDF, the MAC addresses for the various network interfaces are calculated from a single **base MAC address**. By default, the Espressif base MAC address is used. This base MAC address is pre-programmed into the {IDF_TARGET_NAME} eFuse in the factory during production. .. only:: not esp32s2 .. list-table:: :widths: 20 40 40 :header-rows: 1 - MAC Address (4 universally administered, default) - MAC Address (2 universally administered) - base_mac - base_mac - base_mac, +1 to the last octet - :ref:`Local MAC ` (derived from Wi-Fi Station MAC) - base_mac, +2 to the last octet - base_mac, +1 to the last octet - base_mac, +3 to the last octet - :ref:`Local MAC ` (derived from Bluetooth MAC) .
76
. note:: The :ref:`configuration ` configures the number of universally administered MAC addresses that are provided by Espressif. .. only:: esp32s2 .. list-table:: :widths: 20 40 40 :header-rows: 1 - MAC Address (2 universally administered, default) - MAC Address (1 universally administered) - base_mac - base_mac - base_mac, +1 to the last octet - :ref:`Local MAC ` (derived from Wi-Fi Station MAC) - :ref:`Local MAC ` (derived from Wi-Fi SoftAP MAC) - :ref:`Local MAC ` (derived from base_mac with +1 to last octet. Not recommended.) .. note:: The :ref:`configuration ` configures the number of universally administered MAC addresses that are provided by Espressif. .. only:: not SOC_EMAC_SUPPORTED .. note:: Although {IDF_TARGET_NAME} has no integrated Ethernet MAC, it is still possible to calculate an Ethernet MAC address. However, this MAC address can only be used with an external ethernet interface such as an SPI-Ethernet device.
76
See :doc:`/api-reference/network/esp_eth`. Custom Interface MAC Sometimes you may need to define custom MAC addresses that are not generated from the base MAC address. To set a custom interface MAC address, use the :cpp:func:`esp_iface_mac_addr_set` function. This function allows you to overwrite the MAC addresses of interfaces set (or not yet set) by the base MAC address. Once a MAC address has been set for a particular interface, it will not be affected when the base MAC address is changed. Custom Base MAC The default base MAC is pre-programmed by Espressif in eFuse {IDF_TARGET_BASE_MAC_BLOCK}. To set a custom base MAC instead, call the function :cpp:func:`esp_iface_mac_addr_set` with the ``ESP_MAC_BASE`` argument (or :cpp:func:`esp_base_mac_addr_set`) before initializing any network interfaces or calling the :cpp:func:`esp_read_mac` function. The custom MAC address can be stored in any supported storage device (e.g., flash, NVS). The custom base MAC addresses should be allocated such that derived MAC addresses will not overlap.
76
Based on the table above, users can configure the option :ref:`CONFIG_{IDF_TARGET_CFG_PREFIX}_UNIVERSAL_MAC_ADDRESSES` to set the number of valid universal MAC addresses that can be derived from the custom base MAC. .. note:: It is also possible to call the function :cpp:func:`esp_netif_set_mac` to set the specific MAC used by a network interface after network initialization. But it is recommended to use the base MAC approach documented here to avoid the possibility of the original MAC address briefly appearing on the network before being changed. Custom MAC Address in eFuse @@@@@@@@@@@@@@@@@@@@@@@@@@@ When reading custom MAC addresses from eFuse, ESP-IDF provides a helper function :cpp:func:`esp_efuse_mac_get_custom`. Users can also use :cpp:func:`esp_read_mac` with the ``ESP_MAC_EFUSE_CUSTOM`` argument. This loads the MAC address from eFuse BLK3. The :cpp:func:`esp_efuse_mac_get_custom` function assumes that the custom base MAC address is stored in the following format: ..
76
only:: esp32 .. list-table:: :widths: 20 15 20 45 :header-rows: 1 - # of bits - Range of bits - Notes - 8 - 191:184 - 0: invalid, others — valid - 128 - 183:56 - - 48 - 55:8 - - 8 - 7:0 - CRC-8-CCITT, polynomial 0x07 .. note:: If the 3/4 coding scheme is enabled, all eFuse fields in this block must be burnt at the same time. .. only:: not esp32 .. list-table:: :widths: 30 30 30 :header-rows: 1 - # of bits - Range of bits - 48 - 200:248 .. note:: The eFuse BLK3 uses RS-coding during burning, which means that all eFuse fields in this block must be burnt at the same time. Once custom eFuse MAC address has been obtained (using :cpp:func:`esp_efuse_mac_get_custom` or :cpp:func:`esp_read_mac`), you need to set it as the base MAC address.
76
There are two ways to do it: .. _local-mac-addresses: Local Versus Universal MAC Addresses {IDF_TARGET_NAME} comes pre-programmed with enough valid Espressif universally administered MAC addresses for all internal interfaces. The table above shows how to calculate and derive the MAC address for a specific interface according to the base MAC address. When using a custom MAC address scheme, it is possible that not all interfaces can be assigned with a universally administered MAC address. In these cases, a locally administered MAC address is assigned. Note that these addresses are intended for use on a single local network only. See `this article `_ for the definition of locally and universally administered MAC addresses. Function :cpp:func:`esp_derive_local_mac` is called internally to derive a local MAC address from a universal MAC address. The process is as follows: Chip Version :cpp:func:`esp_chip_info` function fills :cpp:class:`esp_chip_info_t` structure with information about the chip.
76
This includes the chip revision, number of CPU cores, and a bit mask of features enabled in the chip. .. _idf-version-h: SDK Version :cpp:func:`esp_get_idf_version` returns a string describing the ESP-IDF version which is used to compile the application. This is the same value as the one available through ``IDF_VER`` variable of the build system. The version string generally has the format of ``git describe`` output. To get the version at build time, additional version macros are provided. They can be used to enable or disable parts of the program depending on the ESP-IDF version. .. code-block:: c #include "esp_idf_version.h" #if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(4, 0, 0) // enable functionality present in ESP-IDF v4.0 #endif .. _app-version: App Version The application version is stored in :cpp:class:`esp_app_desc_t` structure. It is located in DROM sector and has a fixed offset from the beginning of the binary file. The structure is located after :cpp:class:`esp_image_header_t` and :cpp:class:`esp_image_segment_header_t` structures.
76
The type of the field version is string and it has a maximum length of 32 chars. To set the version in your project manually, you need to set the ``PROJECT_VER`` variable in the ``CMakeLists.txt`` of your project. In application ``CMakeLists.txt``, put ``set(PROJECT_VER "0.1.0.1")`` before including ``project.cmake``. If the :ref:`CONFIG_APP_PROJECT_VER_FROM_CONFIG` option is set, the value of :ref:`CONFIG_APP_PROJECT_VER` will be used. Otherwise, if the ``PROJECT_VER`` variable is not set in the project, it will be retrieved either from the ``$(PROJECT_PATH)/version.txt`` file (if present) or using git command ``git describe``. If neither is available, ``PROJECT_VER`` will be set to "1". Application can make use of this by calling :cpp:func:`esp_app_get_description` or :cpp:func:`esp_ota_get_partition_description` functions. API Reference .. include-build-file:: inc/esp_system.inc .. include-build-file:: inc/esp_idf_version.inc .. include-build-file:: inc/esp_mac.inc .. include-build-file:: inc/esp_chip_info.
76
inc .. include-build-file:: inc/esp_cpu.inc .. include-build-file:: inc/esp_app_desc.inc
76
ULP Coprocessor Programming The Ultra Low Power (ULP) coprocessor is a simple finite state machine (FSM) which is designed to perform measurements using the ADC, temperature sensor, and external I2C sensors, while the main processors are in Deep-sleep mode. The ULP coprocessor can access the ``RTC_SLOW_MEM`` memory region, and registers in the ``RTC_CNTL``, ``RTC_IO``, and ``SARADC`` peripherals. The ULP coprocessor uses fixed-width 32-bit instructions, 32-bit memory addressing, and has 4 general-purpose 16-bit registers. This coprocessor is referred to as ``ULP FSM`` in ESP-IDF. .. only:: esp32s2 or esp32s3 {IDF_TARGET_NAME} provides a second type of ULP coprocessor which is based on a RISC-V instruction set architecture. For details regarding `ULP RISC-V` refer :doc:`ULP-RISC-V Coprocessor `. Installing the Toolchain The ULP FSM coprocessor code is written in assembly and compiled using the `binutils-esp32ulp toolchain`_. If you have already set up ESP-IDF with CMake build system according to the :doc:`Getting Started Guide `, then the ULP FSM toolchain will already be installed.
77