data
stringlengths
512
2.99k
leak_some_memory at /path/to/idf/examples/get-started/blink/main/./blink.c:29 0x400d27c1: blink_task at /path/to/idf/examples/get-started/blink/main/./blink.c:52 40 bytes 'leaked' in trace (2 allocations) total allocations 2 total frees 0 Note The above example output uses IDF Monitor to automatically decode PC addresses to their source files and line numbers. The first line indicates how many allocation entries are in the buffer, compared to its total size. In HEAP_TRACE_LEAKS mode, for each traced memory allocation that has not already been freed, a line is printed with: XX bytesis the number of bytes allocated. @ 0x...is the heap address returned from heap_caps_malloc()or heap_caps_calloc(). Internalor PSRAMis the general location of the allocated memory. CPU xis the CPU (0 or 1) running when the allocation was made. ccount 0x...is the CCOUNT (CPU cycle count) register value the allocation was made. The value is different for CPU 0 vs CPU 1. caller 0x...gives the call stack of the call to heap_caps_malloc()or heap_caps_free(), as a list of PC addresses. These can be decoded to source files and line numbers, as shown above. The depth of the call stack recorded for each trace entry can be configured in the project configuration menu, under Heap Memory Debugging > Enable heap tracing > CONFIG_HEAP_TRACING_STACK_DEPTH. Up to 32 stack frames can be recorded for each allocation (the default is 2). Each additional stack frame increases the memory usage of each heap_trace_record_t record by eight bytes. Finally, the total number of the 'leaked' bytes (bytes allocated but not freed while the trace is running) is printed together with the total number of allocations it represents. A warning will be printed if the trace buffer was not large enough to hold all the allocations happened. If you see this warning, consider either shortening the tracing period or increasing the number of records in the trace buffer. Host-Based Mode Once you have identified the code which you think is leaking: In the project configuration menu, navigate to Component settings> Heap Memory Debugging> CONFIG_HEAP_TRACING_DEST and select Host-Based. In the project configuration menu, navigate to Component settings> Application Level Tracing> CONFIG_APPTRACE_DESTINATION1 and select Trace memory. In the project configuration menu, navigate to Component settings> Application Level Tracing> FreeRTOS SystemView
Tracingand enable CONFIG_APPTRACE_SV_ENABLE. Call the function heap_trace_init_tohost()early in the program, to initialize the JTAG heap tracing module. Call the function heap_trace_start()to begin recording all memory allocation and free calls in the system. Call this immediately before the piece of code which you suspect is leaking memory. In host-based mode, the argument to this function is ignored, and the heap tracing module behaves like HEAP_TRACE_ALLis passed, i.e., all allocations and deallocations are sent to the host. Call the function heap_trace_stop()to stop the trace once the suspect piece of code has finished executing.
The following code snippet demonstrates how application code would typically initialize, start, and stop host-based mode heap tracing: #include "esp_heap_trace.h" ... void app_main() { ... ESP_ERROR_CHECK( heap_trace_init_tohost() ); ... } void some_function() { ESP_ERROR_CHECK( heap_trace_start(HEAP_TRACE_LEAKS) ); do_something_you_suspect_is_leaking(); ESP_ERROR_CHECK( heap_trace_stop() ); ... } To gather and analyze heap trace, do the following on the host: Build the program and download it to the target as described in Step 5.
In order to use this feature, you need OpenOCD version v0.10.0-esp32-20181105 or later. You can use GDB to start and/or stop tracing automatically. To do this you need to prepare a special gdbinitfile: target remote :3333 mon reset halt maintenance flush register-cache tb heap_trace_start commands mon esp sysview start file:///tmp/heap.svdat c end tb heap_trace_stop commands mon esp sysview stop end c Using this file GDB can connect to the target, reset it, and start tracing when the program hits breakpoint at heap_trace_start(). Tracing will be stopped when the program hits breakpoint at heap_trace_stop(). Traced data will be saved to /tmp/heap_log.svdat. Run GDB using xtensa-esp32-elf-gdb -x gdbinit </path/to/program/elf>. Quit GDB when the program stops at heap_trace_stop(). Traced data are saved in /tmp/heap.svdat. Run processing script $IDF_PATH/tools/esp_app_trace/sysviewtrace_proc.py -p -b </path/to/program/elf> /tmp/heap_log.svdat. The output from the heap trace has a similar format to the following example: Parse trace from '/tmp/heap.svdat'... Stop parsing trace.
Freed bytes @ 0x3ffb50bc from task "main" on core 0 by: /home/user/projects/esp/esp-idf/components/freertos/tasks.c:4590 /home/user/projects/esp/esp-idf/components/freertos/tasks.c:4590 [0.102436025] HEAP: Allocated 2 bytes @ 0x3ffaffe0 from task "alloc" on core 0 by: /home/user/projects/esp/esp-idf/examples/system/sysview_tracing_heap_log/main/sysview_heap_log.c:47 /home/user/projects/esp/esp-idf/components/freertos/port.c:355 (discriminator 1) [0.102449800] HEAP: Allocated 4 bytes @ 0x3ffaffe8 from task "alloc" on core 0 by: /home/user/projects/esp/esp-idf/examples/system/sysview_tracing_heap_log/main/sysview_heap_log.c:48 /home/user/projects/esp/esp-idf/components/freertos/port.c:355 (discriminator 1) [0.102666150] HEAP:
Freed bytes @ 0x3ffaffe8 from task "free" on core 0 by: /home/user/projects/esp/esp-idf/examples/system/sysview_tracing_heap_log/main/sysview_heap_log.c:31 (discriminator 9) /home/user/projects/esp/esp-idf/components/freertos/port.c:355 (discriminator 1) [0.202436200] HEAP: Allocated 3 bytes @ 0x3ffaffe8 from task "alloc" on core 0 by: /home/user/projects/esp/esp-idf/examples/system/sysview_tracing_heap_log/main/sysview_heap_log.c:47 /home/user/projects/esp/esp-idf/components/freertos/port.c:355 (discriminator 1)
HEAP: Allocated 4 bytes @ 0x3ffafff0 from task "alloc" on core 0 by: /home/user/projects/esp/esp-idf/examples/system/sysview_tracing_heap_log/main/sysview_heap_log.c:47 /home/user/projects/esp/esp-idf/components/freertos/port.c:355 (discriminator 1) [0.302451475] HEAP: Allocated 8 bytes @ 0x3ffb40b8 from task "alloc" on core 0 by: /home/user/projects/esp/esp-idf/examples/system/sysview_tracing_heap_log/main/sysview_heap_log.c:48 /home/user/projects/esp/esp-idf/components/freertos/port.c:355 (discriminator 1) [0.302667500] HEAP:
Processed 1019 events =============== HEAP TRACE REPORT =============== Processed 14 heap events. [0.002244575] HEAP: Allocated 1 bytes @ 0x3ffaffd8 from task "alloc" on core 0 by: /home/user/projects/esp/esp-idf/examples/system/sysview_tracing_heap_log/main/sysview_heap_log.c:47 /home/user/projects/esp/esp-idf/components/freertos/port.c:355 (discriminator 1) [0.102436025] HEAP: Allocated 2 bytes @ 0x3ffaffe0 from task "alloc" on core 0 by: /home/user/projects/esp/esp-idf/examples/system/sysview_tracing_heap_log/main/sysview_heap_log.c:47 /home/user/projects/esp/esp-idf/components/freertos/port.c:355 (discriminator 1) [0.202436200] HEAP: Allocated 3 bytes @ 0x3ffaffe8 from task "alloc" on core 0 by: /home/user/projects/esp/esp-idf/examples/system/sysview_tracing_heap_log/main/sysview_heap_log.c:47 /home/user/projects/esp/esp-idf/components/freertos/port.c:355 (discriminator 1)
This function must be called before any other heap tracing functions. To disable heap tracing and allow the buffer to be freed, stop tracing and then call heap_trace_init_standalone(NULL, 0); - Parameters record_buffer -- Provide a buffer to use for heap trace data. Note: External RAM is allowed, but it prevents recording allocations made from ISR's. num_records -- Size of the heap trace buffer, as number of record structures. - - Returns ESP_ERR_NOT_SUPPORTED Project was compiled without heap tracing enabled in menuconfig. ESP_ERR_INVALID_STATE Heap tracing is currently in progress. ESP_OK Heap tracing initialised successfully. - - esp_err_t heap_trace_init_tohost(void) Initialise heap tracing in host-based mode. This function must be called before any other heap tracing functions. - Returns ESP_ERR_INVALID_STATE Heap tracing is currently in progress. ESP_OK Heap tracing initialised successfully. - - esp_err_t heap_trace_start(heap_trace_mode_t mode) Start heap tracing. All heap allocations & frees will be traced, until heap_trace_stop() is called. Note heap_trace_init_standalone() must be called to provide a valid buffer, before this function is called. Note Calling this function while heap tracing is running will reset the heap trace state and continue tracing. - Parameters mode -- Mode for tracing. HEAP_TRACE_ALL means all heap allocations and frees are traced. HEAP_TRACE_LEAKS means only suspected memory leaks are traced. (When memory is freed, the record is removed from the trace buffer.) - - Returns ESP_ERR_NOT_SUPPORTED Project was compiled without heap tracing enabled in menuconfig
A non-zero-length buffer has not been set via heap_trace_init_standalone(). ESP_OK Tracing is started. - - esp_err_t heap_trace_stop(void) Stop heap tracing. - Returns ESP_ERR_NOT_SUPPORTED Project was compiled without heap tracing enabled in menuconfig. ESP_ERR_INVALID_STATE Heap tracing was not in progress. ESP_OK Heap tracing stopped.. - - esp_err_t heap_trace_resume(void) Resume heap tracing which was previously stopped. Unlike heap_trace_start(), this function does not clear the buffer of any pre-existing trace records. The heap trace mode is the same as when heap_trace_start() was last called (or HEAP_TRACE_ALL if heap_trace_start() was never called). - Returns ESP_ERR_NOT_SUPPORTED Project was compiled without heap tracing enabled in menuconfig.
[out] Record where the heap trace record will be copied. - - Returns ESP_ERR_NOT_SUPPORTED Project was compiled without heap tracing enabled in menuconfig. ESP_ERR_INVALID_STATE Heap tracing was not initialised. ESP_ERR_INVALID_ARG Index is out of bounds for current heap trace record count. ESP_OK Record returned successfully. - - void heap_trace_dump(void) Dump heap trace record data to stdout. Note It is safe to call this function while heap tracing is running, however in HEAP_TRACE_LEAK mode the dump may skip entries unless heap tracing is stopped first. - void heap_trace_dump_caps(const uint32_t caps) Dump heap trace from the memory of the capabilities passed as parameter. - Parameters caps -- Capability(ies) of the memory from which to dump the trace. Set MALLOC_CAP_INTERNAL to dump heap trace data from internal memory. Set MALLOC_CAP_SPIRAM to dump heap trace data from PSRAM. Set both to dump both heap trace data. - esp_err_t heap_trace_summary(heap_trace_summary_t *summary) Get summary information about the result of a heap trace. Note It is safe to call this function while heap tracing is running. Structures - struct heap_trace_record_t Trace record data type. Stores information about an allocated region of memory. Public Members - uint32_t ccount CCOUNT of the CPU when the allocation was made.
LSB (bit value 1) is the CPU number (0 or 1). - void *address Address which was allocated. If NULL, then this record is empty. - size_t size Size of the allocation. - void *alloced_by[CONFIG_HEAP_TRACING_STACK_DEPTH] Call stack of the caller which allocated the memory. - void *freed_by[CONFIG_HEAP_TRACING_STACK_DEPTH] Call stack of the caller which freed the memory (all zero if not freed.) - uint32_t ccount - struct heap_trace_summary_t Stores information about the result of a heap trace. Public Members - heap_trace_mode_t mode The heap trace mode we just completed / are running. - size_t total_allocations The total number of allocations made during tracing. - size_t total_frees The total number of frees made during tracing. - size_t count The number of records in the internal buffer. - size_t capacity The capacity of the internal buffer. - size_t high_water_mark The maximum value that 'count' got to. - size_t has_overflowed True if the internal buffer overflowed at some point. - heap_trace_mode_t mode Macros - CONFIG_HEAP_TRACING_STACK_DEPTH Type Definitions - typedef struct heap_trace_record_t heap_trace_record_t Trace record data type. Stores information about an allocated region of memory.
Although FreeRTOS provides software timers, FreeRTOS software timers have a few limitations: Maximum resolution is equal to the RTOS tick period Timer callbacks are dispatched from a low-priority timer service (i.e., daemon) task. This task can be preempted by other tasks, leading to decreased precision and accuracy. Although hardware timers are not subject to the limitations mentioned, they may not be as user-friendly. For instance, application components may require timer events to be triggered at specific future times, but hardware timers typically have only one "compare" value for interrupt generation. This necessitates the creation of an additional system on top of the hardware timer to keep track of pending events and ensure that callbacks are executed when the corresponding hardware interrupts occur. The hardware timer interrupt's priority is configured via the CONFIG_ESP_TIMER_INTERRUPT_LEVEL option (possible priorities being 1, 2, or 3). Raising the timer interrupt's priority can reduce the timer processing delay caused by interrupt latency. esp_timer set of APIs provides one-shot and periodic timers, microsecond time resolution, and 64-bit range. Internally, esp_timer uses a 64-bit hardware timer. The exact hardware timer implementation used depends on the target, where LAC timer is used for ESP32. Timer callbacks can be dispatched by two methods: ESP_TIMER_TASK.
Timer callbacks are dispatched directly from the timer interrupt handler. This method is useful for some simple callbacks which aim for lower latency. Creating and starting a timer, and dispatching the callback takes some time. Therefore, there is a lower limit to the timeout value of one-shot esp_timer. If esp_timer_start_once() is called with a timeout value of less than 20 us, the callback will be dispatched only after approximately 20 us. Periodic esp_timer also imposes a 50 us restriction on the minimal timer period. Periodic software timers with a period of less than 50 us are not practical since they would consume most of the CPU time. Consider using dedicated hardware peripherals or DMA features if you find that a timer with a small period is required. Using esp_timer APIs A single timer is represented by esp_timer_handle_t type. Each timer has a callback function associated with it. This callback function is called from the esp_timer task each time the timer elapses. To create a timer, call esp_timer_create(). To delete the timer when it is no longer needed, call esp_timer_delete(). The timer can be started in one-shot mode or in periodic mode. To start the timer in one-shot mode, call esp_timer_start_once(), passing the time interval after which the callback should be called. When the callback gets called, the timer is considered to be stopped. To start the timer in periodic mode, call esp_timer_start_periodic(), passing the period with which the callback should be called. The timer keeps running until esp_timer_stop()is called.
[out] Output, pointer to esp_timer_handle_t variable which will hold the created timer handle. - - Returns ESP_OK on success ESP_ERR_INVALID_ARG if some of the create_args are not valid ESP_ERR_INVALID_STATE if esp_timer library is not initialized yet ESP_ERR_NO_MEM if memory allocation fails - - esp_err_t esp_timer_start_once(esp_timer_handle_t timer, uint64_t timeout_us) Start one-shot timer. Timer should not be running when this function is called. - Parameters timer -- timer handle created using esp_timer_create timeout_us -- timer timeout, in microseconds relative to the current moment - - Returns ESP_OK on success ESP_ERR_INVALID_ARG if the handle is invalid ESP_ERR_INVALID_STATE if the timer is already running - - esp_err_t esp_timer_start_periodic(esp_timer_handle_t timer, uint64_t period) Start a periodic timer. Timer should not be running when this function is called. This function will start the timer which will trigger every 'period' microseconds. - Parameters timer -- timer handle created using esp_timer_create period -- timer period, in microseconds - - Returns ESP_OK on success ESP_ERR_INVALID_ARG if the handle is invalid ESP_ERR_INVALID_STATE if the timer is already running - - esp_err_t esp_timer_restart(esp_timer_handle_t timer, uint64_t timeout_us) Restart a currently running timer. If the given timer is a one-shot timer, the timer is restarted immediately and will timeout once in timeout_usmicroseconds. If the given timer is a periodic timer, the timer is restarted immediately with a new period of timeout_usmicroseconds. - Parameters timer -- timer Handle created using esp_timer_create timeout_us -- Timeout, in microseconds relative to the current time. In case of a periodic timer, also represents the new period. - - Returns ESP_OK on success ESP_ERR_INVALID_ARG if the handle is invalid ESP_ERR_INVALID_STATE if the timer is not running - - esp_err_t esp_timer_stop(esp_timer_handle_t timer) Stop the timer. This function stops the timer previously started using esp_timer_start_once or esp_timer_start_periodic. - Parameters timer -- timer handle created using esp_timer_create - Returns ESP_OK on success ESP_ERR_INVALID_STATE if the timer is not running - - esp_err_t esp_timer_delete(esp_timer_handle_t
Internal and Unstable APIs This section is listing some APIs that are internal or likely to be changed or removed in the next releases of ESP-IDF. API Reference Header File This header file can be included with: #include "esp_rom_sys.h" Functions - void esp_rom_software_reset_system(void) Software Reset digital core include RTC. It is not recommended to use this function in esp-idf, use esp_restart() instead. - void esp_rom_software_reset_cpu(int cpu_no) Software Reset cpu core. It is not recommended to use this function in esp-idf, use esp_restart() instead. - Parameters cpu_no -- : The CPU to reset, 0 for PRO CPU, 1 for APP CPU. - int esp_rom_printf(const char *fmt, ...) Print formated string to console device. Note float and long long data are not supported! - Parameters fmt -- Format string ... -- Additional arguments, depending on the format string - - Returns int: Total number of characters written on success; A negative number on failure. - void esp_rom_delay_us(uint32_t us) Pauses execution for us microseconds. - Parameters us -- Number of microseconds to pause - void esp_rom_install_channel_putc(int channel, void (*putc)(char c)) esp_rom_printf can print message to different channels simultaneously. This function can help install the low level putc function for esp_rom_printf. - Parameters channel -- Channel number (startting from 1) putc -- Function pointer to the putc implementation. Set NULL can disconnect esp_rom_printf with putc. - - void esp_rom_install_uart_printf(void) Install UART1 as the default console channel, equivalent to esp_rom_install_channel_putc(1, esp_rom_uart_putc) - soc_reset_reason_t esp_rom_get_reset_reason(int cpu_no)
On targets that use CLIC as their interrupt controller, this number represents the external interrupt number. For example, passing cpu_intr_num = ito this function would in fact bind peripheral source to CPU interrupt CLIC_EXT_INTR_NUM_OFFSET + i. - - - uint32_t esp_rom_get_cpu_ticks_per_us(void) Get the real CPU ticks per us. - Returns CPU ticks per us - void esp_rom_set_cpu_ticks_per_us(uint32_t ticks_per_us) Set the real CPU tick rate. Note Call this function when CPU frequency is changed, otherwise the esp_rom_delay_uscan be inaccurate. - Parameters ticks_per_us -- CPU ticks per us
Note IPC stands for an "Inter-Processor Call" and NOT "Inter-Process Communication" as found on other operating systems. Overview Due to the dual core nature of the ESP32, there are some scenarios where a certain callback must be executed from a particular core such as: When allocating an ISR to an interrupt source of a particular core (applies to freeing a particular core's interrupt source as well) On particular chips (such as the ESP32), accessing memory that is exclusive to a particular core (such as RTC Fast Memory) Reading the registers/state of another core The IPC (Inter-Processor Call) feature allows a particular core (the calling core) to trigger the execution of a callback function on another core (the target core). The IPC feature allows execution of a callback function on the target core in either a task context, or an interrupt context. Depending on the context that the callback function is executed in, different restrictions apply to the implementation of the callback function. IPC in Task Context The IPC feature implements callback execution in a task context by creating an IPC task for each core during application startup. When the calling core needs to execute a callback on the target core, the callback will execute in the context of the target core's IPC task. When using IPCs in a task context, users need to consider the following: IPC callbacks should ideally be simple and short. An IPC callback must never block or yield.
esp_test_ipc_isr_get_cycle_count_other_cpu .type esp_test_ipc_isr_get_cycle_count_other_cpu, @function // Args: // a2 - void* arg esp_test_ipc_isr_get_cycle_count_other_cpu: rsr.ccount a3 s32i a3, a2, 0 ret unit32_t cycle_count; esp_ipc_isr_call_blocking(esp_test_ipc_isr_get_cycle_count_other_cpu, (void *)cycle_count); Note The number of scratch registers available for use is sufficient for most simple use cases. But if your callback requires more scratch registers, void *arg can point to a buffer that is used as a register save area. The callback can then save and restore more registers. See the system/ipc/ipc_isr. Note For more examples of High Priority Interrupt IPC callbacks, you can refer to components/esp_system/port/arch/xtensa/esp_ipc_isr_routines. S and components/esp_system/test_apps/esp_system_unity_tests/main/port/arch/xtensa/test_ipc_isr. S. See examples/system/ipc/ipc_isr/xtensa/main/main.c for an example of its use. The High Priority Interrupt IPC API also provides the following convenience functions that can stall/resume the target core. These APIs utilize the High Priority Interrupt IPC, but supply their own internal callbacks: esp_ipc_isr_stall_other_cpu()stalls the target core. The calling core disables interrupts of level 3 and lower while the target core will busy-wait with interrupts of level 5 and lower disabled. The target core will busy-wait until esp_ipc_isr_release_other_cpu()is called. esp_ipc_isr_release_other_cpu()resumes the target core. API Reference Header File This header file can be included with: #include "esp_ipc.h" Functions - esp_err_t esp_ipc_call(uint32_t cpu_id, esp_ipc_func_t func, void *arg) Execute a callback on a given CPU. Execute a given callback on a particular CPU. The callback must be of type "esp_ipc_func_t" and will be invoked in the context of the target CPU's IPC task. This function will block the target CPU's IPC task has begun execution of the callback If another IPC call is ongoing, this function will block until the ongoing IPC call completes The stack size of the IPC task can be configured via the CONFIG_ESP_IPC_TASK_STACK_SIZE option Note In single-core mode, returns ESP_ERR_INVALID_ARG for cpu_id 1. - Parameters cpu_id -- [in] CPU where the given function should be executed (0 or 1) func -- [in] Pointer to a function of type void func(void* arg) to be executed arg -- [in] Arbitrary argument of type void* to be passed into the function - - Returns ESP_ERR_INVALID_ARG if cpu_id is invalid ESP_ERR_INVALID_STATE if the FreeRTOS scheduler is not running ESP_OK otherwise - - - esp_err_t esp_ipc_call_blocking(uint32_t cpu_id, esp_ipc_func_t func, void *arg) Execute a callback on a given CPU until and block until it completes. This function is identical to esp_ipc_call() except that this function will block until the execution of the callback completes.
If a IPC ISR call is already in progress, this function will busy-wait until the call completes before pausing the CPU stall feature. - void esp_ipc_isr_stall_abort(void) Abort a CPU stall. This function will abort any stalling routine of the other CPU due to a pervious call to esp_ipc_isr_stall_other_cpu(). This function aborts the stall in a non-recoverable manner, thus should only be called in case of a panic(). This function is used in panic handling code - - void esp_ipc_isr_stall_resume(void) Resume the CPU stall feature. This function will resume the CPU stall feature that was previously paused by calling esp_ipc_isr_stall_pause(). Once resumed, calls to esp_ipc_isr_stall_other_cpu() and esp_ipc_isr_release_other_cpu() will have effect again. Macros - esp_ipc_isr_asm_call(func, arg) Execute an ISR callback on the other CPU See esp_ipc_isr_call(). - esp_ipc_isr_asm_call_blocking(func, arg) Execute an ISR callback on the other CPU and busy-wait until it completes See esp_ipc_isr_call_blocking(). Type Definitions - typedef void (*esp_ipc_isr_func_t)(void *arg) IPC ISR Callback.
Interrupt Allocation Overview The ESP32 has two cores, with 32 interrupts each. Each interrupt has a fixed priority, most (but not all) interrupts are connected to the interrupt matrix. Because there are more interrupt sources than interrupts, sometimes it makes sense to share an interrupt in multiple drivers. The esp_intr_alloc() abstraction exists to hide all these implementation details. A driver can allocate an interrupt for a certain peripheral by calling esp_intr_alloc() (or esp_intr_alloc_intrstatus()).
Though the framework supports this feature, you have to use it very carefully. There usually exist two ways to stop an interrupt from being triggered: disable the source or mask peripheral interrupt status. ESP-IDF only handles enabling and disabling of the source itself, leaving status and mask bits to be handled by users. Status bits shall either be masked before the handler responsible for it is disabled, or be masked and then properly handled in another enabled interrupt. Note Leaving some status bits unhandled without masking them, while disabling the handlers for them, will cause the interrupt(s) to be triggered indefinitely, resulting therefore in a system crash. Troubleshooting Interrupt Allocation On most Espressif SoCs, CPU interrupts are a limited resource. Therefore it is possible for a program to run out of CPU interrupts, for example by initializing several peripheral drivers. Typically, this will result in the driver initialization function returning ESP_ERR_NOT_FOUND error code. If this happens, you can use esp_intr_dump() function to print the list of interrupts along with their status.
Free: The interrupt is not allocated and can be used by esp_intr_alloc(). - Free (not general-use): The interrupt is not allocated, but is either a high-priority interrupt (priority 4-7) or an edge-triggered interrupt. High-priority interrupts can be allocated using esp_intr_alloc()but requires the handlers to be written in Assembly, see High Priority Interrupts. Edge-triggered low- and medium-priority interrupts can also be allocated using esp_intr_alloc(), but are not used often since most peripheral interrupts are level-triggered. If you have confirmed that the application is indeed running out of interrupts, a combination of the following suggestions can help resolve the issue: On multi-core SoCs, try initializing some of the peripheral drivers from a task pinned to the second core. Interrupts are typically allocated on the same core where the peripheral driver initialization function runs. Therefore by running the initialization function on the second core, more interrupt inputs can be used. Determine the interrupts which can tolerate higher latency, and allocate them using ESP_INTR_FLAG_SHAREDflag (optionally ORed with ESP_INTR_FLAG_LOWMED). Using this flag for two or more peripherals will let them use a single interrupt input, and therefore save interrupt inputs for other peripherals.
Some peripheral driver may default to allocating interrupts with ESP_INTR_FLAG_LEVEL1flag, so priority 2 and 3 interrupts do not get used by default. If esp_intr_dump()shows that some priority 2 or 3 interrupts are available, try changing the interrupt allocation flags when initializing the driver to ESP_INTR_FLAG_LEVEL2or ESP_INTR_FLAG_LEVEL3. Check if some of the peripheral drivers do not need to be used all the time, and initialize or deinitialize them on demand. This can reduce the number of simultaneously allocated interrupts.
Optional argument for passed to the interrupt handler ret_handle -- Pointer to an intr_handle_t to store a handle that can later be used to request details or free the interrupt. Can be NULL if no handle is required. - - Returns ESP_ERR_INVALID_ARG if the combination of arguments is invalid. ESP_ERR_NOT_FOUND No free interrupt found with the specified flags ESP_OK otherwise - esp_err_t esp_intr_alloc_intrstatus(int source, int flags, uint32_t intrstatusreg, uint32_t intrstatusmask, intr_handler_t handler, void *arg, intr_handle_t *ret_handle) Allocate an interrupt with the given parameters. This essentially does the same as esp_intr_alloc, but allows specifying a register and mask combo. For shared interrupts, the handler is only called if a read from the specified register, ANDed with the mask, returns non-zero. By passing an interrupt status register address and a fitting mask, this can be used to accelerate interrupt handling in the case a shared interrupt is triggered; by checking the interrupt statuses first, the code can decide which ISRs can be skipped - Parameters source -- The interrupt source. One of the ETS_*_INTR_SOURCE interrupt mux sources, as defined in soc/soc.h, or one of the internal ETS_INTERNAL_*_INTR_SOURCE sources as defined in this header. flags -- An ORred mask of the ESP_INTR_FLAG_* defines. These restrict the choice of interrupts that this routine can choose from. If this value is 0, it will default to allocating a non-shared interrupt of level 1, 2 or 3. If this is ESP_INTR_FLAG_SHARED, it will allocate a shared interrupt of level 1. Setting ESP_INTR_FLAG_INTRDISABLED will return from this function with the interrupt disabled. intrstatusreg -- The address of an interrupt status register intrstatusmask -- A mask. If a read of address intrstatusreg has any of the bits that are 1 in the mask set, the ISR will be called. If not, it will be skipped. handler -- The interrupt handler. Must be NULL when an interrupt of level >3 is requested, because these types of interrupts aren't C-callable.
Optional argument for passed to the interrupt handler ret_handle -- Pointer to an intr_handle_t to store a handle that can later be used to request details or free the interrupt. Can be NULL if no handle is required. - - Returns ESP_ERR_INVALID_ARG if the combination of arguments is invalid. ESP_ERR_NOT_FOUND No free interrupt found with the specified flags ESP_OK otherwise - esp_err_t esp_intr_free(intr_handle_t handle) Disable and free an interrupt. Use an interrupt handle to disable the interrupt and release the resources associated with it. If the current core is not the core that registered this interrupt, this routine will be assigned to the core that allocated this interrupt, blocking and waiting until the resource is successfully released. Note When the handler shares its source with other handlers, the interrupt status bits it's responsible for should be managed properly before freeing it. see esp_intr_disablefor more details. Please do not call this function in esp_ipc_call_blocking. - Parameters handle -- The handle, as obtained by esp_intr_alloc or esp_intr_alloc_intrstatus - Returns ESP_ERR_INVALID_ARG the handle is NULL ESP_FAIL failed to release this handle ESP_OK otherwise - int esp_intr_get_cpu(intr_handle_t handle) Get CPU number an interrupt is tied to. - Parameters handle -- The handle, as obtained by esp_intr_alloc or esp_intr_alloc_intrstatus - Returns The core number where the interrupt is allocated - int esp_intr_get_intno(intr_handle_t handle) Get the allocated interrupt for a certain handle. - Parameters handle -- The handle, as obtained by esp_intr_alloc or esp_intr_alloc_intrstatus - Returns The interrupt number - esp_err_t esp_intr_disable(intr_handle_t handle) Disable the interrupt associated with the handle. Note For local interrupts (ESP_INTERNAL_* sources), this function has to be called on the CPU the interrupt is allocated on. Other interrupts have no such restriction. When several handlers sharing a same interrupt source, interrupt status bits, which are handled in the handler to be disabled, should be masked before the disabling, or handled in other enabled interrupts properly. Miss of interrupt status handling will cause infinite interrupt calls and finally system crash. - Parameters handle -- The handle, as obtained by esp_intr_alloc or esp_intr_alloc_intrstatus - Returns ESP_ERR_INVALID_ARG if the combination of arguments is invalid. ESP_OK otherwise - - esp_err_t esp_intr_enable(intr_handle_t handle)
Enable the interrupt associated with the handle. Note For local interrupts (ESP_INTERNAL_* sources), this function has to be called on the CPU the interrupt is allocated on. Other interrupts have no such restriction. - Parameters handle -- The handle, as obtained by esp_intr_alloc or esp_intr_alloc_intrstatus - Returns ESP_ERR_INVALID_ARG if the combination of arguments is invalid. ESP_OK otherwise - esp_err_t esp_intr_set_in_iram(intr_handle_t handle, bool is_in_iram) Set the "in IRAM" status of the handler. Note Does not work on shared interrupts. - Parameters handle -- The handle, as obtained by esp_intr_alloc or esp_intr_alloc_intrstatus is_in_iram -- Whether the handler associated with this handle resides in IRAM. Handlers residing in IRAM can be called when cache is disabled. - - Returns ESP_ERR_INVALID_ARG if the combination of arguments is invalid. ESP_OK otherwise - void esp_intr_noniram_disable(void) Disable interrupts that aren't specifically marked as running from IRAM. - void esp_intr_noniram_enable(void) Re-enable interrupts disabled by esp_intr_noniram_disable. - void esp_intr_enable_source(int inum) enable the interrupt source based on its number - Parameters inum -- interrupt number from 0 to 31 - void esp_intr_disable_source(int inum) disable the interrupt source based on its number - Parameters inum -- interrupt number from 0 to 31 - static inline int esp_intr_flags_to_level(int flags) Get the lowest interrupt level from the flags. - Parameters flags -- The same flags that pass to esp_intr_alloc_intrstatusAPI - static inline int esp_intr_level_to_flags(int level) Get the interrupt flags from the supplied level (priority) - Parameters level -- The interrupt priority level Macros - ESP_INTR_FLAG_LEVEL1 Interrupt allocation flags. These flags can be used to specify which interrupt qualities the code calling esp_intr_alloc* needs.
Accept a Level 1 interrupt vector (lowest priority) - ESP_INTR_FLAG_LEVEL2 Accept a Level 2 interrupt vector. - ESP_INTR_FLAG_LEVEL3 Accept a Level 3 interrupt vector. - ESP_INTR_FLAG_LEVEL4 Accept a Level 4 interrupt vector. - ESP_INTR_FLAG_LEVEL5 Accept a Level 5 interrupt vector. - ESP_INTR_FLAG_LEVEL6 Accept a Level 6 interrupt vector. - ESP_INTR_FLAG_NMI Accept a Level 7 interrupt vector (highest priority) - ESP_INTR_FLAG_SHARED Interrupt can be shared between ISRs. - ESP_INTR_FLAG_EDGE Edge-triggered interrupt. - ESP_INTR_FLAG_IRAM ISR can be called if cache is disabled. - ESP_INTR_FLAG_INTRDISABLED Return with this interrupt disabled. - ESP_INTR_FLAG_LOWMED Low and medium prio interrupts. These can be handled in C. - ESP_INTR_FLAG_HIGH High level interrupts. Need to be handled in assembly. - ESP_INTR_FLAG_LEVELMASK Mask for all level flags. - ETS_INTERNAL_TIMER0_INTR_SOURCE Platform timer 0 interrupt source. The esp_intr_alloc* functions can allocate an int for all ETS_*_INTR_SOURCE interrupt sources that are routed through the interrupt mux. Apart from these sources, each core also has some internal sources that do not pass through the interrupt mux. To allocate an interrupt for these sources, pass these pseudo-sources to the functions. - ETS_INTERNAL_TIMER1_INTR_SOURCE Platform timer 1 interrupt source. - ETS_INTERNAL_TIMER2_INTR_SOURCE Platform timer 2 interrupt source. - ETS_INTERNAL_SW0_INTR_SOURCE Software int source 1. - ETS_INTERNAL_SW1_INTR_SOURCE Software int source 2. - ETS_INTERNAL_PROFILING_INTR_SOURCE Int source for profiling. - ETS_INTERNAL_UNUSED_INTR_SOURCE Interrupt is not assigned to any source. - ETS_INTERNAL_INTR_SOURCE_OFF Provides SystemView with positive IRQ IDs, otherwise scheduler events are not shown properly - ESP_INTR_ENABLE(inum) Enable interrupt by interrupt number - ESP_INTR_DISABLE(inum) Disable interrupt by interrupt number
Logging library Overview The logging library provides three ways for setting log verbosity: At compile time: in menuconfig, set the verbosity level using the option CONFIG_LOG_DEFAULT_LEVEL. Optionally, also in menuconfig, set the maximum verbosity level using the option CONFIG_LOG_MAXIMUM_LEVEL. By default, this is the same as the default level, but it can be set higher in order to compile more optional logs into the firmware. At runtime: all logs for verbosity levels lower than CONFIG_LOG_DEFAULT_LEVEL are enabled by default. The function esp_log_level_set()can be used to set a logging level on a per-module basis. Modules are identified by their tags, which are human-readable ASCII zero-terminated strings. At runtime: if CONFIG_LOG_MASTER_LEVEL is enabled then a Master logging levelcan be set using esp_log_set_level_master(). This option adds an additional logging level check for all compiled logs. Note that this will increase application size. This feature is useful if you want to compile in a lot of logs that are selectable at runtime, but also want to avoid the performance hit from looking up the tags and their log level when you don't want log output.
There are the following verbosity levels: Error (lowest) Warning Info Debug Verbose (highest) Note The function esp_log_level_set() cannot set logging levels higher than specified by CONFIG_LOG_MAXIMUM_LEVEL. To increase log level for a specific file above this maximum at compile time, use the macro LOG_LOCAL_LEVEL (see the details below). How to use this library In each C file that uses logging functionality, define the TAG variable as shown below: static const char* TAG = "MyModule"; Then use one of logging macros to produce output, e.g: ESP_LOGW(TAG, "Baud rate error %.1f%%. Requested: %d baud, actual: %d baud", error * 100, baud_req, baud_real); Several macros are available for different verbosity levels: ESP_LOGE- error (lowest) ESP_LOGW- warning ESP_LOGI- info ESP_LOGD- debug ESP_LOGV- verbose (highest)
Additionally, there are ESP_EARLY_LOGx versions for each of these macros, e.g. ESP_EARLY_LOGE. These versions have to be used explicitly in the early startup code only, before heap allocator and syscalls have been initialized. Normal ESP_LOGx macros can also be used while compiling the bootloader, but they will fall back to the same implementation as ESP_EARLY_LOGx macros. There are also ESP_DRAM_LOGx versions for each of these macros, e.g. ESP_DRAM_LOGE. These versions are used in some places where logging may occur with interrupts disabled or with flash cache inaccessible. Use of this macros should be as sparing as possible, as logging in these types of code should be avoided for performance reasons. Note Inside critical sections interrupts are disabled so it's only possible to use ESP_DRAM_LOGx (preferred) or ESP_EARLY_LOGx. Even though it's possible to log in these situations, it's better if your program can be structured not to require it. To override default verbosity level at file or component scope, define the LOG_LOCAL_LEVEL macro.
At file scope, define it before including esp_log.h, e.g.: #define LOG_LOCAL_LEVEL ESP_LOG_VERBOSE #include "esp_log.h" At component scope, define it in the component CMakeLists: target_compile_definitions(${COMPONENT_LIB} PUBLIC "-DLOG_LOCAL_LEVEL=ESP_LOG_VERBOSE") To configure logging output per module at runtime, add calls to the function esp_log_level_set() as follows: esp_log_level_set("*", ESP_LOG_ERROR); // set all components to ERROR level esp_log_level_set("wifi", ESP_LOG_WARN); // enable WARN logs from WiFi stack esp_log_level_set("dhcpc", ESP_LOG_INFO); // enable INFO logs from DHCP client Note The "DRAM" and "EARLY" log macro variants documented above do not support per module setting of log verbosity. These macros will always log at the "default" verbosity level, which can only be changed at runtime by calling esp_log_level("*", level). Even when logs are disabled by using a tag name they will still require a processing time of around 10.9 microseconds per entry. Master Logging Level To enable the Master logging level feature, the CONFIG_LOG_MASTER_LEVEL option must be enabled.
It adds an additional level check for ESP_LOGx macros before calling esp_log_write(). This allows to set a higher CONFIG_LOG_MAXIMUM_LEVEL, but not inflict a performance hit during normal operation (only when directed). An application may set the master logging level ( esp_log_set_level_master()) globally to enforce a maximum log level. ESP_LOGx macros above this level will be skipped immediately, rather than calling esp_log_write() and doing a tag lookup. It is recommended to only use this in an top-level application and not in shared components as this would override the global log level for any user using the component. By default, at startup, the Master logging level is CONFIG_LOG_DEFAULT_LEVEL. Note that this feature increases application size because the additional check is added into all ESP_LOGx macros. The snippet below shows how it works. Setting the Master logging level to ESP_LOG_NONE disables all logging globally. esp_log_level_set() does not currently affect logging. But after the Master logging level is released, the logs will be printed as set by esp_log_level_set(). // Master logging level is CONFIG_LOG_DEFAULT_LEVEL at start up and = ESP_LOG_INFO ESP_LOGI("lib_name", "Message for print"); // prints a INFO message esp_log_level_set("lib_name", ESP_LOG_WARN); // enables WARN logs from lib_name esp_log_set_level_master(ESP_LOG_NONE); // disables all logs globally.
ESP_LOGW("lib_name", "Message for print"); // no print, Master logging level blocks it esp_log_level_set("lib_name", ESP_LOG_INFO); // enable INFO logs from lib_name ESP_LOGI("lib_name", "Message for print"); // no print, Master logging level blocks it esp_log_set_level_master(ESP_LOG_INFO); // enables all INFO logs globally. ESP_LOGI("lib_name", "Message for print"); // prints a INFO message Logging to Host via JTAG By default, the logging library uses the vprintf-like function to write formatted output to the dedicated UART. By calling a simple API, all log output may be routed to JTAG instead, making logging several times faster. For details, please refer to Section Logging to Host. Thread Safety The log string is first written into a memory buffer and then sent to the UART for printing. Log calls are thread-safe, i.e., logs of different threads do not conflict with each other. Application Example The logging library is commonly used by most ESP-IDF components and examples. For demonstration of log functionality, check ESP-IDF's examples directory. The most relevant examples that deal with logging are the following: API Reference Header File This header file can be included with: #include "esp_log.h" Functions - void esp_log_set_level_master(esp_log_level_t level) Master log level. Optional master log level to check against for ESP_LOGx macros before calling esp_log_write. Allows one to set a higher CONFIG_LOG_MAXIMUM_LEVEL but not impose a performance hit during normal operation (only when instructed). An application may set esp_log_set_level_master(level) to globally enforce a maximum log level. ESP_LOGx macros above this level will be skipped immediately, rather than calling esp_log_write and doing a cache hit. The tradeoff is increased application size. - Parameters level -- Master log level - esp_log_level_t esp_log_get_level_master(void) Returns master log level. - Returns Master log level - void esp_log_level_set(const char *tag, esp_log_level_t level) Set log level for given tag.
If logging for given component has already been enabled, changes previous setting. Note Note that this function can not raise log level above the level set using CONFIG_LOG_MAXIMUM_LEVEL setting in menuconfig. To raise log level above the default one for a given file, define LOG_LOCAL_LEVEL to one of the ESP_LOG_* values, before including esp_log.h in this file. - Parameters tag -- Tag of the log entries to enable. Must be a non-NULL zero terminated string. Value "*" resets log level for all tags to the given value. level -- Selects log level to enable. Only logs at this and lower verbosity levels will be shown. - - esp_log_level_t esp_log_level_get(const char *tag) Get log level for a given tag, can be used to avoid expensive log statements. - Parameters tag -- Tag of the log to query current level. Must be a non-NULL zero terminated string. - Returns The current log level for the given tag - vprintf_like_t esp_log_set_vprintf(vprintf_like_t func) Set function used to output log entries. By default, log output goes to UART0. This function can be used to redirect log output to some other destination, such as file or network. Returns the original log handler, which may be necessary to return output to the previous destination. Note Please note that function callback here must be re-entrant as it can be invoked in parallel from multiple thread context. - Parameters func -- new Function used for output. Must have same signature as vprintf. - Returns func old Function used for output. - uint32_t esp_log_timestamp(void) Function which returns timestamp to be used in log output. This function is used in expansion of ESP_LOGx macros. In the 2nd stage bootloader, and at early application startup stage this function uses CPU cycle counter as time source. Later when FreeRTOS scheduler start running, it switches to FreeRTOS tick count. For now, we ignore millisecond counter overflow. - Returns timestamp, in milliseconds - char *esp_log_system_timestamp(void) Function which returns system timestamp to be used in log output. This function is used in expansion of ESP_LOGx macros to print the system time as "HH:MM:SS.sss". The system time is initialized to 0 on startup, this can be set to the correct time with an SNTP sync, or manually with standard POSIX time functions. Currently, this will not get used in logging from binary blobs (i.e. Wi-Fi & Bluetooth libraries), these will still print the RTOS tick time. - Returns timestamp, in "HH:MM:SS.sss" - uint32_t esp_log_early_timestamp(void) Function which returns timestamp to be used in log output. This function uses HW cycle counter and does not depend on OS, so it can be safely used after application crash. - Returns timestamp, in milliseconds - void esp_log_write(esp_log_level_t level, const char *tag, const char *format, ...) Write message into the log. This function is not intended to be used directly.
See also esp_log_write() Macros - ESP_LOG_BUFFER_HEX_LEVEL(tag, buffer, buff_len, level) Log a buffer of hex bytes at specified level, separated into 16 bytes each line. - Parameters tag -- description tag buffer -- Pointer to the buffer array buff_len -- length of buffer in bytes level -- level of the log - - ESP_LOG_BUFFER_CHAR_LEVEL(tag, buffer, buff_len, level) Log a buffer of characters at specified level, separated into 16 bytes each line. Buffer should contain only printable characters. - Parameters tag -- description tag buffer -- Pointer to the buffer array buff_len -- length of buffer in bytes level -- level of the log - - ESP_LOG_BUFFER_HEXDUMP(tag, buffer, buff_len, level) Dump a buffer to the log at specified level.
The dump log shows just like the one below: W (195) log_example: 0x3ffb4280 45 53 50 33 32 20 69 73 20 67 72 65 61 74 2c 20 |ESP32 is great, | W (195) log_example: 0x3ffb4290 77 6f 72 6b 69 6e 67 20 61 6c 6f 6e 67 20 77 69 |working along wi| W (205) log_example: 0x3ffb42a0 74 68 20 74 68 65 20 49 44 46 2e 00 |th the IDF..| It is highly recommended to use terminals with over 102 text width. - Parameters tag -- description tag buffer -- Pointer to the buffer array buff_len -- length of buffer in bytes level -- level of the log - - ESP_LOG_BUFFER_HEX(tag, buffer, buff_len) Log a buffer of hex bytes at Info level. See also esp_log_buffer_hex_level - Parameters tag -- description tag buffer -- Pointer to the buffer array buff_len -- length of buffer in bytes - - ESP_LOG_BUFFER_CHAR(tag, buffer, buff_len) Log a buffer of characters at Info level. Buffer should contain only printable characters. See also esp_log_buffer_char_level - Parameters tag -- description tag buffer -- Pointer to the buffer array buff_len -- length of buffer in bytes - - ESP_EARLY_LOGE(tag, format, ...) macro to output logs in startup code, before heap allocator and syscalls have been initialized. Log at ESP_LOG_ERRORlevel.
See also printf, ESP_LOGE, ESP_DRAM_LOGEIn the future, we want to become compatible with clang. Hence, we provide two versions of the following macros which are using variadic arguments. The first one is using the GNU extension ##__VA_ARGS__. The second one is using the C++20 feature VA_OPT(,). This allows users to compile their code with standard C++20 enabled instead of the GNU extension. Below C++20, we haven't found any good alternative to using ##__VA_ARGS__. - ESP_EARLY_LOGW(tag, format, ...) macro to output logs in startup code at ESP_LOG_WARNlevel. See also ESP_EARLY_LOGE, ESP_LOGE, printf - ESP_EARLY_LOGI(tag, format, ...) macro to output logs in startup code at ESP_LOG_INFOlevel. See also ESP_EARLY_LOGE, ESP_LOGE, printf - ESP_EARLY_LOGD(tag, format, ...) macro to output logs in startup code at ESP_LOG_DEBUGlevel. See also ESP_EARLY_LOGE, ESP_LOGE, printf - ESP_EARLY_LOGV(tag, format, ...) macro to output logs in startup code at ESP_LOG_VERBOSElevel. See also ESP_EARLY_LOGE, ESP_LOGE, printf - _ESP_LOG_EARLY_ENABLED(log_level) - ESP_LOG_EARLY_IMPL(tag, format, log_level, log_tag_letter, ...) - ESP_LOGE(tag, format, ...) - ESP_LOGW(tag, format, ...) - ESP_LOGI(tag, format, ...) - ESP_LOGD(tag, format, ...) - ESP_LOGV(tag, format, ...) - ESP_LOG_LEVEL(level, tag, format, ...) runtime macro to output logs at a specified level. See also printf - Parameters tag -- tag of the log, which can be used to change the log level by esp_log_level_setat runtime. level -- level of the output log. format -- format of the output log. See printf ... -- variables to be replaced into the log. See printf - - ESP_LOG_LEVEL_LOCAL(level, tag, format, ...) runtime macro to output logs at a specified level. Also check the level with LOG_LOCAL_LEVEL. If CONFIG_LOG_MASTER_LEVELset, also check first against esp_log_get_level_master(). See also printf, ESP_LOG_LEVEL - ESP_DRAM_LOGE(tag, format, ...) Macro to output logs when the cache is disabled. Log at ESP_LOG_ERRORlevel.
Similar to Usage: ESP_DRAM_LOGE(DRAM_STR("my_tag"), "format", orESP_DRAM_LOGE(TAG, "format", ...)`, where TAG is a char* that points to a str in the DRAM. See also ESP_EARLY_LOGE, the log level cannot be changed per-tag, however esp_log_level_set("*", level) will set the default level which controls these log lines also. See also esp_rom_printf, ESP_LOGE Note Unlike normal logging macros, it's possible to use this macro when interrupts are disabled or inside an ISR. Note Placing log strings in DRAM reduces available DRAM, so only use when absolutely essential. - ESP_DRAM_LOGW(tag, format, ...) macro to output logs when the cache is disabled at ESP_LOG_WARNlevel. See also ESP_DRAM_LOGW, ESP_LOGW, esp_rom_printf - ESP_DRAM_LOGI(tag, format, ...) macro to output logs when the cache is disabled at ESP_LOG_INFOlevel. See also ESP_DRAM_LOGI, ESP_LOGI, esp_rom_printf - ESP_DRAM_LOGD(tag, format, ...) macro to output logs when the cache is disabled at ESP_LOG_DEBUGlevel. See also ESP_DRAM_LOGD, ESP_LOGD, esp_rom_printf - ESP_DRAM_LOGV(tag, format, ...) macro to output logs when the cache is disabled at ESP_LOG_VERBOSElevel. See also ESP_DRAM_LOGV, ESP_LOGV, esp_rom_printf Type Definitions - typedef int (*vprintf_like_t)(const char*, va_list) Enumerations - enum esp_log_level_t Log level. Values: - enumerator ESP_LOG_NONE No log output - enumerator ESP_LOG_ERROR Critical errors, software module can not recover on its own - enumerator ESP_LOG_WARN Error conditions from which recovery measures have been taken - enumerator ESP_LOG_INFO Information messages which describe normal flow of events - enumerator ESP_LOG_DEBUG Extra information which is not necessary for normal use (values, pointers, sizes, etc). - enumerator ESP_LOG_VERBOSE Bigger chunks of debugging information, or frequent messages which can potentially flood the output. - enumerator ESP_LOG_NONE
Miscellaneous System APIs Software Reset To perform software reset of the chip, the esp_restart() function is provided. When the function is called, execution of the program stops, both CPUs are reset, the application is loaded by the bootloader and starts execution again. Additionally, the esp_register_shutdown_handler() function can register a routine that will be automatically called before a restart (that is triggered by 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 esp_reset_reason() function. See description of esp_reset_reason_t for the list of possible reset reasons. Heap Memory Two heap-memory-related functions are provided: esp_get_free_heap_size()returns the current size of free heap memory. esp_get_minimum_free_heap_size()returns the minimum size of free heap memory that has ever been available (i.e., the smallest size of free heap memory in the application's lifetime). 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 Heap Memory 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 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 ESP32 eFuse in the factory during production.
| Interface | MAC Address (4 universally administered, default) | MAC Address (2 universally administered) | Wi-Fi Station | base_mac | base_mac | Wi-Fi SoftAP | base_mac, +1 to the last octet | Local MAC (derived from Wi-Fi Station MAC) | Bluetooth | base_mac, +2 to the last octet | base_mac, +1 to the last octet | Ethernet | base_mac, +3 to the last octet | Local MAC (derived from Bluetooth MAC) Note The configuration configures the number of universally administered MAC addresses that are provided by Espressif.
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 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 BLK0. To set a custom base MAC instead, call the function esp_iface_mac_addr_set() with the ESP_MAC_BASE argument (or esp_base_mac_addr_set()) before initializing any network interfaces or calling the 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. Based on the table above, users can configure the option CONFIG_ESP32_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 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 esp_efuse_mac_get_custom(). Users can also use esp_read_mac() with the ESP_MAC_EFUSE_CUSTOM argument. This loads the MAC address from eFuse BLK3.
Once custom eFuse MAC address has been obtained (using esp_efuse_mac_get_custom() or esp_read_mac()), you need to set it as the base MAC address. There are two ways to do it: Use an old API: call esp_base_mac_addr_set(). Use a new API: call esp_iface_mac_addr_set()with the ESP_MAC_BASEargument. Local Versus Universal MAC Addresses ESP32 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 esp_derive_local_mac() is called internally to derive a local MAC address from a universal MAC address. The process is as follows: The U/L bit (bit value 0x2) is set in the first octet of the universal MAC address, creating a local MAC address. If this bit is already set in the supplied universal MAC address (i.e., the supplied "universal" MAC address was in fact already a local MAC address), then the first octet of the local MAC address is XORed with 0x4. Chip Version esp_chip_info() function fills esp_chip_info_t structure with information about the chip. This includes the chip revision, number of CPU cores, and a bit mask of features enabled in the chip. SDK Version 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. ESP_IDF_VERSION_MAJOR, ESP_IDF_VERSION_MINOR, ESP_IDF_VERSION_PATCHare defined to integers representing major, minor, and patch version.
ESP_IDF_VERSION_VAL(4, 0, 0) // enable functionality present in ESP-IDF v4.0 #endif App Version The application version is stored in 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 esp_image_header_t and esp_image_segment_header_t structures. 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.
Application can make use of this by calling esp_app_get_description() or esp_ota_get_partition_description() functions. API Reference Header File This header file can be included with: #include "esp_system.h" Functions - esp_err_t esp_register_shutdown_handler(shutdown_handler_t handle) Register shutdown handler. This function allows you to register a handler that gets invoked before the application is restarted using esp_restart function. - Parameters handle -- function to execute on restart - Returns ESP_OK on success ESP_ERR_INVALID_STATE if the handler has already been registered ESP_ERR_NO_MEM if no more shutdown handler slots are available - - esp_err_t esp_unregister_shutdown_handler(shutdown_handler_t handle) Unregister shutdown handler. This function allows you to unregister a handler which was previously registered using esp_register_shutdown_handler function. ESP_OK on success ESP_ERR_INVALID_STATE if the given handler hasn't been registered before - - void esp_restart(void) Restart PRO and APP CPUs. This function can be called both from PRO and APP CPUs. After successful restart, CPU reset reason will be SW_CPU_RESET.
Get reason of last reset. - Returns See description of esp_reset_reason_t for explanation of each value. - uint32_t esp_get_free_heap_size(void) Get the size of available heap. Note Note that the returned value may be larger than the maximum contiguous block which can be allocated. - Returns Available heap size, in bytes. - uint32_t esp_get_free_internal_heap_size(void) Get the size of available internal heap. Note Note that the returned value may be larger than the maximum contiguous block which can be allocated. - Returns Available internal heap size, in bytes. - uint32_t esp_get_minimum_free_heap_size(void) Get the minimum heap that has ever been available. - Returns Minimum free heap ever available - void esp_system_abort(const char *details) Trigger a software abort. - Parameters details -- Details that will be displayed during panic handling.
local_mac, const uint8_t *universal_mac) Derive local MAC address from universal MAC address. This function copies a universal MAC address and then sets the "locally administered" bit (bit 0x2) in the first octet, creating a locally administered MAC address. If the universal MAC address argument is already a locally administered MAC address, then the first octet is XORed with 0x4 in order to create a different locally administered MAC address. - Parameters local_mac -- base MAC address, length: 6 bytes. length: 6 bytes for MAC-48 universal_mac -- Source universal MAC address, length: 6 bytes. - - Returns ESP_OK on success - esp_err_t esp_iface_mac_addr_set(const uint8_t *mac, esp_mac_type_t type) Set custom MAC address of the interface. This function allows you to overwrite the MAC addresses of the interfaces set by the base MAC address. - Parameters mac -- MAC address, length: 6 bytes/8 bytes. length: 6 bytes for MAC-48 8 bytes for EUI-64(used for ESP_MAC_IEEE802154 type, if CONFIG_SOC_IEEE802154_SUPPORTED=y) type -- Type of MAC address - - Returns ESP_OK on success - size_t esp_mac_addr_len_get(esp_mac_type_t type) Return the size of the MAC type in bytes. If CONFIG_SOC_IEEE802154_SUPPORTED is set then for these types: ESP_MAC_IEEE802154 is 8 bytes. ESP_MAC_BASE, ESP_MAC_EFUSE_FACTORY and ESP_MAC_EFUSE_CUSTOM the MAC size is 6 bytes. ESP_MAC_EFUSE_EXT is 2 bytes. If CONFIG_SOC_IEEE802154_SUPPORTED is not set then for all types it returns 6 bytes. - Parameters type -- Type of MAC address - Returns 0 MAC type not found (not supported) 6 bytes for MAC-48. 8 bytes for EUI-64. - Macros - MAC2STR(a) - MACSTR Enumerations - enum esp_mac_type_t Values: - enumerator ESP_MAC_WIFI_STA MAC for WiFi Station (6 bytes) - enumerator ESP_MAC_WIFI_SOFTAP MAC for WiFi Soft-AP (6 bytes) - enumerator ESP_MAC_BT MAC for Bluetooth (6 bytes) - enumerator ESP_MAC_ETH MAC for Ethernet (6 bytes) - enumerator ESP_MAC_IEEE802154 if CONFIG_SOC_IEEE802154_SUPPORTED=y, MAC for IEEE802154 (8 bytes) - enumerator ESP_MAC_BASE Base MAC for that used for other MAC types (6 bytes) - enumerator ESP_MAC_EFUSE_FACTORY MAC_FACTORY eFuse which was burned by Espressif in production (6 bytes) - enumerator ESP_MAC_EFUSE_CUSTOM MAC_CUSTOM eFuse which was can be burned by customer (6 bytes) - enumerator ESP_MAC_EFUSE_EXT if CONFIG_SOC_IEEE802154_SUPPORTED=y, MAC_EXT eFuse which is used as an extender for IEEE802154 MAC (2 bytes) - enumerator ESP_MAC_WIFI_STA Header File This header file can be included with: #include "esp_chip_info.h" Functions - void esp_chip_info(esp_chip_info_t *out_info) Fill an esp_chip_info_t structure with information about the chip. - Parameters out_info --
The structure represents information about the chip. Public Members - esp_chip_model_t model chip model, one of esp_chip_model_t - uint32_t features bit mask of CHIP_FEATURE_x feature flags - uint16_t revision chip revision number (in format MXX; where M - wafer major version, XX - wafer minor version) - uint8_t cores number of CPU cores - esp_chip_model_t model Macros - CHIP_FEATURE_EMB_FLASH Chip has embedded flash memory. - CHIP_FEATURE_WIFI_BGN Chip has 2.4GHz WiFi. - CHIP_FEATURE_BLE Chip has Bluetooth LE. - CHIP_FEATURE_BT Chip has Bluetooth Classic. - CHIP_FEATURE_IEEE802154 Chip has IEEE 802.15.4. - CHIP_FEATURE_EMB_PSRAM Chip has embedded psram. Enumerations - enum esp_chip_model_t Chip models. Values: - enumerator CHIP_ESP32 ESP32. - enumerator CHIP_ESP32S2 ESP32-S2. - enumerator CHIP_ESP32S3 ESP32-S3. - enumerator CHIP_ESP32C3 ESP32-C3. - enumerator CHIP_ESP32C2 ESP32-C2. - enumerator CHIP_ESP32C6 ESP32-C6. - enumerator CHIP_ESP32H2 ESP32-H2. - enumerator CHIP_ESP32P4 ESP32-P4. - enumerator CHIP_POSIX_LINUX The code is running on POSIX/Linux simulator. - enumerator CHIP_ESP32 Header File This header file can be included with: #include "esp_cpu.h" Functions - void esp_cpu_stall(int core_id) Stall a CPU core. - Parameters core_id -- The core's ID - void esp_cpu_unstall(int core_id) Resume a previously stalled CPU core. - Parameters core_id -- The core's ID - void esp_cpu_reset(int core_id) Reset a CPU core. - Parameters core_id -- The core's ID - void esp_cpu_wait_for_intr(void)
This function causes the current CPU core to execute its Wait For Interrupt (WFI or equivalent) instruction. After executing this function, the CPU core will stop execution until an interrupt occurs. - int esp_cpu_get_core_id(void) Get the current core's ID. This function will return the ID of the current CPU (i.e., the CPU that calls this function). - Returns The current core's ID [0..SOC_CPU_CORES_NUM - 1] - void *esp_cpu_get_sp(void) Read the current stack pointer address. - Returns Stack pointer address - esp_cpu_cycle_count_t esp_cpu_get_cycle_count(void) Get the current CPU core's cycle count. Each CPU core maintains an internal counter (i.e., cycle count) that increments every CPU clock cycle. - Returns Current CPU's cycle count, 0 if not supported. - void esp_cpu_set_cycle_count(esp_cpu_cycle_count_t cycle_count) Set the current CPU core's cycle count. Set the given value into the internal counter that increments every CPU clock cycle. - Parameters cycle_count -- CPU cycle count - void *esp_cpu_pc_to_addr(uint32_t pc) Convert a program counter (PC) value to address. If the architecture does not store the true virtual address in the CPU's PC or return addresses, this function will convert the PC value to a virtual address. Otherwise, the PC is just returned - Parameters pc -- PC value - Returns Virtual address - void esp_cpu_intr_get_desc(int core_id, int intr_num, esp_cpu_intr_desc_t *intr_desc_ret) Get a CPU interrupt's descriptor. Each CPU interrupt has a descriptor describing the interrupt's capabilities and restrictions. This function gets the descriptor of a particular interrupt on a particular CPU.
[in] The core's ID intr_num -- [in] Interrupt number intr_desc_ret -- [out] The interrupt's descriptor - - void esp_cpu_intr_set_ivt_addr(const void *ivt_addr) Set the base address of the current CPU's Interrupt Vector Table (IVT) - Parameters ivt_addr -- Interrupt Vector Table's base address - bool esp_cpu_intr_has_handler(int intr_num) Check if a particular interrupt already has a handler function. Check if a particular interrupt on the current CPU already has a handler function assigned. Note This function simply checks if the IVT of the current CPU already has a handler assigned. - Parameters intr_num -- Interrupt number (from 0 to 31) - Returns True if the interrupt has a handler function, false otherwise. - void esp_cpu_intr_set_handler(int intr_num, esp_cpu_intr_handler_t handler, void *handler_arg) Set the handler function of a particular interrupt. Assign a handler function (i.e., ISR) to a particular interrupt on the current CPU. Note This function simply sets the handler function (in the IVT) and does not actually enable the interrupt. - Parameters intr_num -- Interrupt number (from 0 to 31) handler -- Handler function handler_arg --
The the argument passed to the handler function - void esp_cpu_intr_enable(uint32_t intr_mask) Enable particular interrupts on the current CPU. - Parameters intr_mask -- Bit mask of the interrupts to enable - void esp_cpu_intr_disable(uint32_t intr_mask) Disable particular interrupts on the current CPU. - Parameters intr_mask -- Bit mask of the interrupts to disable - uint32_t esp_cpu_intr_get_enabled_mask(void) Get the enabled interrupts on the current CPU. - Returns Bit mask of the enabled interrupts - void esp_cpu_intr_edge_ack(int intr_num) Acknowledge an edge interrupt. - Parameters intr_num -- Interrupt number (from 0 to 31) - void esp_cpu_configure_region_protection(void) Configure the CPU to disable access to invalid memory regions. - esp_err_t esp_cpu_set_breakpoint(int bp_num, const void *bp_addr) Set and enable a hardware breakpoint on the current CPU. Note This function is meant to be called by the panic handler to set a breakpoint for an attached debugger during a panic. Note Overwrites previously set breakpoint with same breakpoint number. - Parameters bp_num -- Hardware breakpoint number [0..SOC_CPU_BREAKPOINTS_NUM - 1] bp_addr -- Address to set a breakpoint on - - Returns ESP_OK if breakpoint is set.
Clear a hardware breakpoint on the current CPU. Note Clears a breakpoint regardless of whether it was previously set - Parameters bp_num -- Hardware breakpoint number [0..SOC_CPU_BREAKPOINTS_NUM - 1] - Returns ESP_OK if breakpoint is cleared. Failure otherwise - esp_err_t esp_cpu_set_watchpoint(int wp_num, const void *wp_addr, size_t size, esp_cpu_watchpoint_trigger_t trigger) Set and enable a hardware watchpoint on the current CPU. Set and enable a hardware watchpoint on the current CPU, specifying the memory range and trigger operation. Watchpoints will break/panic the CPU when the CPU accesses (according to the trigger type) on a certain memory range. Note Overwrites previously set watchpoint with same watchpoint number. On RISC-V chips, this API uses method0(Exact matching) and method1(NAPOT matching) according to the riscv-debug-spec-0.13 specification for address matching. If the watch region size is 1byte, it uses exact matching (method 0). If the watch region size is larger than 1byte, it uses NAPOT matching (method 1). This mode requires the watching region start address to be aligned to the watching region size. - Parameters wp_num -- Hardware watchpoint number [0..SOC_CPU_WATCHPOINTS_NUM - 1] wp_addr -- Watchpoint's base address, must be naturally aligned to the size of the region size -- Size of the region to watch. Must be one of 2^n and in the range of [1 ... SOC_CPU_WATCHPOINT_MAX_REGION_SIZE] trigger -- Trigger type - - Returns ESP_ERR_INVALID_ARG on invalid arg, ESP_OK otherwise - esp_err_t esp_cpu_clear_watchpoint(int wp_num) Clear a hardware watchpoint on the current CPU. Note Clears a watchpoint regardless of whether it was previously set - Parameters wp_num -- Hardware watchpoint number [0..SOC_CPU_WATCHPOINTS_NUM - 1] - Returns ESP_OK if watchpoint was cleared. Failure otherwise. - bool esp_cpu_dbgr_is_attached(void) Check if the current CPU has a debugger attached. - Returns True if debugger is attached, false otherwise - void esp_cpu_dbgr_break(void) Trigger a call to the current CPU's attached debugger. - intptr_t
Given the return address, calculate the address of the preceding call instruction This is typically used to answer the question "where was the function called from?". - Parameters return_address -- The value of the return address register. Typically set to the value of __builtin_return_address(0). - Returns Address of the call instruction preceding the return address. - bool esp_cpu_compare_and_set(volatile uint32_t *addr, uint32_t compare_value, uint32_t new_value) Atomic compare-and-set operation. - Parameters addr -- Address of atomic variable compare_value -- Value to compare the atomic variable to new_value -- New value to set the atomic variable to - - Returns Whether the atomic variable was set or not Structures - struct esp_cpu_intr_desc_t CPU interrupt descriptor. Each particular CPU interrupt has an associated descriptor describing that particular interrupt's characteristics. Call esp_cpu_intr_get_desc() to get the descriptors of a particular interrupt. Public Members - int priority Priority of the interrupt if it has a fixed priority, (-1) if the priority is configurable. - esp_cpu_intr_type_t type Whether the interrupt is an edge or level type interrupt, ESP_CPU_INTR_TYPE_NA if the type is configurable. - uint32_t flags Flags indicating extra details. - int priority Macros - ESP_CPU_INTR_DESC_FLAG_SPECIAL Interrupt descriptor flags of esp_cpu_intr_desc_t. The interrupt is a special interrupt (e.g., a CPU timer interrupt) - ESP_CPU_INTR_DESC_FLAG_RESVD The interrupt is reserved for internal use Type Definitions - typedef uint32_t esp_cpu_cycle_count_t CPU cycle count type. This data type represents the CPU's clock cycle count - typedef void
This structure includes app version. Return description for running app. - Returns Pointer to esp_app_desc structure. - int esp_app_get_elf_sha256(char *dst, size_t size) Fill the provided buffer with SHA256 of the ELF file, formatted as hexadecimal, null-terminated. If the buffer size is not sufficient to fit the entire SHA256 in hex plus a null terminator, the largest possible number of bytes will be written followed by a null. - Parameters dst -- Destination buffer size -- Size of the buffer - - Returns Number of bytes written to dst (including null terminator) - char *esp_app_get_elf_sha256_str(void) Return SHA256 of the ELF file which is already formatted as hexadecimal, null-terminated included. Can be used in panic handler or core dump during when cache is disabled. The length is defined by CONFIG_APP_RETRIEVE_LEN_ELF_SHA option. - Returns Hexadecimal SHA256 string Structures - struct esp_app_desc_t Description about application. Public Members - uint32_t magic_word Magic word ESP_APP_DESC_MAGIC_WORD - uint32_t secure_version Secure version - uint32_t reserv1[2] reserv1 - char version[32] Application version - char project_name[32] Project name - char time[16] Compile time - char date[16] Compile date - char idf_ver[32] Version IDF - uint8_t app_elf_sha256[32] sha256 of elf file - uint32_t reserv2[20] reserv2 - uint32_t magic_word Macros - ESP_APP_DESC_MAGIC_WORD The magic word for the esp_app_desc structure that is in DROM.
Over The Air Updates (OTA) OTA Process Overview The OTA update mechanism allows a device to update itself based on data received while the normal firmware is running (for example, over Wi-Fi or Bluetooth.) OTA requires configuring the Partition Tables of the device with at least two OTA app slot partitions (i.e., ota_0 and ota_1) and an OTA Data Partition. The OTA operation functions write a new app firmware image to whichever OTA app slot that is currently not selected for booting. Once the image is verified, the OTA Data partition is updated to specify that this image should be used for the next boot. OTA Data Partition An OTA data partition (type data, subtype ota) must be included in the Partition Tables of any project which uses the OTA functions. For factory boot settings, the OTA data partition should contain no data (all bytes erased to 0xFF). In this case, the ESP-IDF software bootloader will boot the factory app if it is present in the partition table. If no factory app is included in the partition table, the first available OTA slot (usually ota_0) is booted. After the first OTA update, the OTA data partition is updated to specify which OTA app slot partition should be booted next. The OTA data partition is two flash sectors (0x2000 bytes) in size, to prevent problems if there is a power failure while it is being written. Sectors are independently erased and written with matching data, and if they disagree a counter field is used to determine which sector was written more recently. App Rollback The main purpose of the application rollback is to keep the device working after the update. This feature allows you to roll back to the previous working application in case a new application has critical errors. When the rollback process is enabled and an OTA update provides a new version of the app, one of three things can happen: The application works fine, esp_ota_mark_app_valid_cancel_rollback()marks the running application with the state ESP_OTA_IMG_VALID. There are no restrictions on booting this application. The application has critical errors and further work is not possible, a rollback to the previous application is required, esp_ota_mark_app_invalid_rollback_and_reboot()marks the running application with the state ESP_OTA_IMG_INVALIDand reset. This application will not be selected by the bootloader for boot and will boot the previously working application. If the CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE option is set, and a reset occurs without calling either function then the application is rolled back. Note The state is not written to the binary image of the application but rather to the otadata partition. The partition contains a ota_seq counter, which is a pointer to the slot ( ota_0, ota_1, ...) from which the application will be selected for boot. App OTA State States control the process of selecting a boot app: | States | Restriction of selecting a boot app in bootloader | ESP_OTA_IMG_VALID | None restriction.
Will be selected. | ESP_OTA_IMG_INVALID | Will not be selected. | ESP_OTA_IMG_ABORTED | Will not be selected. | ESP_OTA_IMG_NEW | If CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE option is set it will be selected only once. In bootloader the state immediately changes to | ESP_OTA_IMG_PENDING_VERIFY | If CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE option is set it will not be selected, and the state will change to If CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE option is not enabled (by default), then the use of the following functions esp_ota_mark_app_valid_cancel_rollback() and esp_ota_mark_app_invalid_rollback_and_reboot() are optional, and ESP_OTA_IMG_NEW and ESP_OTA_IMG_PENDING_VERIFY states are not used. An option in Kconfig CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE allows you to track the first boot of a new application. In this case, the application must confirm its operability by calling esp_ota_mark_app_valid_cancel_rollback() function, otherwise the application will be rolled back upon reboot. It allows you to control the operability of the application during the boot phase. Thus, a new application has only one attempt to boot successfully. Rollback Process The description of the rollback process when CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE option is enabled: The new application is successfully downloaded and esp_ota_set_boot_partition()function makes this partition bootable and sets the state ESP_OTA_IMG_NEW. This state means that the application is new and should be monitored for its first boot.
The bootloader checks for the ESP_OTA_IMG_PENDING_VERIFYstate if it is set, then it will be written to ESP_OTA_IMG_ABORTED. The bootloader selects a new application to boot so that the state is not set as ESP_OTA_IMG_INVALIDor ESP_OTA_IMG_ABORTED. The bootloader checks the selected application for ESP_OTA_IMG_NEWstate if it is set, then it will be written to ESP_OTA_IMG_PENDING_VERIFY. This state means that the application requires confirmation of its operability, if this does not happen and a reboot occurs, this state will be overwritten to ESP_OTA_IMG_ABORTED(see above) and this application will no longer be able to start, i.e., there will be a rollback to the previous working application. A new application has started and should make a self-test. If the self-test has completed successfully, then you must call the function esp_ota_mark_app_valid_cancel_rollback()because the application is awaiting confirmation of operability ( ESP_OTA_IMG_PENDING_VERIFYstate). If the self-test fails, then call esp_ota_mark_app_invalid_rollback_and_reboot()function to roll back to the previous working application, while the invalid application is set ESP_OTA_IMG_INVALIDstate. If the application has not been confirmed, the state remains ESP_OTA_IMG_PENDING_VERIFY, and the next boot it will be changed to ESP_OTA_IMG_ABORTED, which prevents re-boot of this application. There will be a rollback to the previous working application. Unexpected Reset If a power loss or an unexpected crash occurs at the time of the first boot of a new application, it will roll back the application. Recommendation: Perform the self-test procedure as quickly as possible, to prevent rollback due to power loss. Only OTA partitions can be rolled back. Factory partition is not rolled back. Booting Invalid/aborted Apps Booting an application which was previously set to ESP_OTA_IMG_INVALID or ESP_OTA_IMG_ABORTED is possible: Get the last invalid application partition esp_ota_get_last_invalid_partition(). Pass the received partition to esp_ota_set_boot_partition(), this will update the otadata. Restart esp_restart().
The bootloader will boot the specified application. To determine if self-tests should be run during startup of an application, call the esp_ota_get_state_partition() function. If result is ESP_OTA_IMG_PENDING_VERIFY then self-testing and subsequent confirmation of operability is required. Where the States Are Set A brief description of where the states are set: ESP_OTA_IMG_VALIDstate is set by esp_ota_mark_app_valid_cancel_rollback()function. ESP_OTA_IMG_UNDEFINEDstate is set by esp_ota_set_boot_partition()function if CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE option is not enabled. ESP_OTA_IMG_NEWstate is set by esp_ota_set_boot_partition()function if CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE option is enabled. ESP_OTA_IMG_INVALIDstate is set by esp_ota_mark_app_invalid_rollback_and_reboot()function. ESP_OTA_IMG_ABORTEDstate is set if there was no confirmation of the application operability and occurs reboots (if CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE option is enabled). ESP_OTA_IMG_PENDING_VERIFYstate is set in a bootloader if CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE option is enabled and selected app has ESP_OTA_IMG_NEWstate. Anti-rollback Anti-rollback prevents rollback to application with security version lower than one programmed in eFuse of chip. This function works if set CONFIG_BOOTLOADER_APP_ANTI_ROLLBACK option. In the bootloader, when selecting a bootable application, an additional security version check is added which is on the chip and in the application image. The version in the bootable firmware must be greater than or equal to the version in the chip. CONFIG_BOOTLOADER_APP_ANTI_ROLLBACK and CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE options are used together. In this case, rollback is possible only on the security version which is equal or higher than the version in the chip. A Typical Anti-rollback Scheme Is New firmware released with the elimination of vulnerabilities with the previous version of security. After the developer makes sure that this firmware is working. He can increase the security version and release a new firmware. Download new application. To make it bootable, run the function esp_ota_set_boot_partition(). If the security version of the new application is smaller than the version in the chip, the new application will be erased. Update to new firmware is not possible.
Then the application should perform diagnostics of the operation and if it is completed successfully, you should call esp_ota_mark_app_valid_cancel_rollback()function to mark the running application with the ESP_OTA_IMG_VALIDstate and update the secure version on chip. Note that if was called esp_ota_mark_app_invalid_rollback_and_reboot()function a rollback may not happen as the device may not have any bootable apps. It will then return ESP_ERR_OTA_ROLLBACK_FAILEDerror and stay in the ESP_OTA_IMG_PENDING_VERIFYstate. The next update of app is possible if a running app is in the ESP_OTA_IMG_VALIDstate. Recommendation: If you want to avoid the download/erase overhead in case of the app from the server has security version lower than the running app, you have to get new_app_info.secure_version from the first package of an image and compare it with the secure version of efuse. Use esp_efuse_check_secure_version(new_app_info.secure_version) function if it is true then continue downloading otherwise abort.
bool image_header_was_checked = false; while (1) { int data_read = esp_http_client_read(client, ota_write_data, BUFFSIZE); ... if (data_read > 0) { if (image_header_was_checked == false) { esp_app_desc_t new_app_info; if (data_read > sizeof(esp_image_header_t) + sizeof(esp_image_segment_header_t) + sizeof(esp_app_desc_t)) { // check current version with downloading if (esp_efuse_check_secure_version(new_app_info.secure_version) == false) { ESP_LOGE(TAG, "This a new app can not be downloaded due to a secure version is lower than stored in efuse."); http_cleanup(client); task_fatal_error(); } image_header_was_checked = true; esp_ota_begin(update_partition, OTA_SIZE_UNKNOWN, &update_handle); } } esp_ota_write( update_handle, (const void *)ota_write_data, data_read); } } ... Restrictions: The number of bits in the secure_versionfield is limited to 32 bits. This means that only 32 times you can do an anti-rollback. You can reduce the length of this efuse field using CONFIG_BOOTLOADER_APP_SEC_VER_SIZE_EFUSE_FIELD option. Anti-rollback works only if the encoding scheme for efuse is set to NONE. Factory and Test partitions are not supported in anti rollback scheme and hence partition table should not have partition with SubType set to factoryor test.
In application image it is stored in esp_app_descstructure. The number is set CONFIG_BOOTLOADER_APP_SECURE_VERSION. In ESP32 it is stored in efuse EFUSE_BLK3_RDATA4_REG. (when a eFuse bit is programmed to 1, it can never be reverted to 0). The number of bits set in this register is the security_versionfrom app. Secure OTA Updates Without Secure Boot The verification of signed OTA updates can be performed even without enabling hardware secure boot. This can be achieved by setting CONFIG_SECURE_SIGNED_APPS_NO_SECURE_BOOT and CONFIG_SECURE_SIGNED_ON_UPDATE_NO_SECURE_BOOT For more information refer to Signed App Verification Without Hardware Secure Boot OTA Tool otatool.py The component app_update provides a tool app_update/otatool.py for performing OTA partition-related operations on a target device. The following operations can be performed using the tool: - read contents of otadata partition (read_otadata) - erase otadata partition, effectively resetting device to factory app (erase_otadata) - switch OTA partitions (switch_ota_partition) - erasing OTA partition (erase_ota_partition) - write to OTA partition (write_ota_partition) - read contents of OTA partition (read_ota_partition) The tool can either be imported and used from another Python script or invoked from shell script for users wanting to perform operation programmatically. This is facilitated by the tool's Python API and command-line interface, respectively. Python API Before anything else, make sure that the otatool module is imported.
import sys import os idf_path = os.environ["IDF_PATH"] # get value of IDF_PATH from environment otatool_dir = os.path.join(idf_path, "components", "app_update") # otatool.py lives in $IDF_PATH/components/app_update sys.path.append(otatool_dir) # this enables Python to find otatool module from otatool import * # import all names inside otatool module The starting point for using the tool's Python API to do is create a OtatoolTarget object: # Create a partool.py target device connected on serial port /dev/ttyUSB1 target = OtatoolTarget("/dev/ttyUSB1") The created object can now be used to perform operations on the target device: # Erase otadata, reseting the device to factory app target.erase_otadata() # Erase contents of OTA app slot 0 target.erase_ota_partition(0) # Switch boot partition to that of app slot 1 target.switch_ota_partition(1) # Read OTA partition 'ota_3' and save contents to a file named 'ota_3.bin' target.read_ota_partition("ota_3", "ota_3.bin") The OTA partition to operate on is specified using either the app slot number or the partition name. More information on the Python API is available in the docstrings for the tool. Command-line Interface The command-line interface of otatool.py has the following structure: otatool.py [command-args] [subcommand]
[subcommand-args] - command-args - these are arguments that are needed for executing the main command (parttool.py), mostly pertaining to the target device - subcommand - this is the operation to be performed - subcommand-args - these are arguments that are specific to the chosen operation # Erase otadata, resetting the device to factory app otatool.py --port "/dev/ttyUSB1" erase_otadata # Erase contents of OTA app slot 0 otatool.py --port "/dev/ttyUSB1" erase_ota_partition --slot 0 # Switch boot partition to that of app slot 1 otatool.py --port "/dev/ttyUSB1" switch_ota_partition --slot 1 # Read OTA partition 'ota_3' and save contents to a file named 'ota_3.bin' otatool.py --port "/dev/ttyUSB1" read_ota_partition --name=ota_3 --output=ota_3.bin More information can be obtained by specifying --help as argument: # Display possible subcommands and show main command argument descriptions otatool.py --help # Show descriptions for specific subcommand arguments otatool.py [subcommand] --help See Also Application Example End-to-end example of OTA firmware update workflow: system/ota. API Reference Header File This header file can be included with: #include "esp_ota_ops.h" This header file is a part of the API provided by the app_updatecomponent. To declare that your component depends on app_update, add the following to your CMakeLists.txt: REQUIRES app_update or PRIV_REQUIRES
This structure includes app version. Return description for running app. Note This API is present for backward compatibility reasons. Alternative function with the same functionality is esp_app_get_description - Returns Pointer to esp_app_desc structure. - int esp_ota_get_app_elf_sha256(char *dst, size_t size) Fill the provided buffer with SHA256 of the ELF file, formatted as hexadecimal, null-terminated. If the buffer size is not sufficient to fit the entire SHA256 in hex plus a null terminator, the largest possible number of bytes will be written followed by a null. Note This API is present for backward compatibility reasons. Alternative function with the same functionality is esp_app_get_elf_sha256 - Parameters dst -- Destination buffer size -- Size of the buffer - - Returns Number of bytes written to dst (including null terminator) - esp_err_t esp_ota_begin(const esp_partition_t *partition, size_t image_size, esp_ota_handle_t *out_handle) Commence an OTA update writing to the specified partition. The specified partition is erased to the specified image size. If image size is not yet known, pass OTA_SIZE_UNKNOWN which will cause the entire partition to be erased. On success, this function allocates memory that remains in use until esp_ota_end() is called with the returned handle. Note: If the rollback option is enabled and the running application has the ESP_OTA_IMG_PENDING_VERIFY state then it will lead to the ESP_ERR_OTA_ROLLBACK_INVALID_STATE error. Confirm the running app before to run download a new app, use esp_ota_mark_app_valid_cancel_rollback() function for it (this should be done as early as possible when you first download a new application). - Parameters partition -- Pointer to info for partition which will receive the OTA update. Required.
Flash write failed. ESP_ERR_OTA_ROLLBACK_INVALID_STATE: If the running app has not confirmed state. Before performing an update, the application must be valid. - - esp_err_t esp_ota_write(esp_ota_handle_t handle, const void *data, size_t size) Write OTA update data to partition. This function can be called multiple times as data is received during the OTA operation. Data is written sequentially to the partition. - Parameters handle -- Handle obtained from esp_ota_begin data -- Data buffer to write size -- Size of data buffer in bytes. - - Returns ESP_OK: Data was written to flash successfully, or size = 0 ESP_ERR_INVALID_ARG: handle is invalid. ESP_ERR_OTA_VALIDATE_FAILED: First byte of image contains invalid app image magic byte. ESP_ERR_FLASH_OP_TIMEOUT or ESP_ERR_FLASH_OP_FAIL: Flash write failed. ESP_ERR_OTA_SELECT_INFO_INVALID:
OTA data partition has invalid contents - - esp_err_t esp_ota_write_with_offset(esp_ota_handle_t handle, const void *data, size_t size, uint32_t offset) Write OTA update data to partition at an offset. This function can write data in non-contiguous manner. If flash encryption is enabled, data should be 16 bytes aligned. Note While performing OTA, if the packets arrive out of order, esp_ota_write_with_offset() can be used to write data in non-contiguous manner. Use of esp_ota_write_with_offset() in combination with esp_ota_write() is not recommended. - Parameters handle -- Handle obtained from esp_ota_begin data -- Data buffer to write size -- Size of data buffer in bytes offset -- Offset in flash partition - - Returns ESP_OK: Data was written to flash successfully. ESP_ERR_INVALID_ARG: handle is invalid. ESP_ERR_OTA_VALIDATE_FAILED: First byte of image contains invalid app image magic byte. ESP_ERR_FLASH_OP_TIMEOUT or ESP_ERR_FLASH_OP_FAIL: Flash write failed. ESP_ERR_OTA_SELECT_INFO_INVALID:
If flash encryption is enabled, this result indicates an internal error writing the final encrypted bytes to flash. - - esp_err_t esp_ota_abort(esp_ota_handle_t handle) Abort OTA update, free the handle and memory associated with it. - Parameters handle -- obtained from esp_ota_begin(). - Returns ESP_OK: Handle and its associated memory is freed successfully. ESP_ERR_NOT_FOUND: OTA handle was not found. - - esp_err_t esp_ota_set_boot_partition(const esp_partition_t *partition) Configure OTA data for a new boot partition. Note If this function returns ESP_OK, calling esp_restart() will boot the newly configured app partition. - Parameters partition -- Pointer to info for partition containing app image to boot. - Returns ESP_OK: OTA data updated, next reboot will use specified partition. ESP_ERR_INVALID_ARG: partition argument was NULL or didn't point to a valid OTA partition of type "app".
If esp_ota_set_boot_partition() has been called, the partition which was set by that function will be returned. If esp_ota_set_boot_partition() has not been called, the result is usually the same as esp_ota_get_running_partition(). The two results are not equal if the configured boot partition does not contain a valid app (meaning that the running partition will be an app that the bootloader chose via fallback). If the OTA data partition is not present or not valid then the result is the first app partition found in the partition table. In priority order, this means: the factory app, the first OTA app slot, or the test app partition. Note that there is no guarantee the returned partition is a valid app. Use esp_image_verify(ESP_IMAGE_VERIFY, ...) to verify if the returned partition contains a bootable image. - Returns Pointer to info for partition structure, or NULL if partition table is invalid or a flash read operation failed. Any returned pointer is valid for the lifetime of the application. - const esp_partition_t *esp_ota_get_running_partition(void) Get partition info of currently running app. This function is different to esp_ota_get_boot_partition() in that it ignores any change of selected boot partition caused by esp_ota_set_boot_partition(). Only the app whose code is currently running will have its partition information returned. The partition returned by this function may also differ from esp_ota_get_boot_partition() if the configured boot partition is somehow invalid, and the bootloader fell back to a different app partition at boot. - Returns Pointer to info for partition structure, or NULL if no partition is found or flash read operation failed. Returned pointer is valid for the lifetime of the application. - const esp_partition_t *esp_ota_get_next_update_partition(const esp_partition_t *start_from) Return the next OTA app partition which should be written with a new firmware. Call this function to find an OTA app partition which can be passed to esp_ota_begin(). Finds next partition round-robin, starting from the current running partition. - Parameters start_from -- If set, treat this partition info as describing the current running partition. Can be NULL, in which case esp_ota_get_running_partition() is used to find the currently running partition. The result of this function is never the same as this argument. - Returns Pointer to info for partition which should be updated next. NULL result indicates invalid OTA data partition, or that no eligible OTA app slot partition was found. - esp_err_t esp_ota_get_partition_description(const esp_partition_t *partition, esp_app_desc_t *app_desc) Returns esp_app_desc structure for app partition. This structure includes app version. Returns a description for the requested app partition. - Parameters partition --
[out] Structure of info about app. - - Returns ESP_OK Successful. ESP_ERR_NOT_FOUND app_desc structure is not found. Magic word is incorrect. ESP_ERR_NOT_SUPPORTED Partition is not application. ESP_ERR_INVALID_ARG Arguments is NULL or if partition's offset exceeds partition size. ESP_ERR_INVALID_SIZE Read would go out of bounds of the partition. or one of error codes from lower-level flash driver. - - esp_err_t esp_ota_get_bootloader_description(const esp_partition_t *bootloader_partition, esp_bootloader_desc_t *desc) Returns the description structure of the bootloader. -
ESP_ERR_INVALID_SIZE Read would go out of bounds of the partition. or one of error codes from lower-level flash driver. - - uint8_t esp_ota_get_app_partition_count(void) Returns number of ota partitions provided in partition table. - Returns Number of OTA partitions - - esp_err_t esp_ota_mark_app_valid_cancel_rollback(void) This function is called to indicate that the running app is working well. - Returns ESP_OK: if successful. - - esp_err_t esp_ota_mark_app_invalid_rollback_and_reboot(void) This function is called to roll back to the previously workable app with reboot. If rollback is successful then device will reset else API will return with error code. Checks applications on a flash drive that can be booted in case of rollback. If the flash does not have at least one app (except the running app) then rollback is not possible . - Returns ESP_FAIL: if not successful. ESP_ERR_OTA_ROLLBACK_FAILED: The rollback is not possible due to flash does not have any apps. - - const esp_partition_t *esp_ota_get_last_invalid_partition(void) Returns last partition with invalid state (ESP_OTA_IMG_INVALID or ESP_OTA_IMG_ABORTED). - Returns partition. - esp_err_t esp_ota_get_state_partition(const esp_partition_t *partition, esp_ota_img_states_t *ota_state) Returns state for given partition. - Parameters partition -- [in] Pointer to partition. ota_state -- [out] state of partition (if this partition has a record in otadata). - - Returns ESP_OK: Successful. ESP_ERR_INVALID_ARG: partition or ota_state arguments were NULL. ESP_ERR_NOT_SUPPORTED: partition is not ota. ESP_ERR_NOT_FOUND: Partition table does not have otadata or state was not found for given partition. - - esp_err_t esp_ota_erase_last_boot_app_partition(void) Erase previous boot app partition and corresponding otadata select for this partition. When current app is marked to as valid then you can erase previous app partition. - Returns ESP_OK: Successful, otherwise ESP_ERR. - - bool esp_ota_check_rollback_is_possible(void) Checks applications on the slots which can be booted in case of rollback. These applications should be valid (marked in otadata as not UNDEFINED, INVALID or ABORTED and crc is good) and be able booted, and secure_version of app >= secure_version of efuse (if anti-rollback is enabled). - Returns True
: Returns true if the slots have at least one app (except the running app). False: The rollback is not possible. - Macros - OTA_SIZE_UNKNOWN Used for esp_ota_begin() if new image size is unknown - OTA_WITH_SEQUENTIAL_WRITES Used for esp_ota_begin() if new image size is unknown and erase can be done in incremental manner (assuming write operation is in continuous sequence) - ESP_ERR_OTA_BASE Base error code for ota_ops api - ESP_ERR_OTA_PARTITION_CONFLICT Error if request was to write or erase the current running partition - ESP_ERR_OTA_SELECT_INFO_INVALID Error if OTA data partition contains invalid content - ESP_ERR_OTA_VALIDATE_FAILED Error if OTA app image is invalid - ESP_ERR_OTA_SMALL_SEC_VER Error if the firmware has a secure version less than the running firmware. - ESP_ERR_OTA_ROLLBACK_FAILED Error if flash does not have valid firmware in passive partition and hence rollback is not possible - ESP_ERR_OTA_ROLLBACK_INVALID_STATE Error if current active firmware is still marked in pending validation state (ESP_OTA_IMG_PENDING_VERIFY), essentially first boot of firmware image post upgrade and hence firmware upgrade is not possible Type Definitions - typedef uint32_t esp_ota_handle_t Opaque handle for an application OTA update. esp_ota_begin() returns a handle which is then used for subsequent calls to esp_ota_write() and esp_ota_end().
Performance Monitor The Performance Monitor component provides APIs to use ESP32 internal performance counters to profile functions and applications. Application Example An example which combines performance monitor is provided in examples/system/perfmon directory. This example initializes the performance monitor structure and execute them with printing the statistics. High-Level API Reference Header Files API Reference Header File This header file can be included with: #include "xtensa_perfmon_access.h" This header file is a part of the API provided by the perfmoncomponent. To declare that your component depends on perfmon, add the following to your CMakeLists.txt: REQUIRES perfmon or PRIV_REQUIRES perfmon Functions - esp_err_t xtensa_perfmon_init(int id, uint16_t select, uint16_t mask, int kernelcnt, int tracelevel) Init Performance Monitoor. Initialize performance monitor register with define values - Parameters id -- [in] performance counter number select -- [in] select value from PMCTRLx register mask -- [in] mask value from PMCTRLx register kernelcnt -- [in] kernelcnt value from PMCTRLx register tracelevel -- [in] tracelevel value from PMCTRLx register - - Returns ESP_OK on success ESP_ERR_INVALID_ARG if one of the arguments is not correct - - esp_err_t xtensa_perfmon_reset(int id) Reset PM counter. Reset PM counter. Writes 0 to the PMx register.
Stop PM counters. Stop all PM counters synchronously. Write 0 to the PGM register - uint32_t xtensa_perfmon_value(int id) Read PM counter. Read value of defined PM counter. - Parameters id -- [in] performance counter number - Returns Performance counter value - - esp_err_t xtensa_perfmon_overflow(int id) Read PM overflow state. Read overflow value of defined PM counter. - Parameters id -- [in] performance counter number - Returns ESP_OK if there is no overflow (overflow = 0) ESP_FAIL if overflow occure (overflow = 1) - - void xtensa_perfmon_dump(void) Dump PM values.
[in] used parameters passed from configuration (callback_params). This parameter expected as FILE* hanle, where data will be stored. If this parameter NULL, then data will be stored to the stdout. select -- [in] select value for current counter mask -- [in] mask value for current counter value -- [in] counter value for current counter - Structures - struct xtensa_perfmon_config Performance monitor configuration structure. Structure to configure performance counter to measure dedicated function Public Members - int repeat_count how much times function will be called before the calback will be repeated - float max_deviation Difference between min and max counter number 0..1, 0 - no difference, 1 - not used - void *call_params This pointer will be passed to the call_function as a parameter - void (*call_function)(void *params) pointer to the function that have to be called - void (*callback)(void *params, uint32_t select, uint32_t mask, uint32_t value) pointer to the function that will be called with result parameters - void *callback_params parameter that will be passed to the callback - int tracelevel trace level for all counters. In case of negative value, the filter will be ignored. If it's >=0, then the perfmon will count only when interrupt level > tracelevel. It's useful to monitor interrupts. - uint32_t counters_size amount of counter in the list - const uint32_t *select_mask list of the select/mask parameters - int repeat_count Type Definitions - typedef struct xtensa_perfmon_config xtensa_perfmon_config_t Performance monitor configuration structure. Structure to configure performance counter to measure dedicated function