Merge branch 'feature/systemview_4_uart' into 'master'

Add support for UART to the app trace module.

See merge request espressif/esp-idf!15266
This commit is contained in:
Dmitry Yakovlev 2022-03-24 16:42:02 +08:00
commit 8075f44178
13 changed files with 699 additions and 88 deletions

View File

@ -21,6 +21,8 @@ if(CONFIG_APPTRACE_MEMBUFS_APPTRACE_PROTO_ENABLE)
"port/riscv/port.c")
endif()
endif()
list(APPEND srcs
"port/port_uart.c")
if(CONFIG_APPTRACE_SV_ENABLE)
list(APPEND include_dirs
@ -58,3 +60,16 @@ target_compile_options(${COMPONENT_LIB} PRIVATE "-fno-profile-arcs" "-fno-test-c
# Force app_trace to also appear later than gcov in link line
idf_component_get_property(app_trace app_trace COMPONENT_LIB)
target_link_libraries(${COMPONENT_LIB} INTERFACE $<TARGET_FILE:${app_trace}> gcov $<TARGET_FILE:${app_trace}> c)
# This function adds a dependency on the given component if the component is included into the build.
function(maybe_add_component component_name)
idf_build_get_property(components BUILD_COMPONENTS)
if(${component_name} IN_LIST components)
idf_component_get_property(lib_name ${component_name} COMPONENT_LIB)
target_link_libraries(${COMPONENT_LIB} PUBLIC ${lib_name})
endif()
endfunction()
if(CONFIG_APPTRACE_DEST_UART0 OR CONFIG_APPTRACE_DEST_UART1 OR CONFIG_APPTRACE_DEST_UART2)
maybe_add_component(driver)
endif()

View File

@ -1,7 +1,7 @@
menu "Application Level Tracing"
choice APPTRACE_DESTINATION
prompt "Data Destination"
choice APPTRACE_DESTINATION1
prompt "Data Destination 1"
default APPTRACE_DEST_NONE
help
Select destination for application trace: JTAG or none (to disable).
@ -16,6 +16,124 @@ menu "Application Level Tracing"
bool "None"
endchoice
config APPTRACE_DEST_UART
bool
config APPTRACE_DEST_UART_NOUSB
bool
choice APPTRACE_DESTINATION2
prompt "Data Destination 2"
default APPTRACE_DEST_UART_NONE
help
Select destination for application trace: UART(XX) or none (to disable).
config APPTRACE_DEST_UART0
bool "UART0"
select APPTRACE_ENABLE
select APPTRACE_DEST_UART
select APPTRACE_DEST_UART_NOUSB
depends on (ESP_CONSOLE_UART_NUM !=0)
config APPTRACE_DEST_UART1
bool "UART1"
select APPTRACE_ENABLE
select APPTRACE_DEST_UART
select APPTRACE_DEST_UART_NOUSB
depends on (ESP_CONSOLE_UART_NUM !=1)
config APPTRACE_DEST_UART2
bool "UART2"
select APPTRACE_ENABLE
select APPTRACE_DEST_UART
select APPTRACE_DEST_UART_NOUSB
depends on (ESP_CONSOLE_UART_NUM !=2) && !IDF_TARGET_ESP32C3 && !IDF_TARGET_ESP32S2 && !IDF_TARGET_ESP32H2
config APPTRACE_DEST_USB_CDC
bool "USB_CDC"
select APPTRACE_ENABLE
select APPTRACE_DEST_UART
depends on !ESP_CONSOLE_USB_CDC && (IDF_TARGET_ESP32C3 || IDF_TARGET_ESP32S3) && !USB_ENABLED
config APPTRACE_DEST_UART_NONE
bool "None"
endchoice
config APPTRACE_UART_TX_GPIO
int "UART TX on GPIO#"
depends on APPTRACE_DEST_UART_NOUSB
range 0 46
default 12 if IDF_TARGET_ESP32
default 12 if IDF_TARGET_ESP32C3
default 12
help
This GPIO is used for UART TX pin.
config APPTRACE_UART_RX_GPIO
int "UART RX on GPIO#"
depends on APPTRACE_DEST_UART_NOUSB
range 0 46
default 13 if IDF_TARGET_ESP32
default 13 if IDF_TARGET_ESP32C3
default 13
help
This GPIO is used for UART RX pin.
config APPTRACE_UART_BAUDRATE
int
prompt "UART baud rate" if APPTRACE_DEST_UART
depends on APPTRACE_DEST_UART
default 1000000
range 1200 8000000
range 1200 1000000
help
This baud rate is used for UART.
The app's maximum baud rate depends on the UART clock source. If Power Management is disabled,
the UART clock source is the APB clock and all baud rates in the available range will be sufficiently
accurate. If Power Management is enabled, REF_TICK clock source is used so the baud rate is divided
from 1MHz. Baud rates above 1Mbps are not possible and values between 500Kbps and 1Mbps may not be
accurate.
config APPTRACE_UART_RX_BUFF_SIZE
int
prompt "UART RX ring buffer size" if APPTRACE_DEST_UART
depends on APPTRACE_DEST_UART
default 128
range 64 32768
help
Size of the UART input ring buffer.
This size related to the baudrate, system tick frequency and amount of data to transfer.
The data placed to this buffer before sent out to the interface.
config APPTRACE_UART_TX_BUFF_SIZE
int
prompt "UART TX ring buffer size" if APPTRACE_DEST_UART
depends on APPTRACE_DEST_UART
default 4096
range 2048 32768
help
Size of the UART output ring buffer.
This size related to the baudrate, system tick frequency and amount of data to transfer.
config APPTRACE_UART_TX_MSG_SIZE
int
prompt "UART TX message size" if APPTRACE_DEST_UART
depends on APPTRACE_DEST_UART
default 128
range 64 32768
help
Maximum size of the single message to transfer.
config APPTRACE_UART_TASK_PRIO
int
prompt "UART Task Priority" if APPTRACE_DEST_UART
default 1
range 1 32
help
UART task priority. In case of high events rate,
this parameter could be changed up to (configMAX_PRIORITIES-1).
config APPTRACE_DEST_TRAX
bool
depends on IDF_TARGET_ARCH_XTENSA && !ESP32_TRAX && !ESP32S2_TRAX && !ESP32S3_TRAX
@ -90,6 +208,47 @@ menu "Application Level Tracing"
help
Enables supporrt for SEGGER SystemView tracing functionality.
choice APPTRACE_SV_DEST
prompt "SystemView destination"
depends on APPTRACE_SV_ENABLE
default APPTRACE_SV_DEST_JTAG
help
SystemView witt transfer data trough defined interface.
config APPTRACE_SV_DEST_JTAG
bool "Data destination JTAG"
depends on !PM_ENABLE && !APPTRACE_DEST_NONE
help
Send SEGGER SystemView events through JTAG interface.
config APPTRACE_SV_DEST_UART
bool "Data destination UART"
depends on APPTRACE_DEST_UART
help
Send SEGGER SystemView events through UART interface.
endchoice
choice APPTRACE_SV_CPU
prompt "CPU to trace"
depends on APPTRACE_SV_DEST_UART && !FREERTOS_UNICORE
default APPTRACE_SV_DEST_CPU_0
help
Define the CPU to trace by SystemView.
config APPTRACE_SV_DEST_CPU_0
bool "CPU0"
help
Send SEGGER SystemView events for Pro CPU.
config APPTRACE_SV_DEST_CPU_1
bool "CPU1"
help
Send SEGGER SystemView events for App CPU.
endchoice
choice APPTRACE_SV_TS_SOURCE
prompt "Timer to use as timestamp source"
depends on APPTRACE_SV_ENABLE

View File

@ -9,20 +9,32 @@
#include "esp_app_trace.h"
#include "esp_app_trace_port.h"
#define ESP_APPTRACE_MAX_VPRINTF_ARGS 256
#define ESP_APPTRACE_HOST_BUF_SIZE 256
#ifdef CONFIG_APPTRACE_DEST_UART0
#define ESP_APPTRACE_DEST_UART_NUM 0
#elif CONFIG_APPTRACE_DEST_UART1
#define ESP_APPTRACE_DEST_UART_NUM 1
#elif CONFIG_APPTRACE_DEST_UART2
#define ESP_APPTRACE_DEST_UART_NUM 2
#elif CONFIG_APPTRACE_DEST_USB_CDC
#define ESP_APPTRACE_DEST_UART_NUM 10
#else
#define ESP_APPTRACE_DEST_UART_NUM 0
#endif
#define ESP_APPTRACE_PRINT_LOCK 0
#define ESP_APPTRACE_MAX_VPRINTF_ARGS 256
#define ESP_APPTRACE_HOST_BUF_SIZE 256
#define ESP_APPTRACE_PRINT_LOCK 0
const static char *TAG = "esp_apptrace";
/** tracing module internal data */
typedef struct {
esp_apptrace_hw_t * hw;
void * hw_data;
esp_apptrace_hw_t *hw;
void *hw_data;
} esp_apptrace_channel_t;
static esp_apptrace_channel_t s_trace_channels[ESP_APPTRACE_DEST_NUM];
static esp_apptrace_channel_t s_trace_channels[ESP_APPTRACE_DEST_MAX];
static bool s_inited;
esp_err_t esp_apptrace_init(void)
@ -40,16 +52,16 @@ esp_err_t esp_apptrace_init(void)
s_trace_channels[ESP_APPTRACE_DEST_JTAG].hw = hw;
s_trace_channels[ESP_APPTRACE_DEST_JTAG].hw_data = hw_data;
}
hw = esp_apptrace_uart_hw_get(0, &hw_data);
hw = esp_apptrace_uart_hw_get(ESP_APPTRACE_DEST_UART_NUM, &hw_data);
if (hw != NULL) {
s_trace_channels[ESP_APPTRACE_DEST_UART0].hw = hw;
s_trace_channels[ESP_APPTRACE_DEST_UART0].hw_data = hw_data;
s_trace_channels[ESP_APPTRACE_DEST_UART].hw = hw;
s_trace_channels[ESP_APPTRACE_DEST_UART].hw_data = hw_data;
}
s_inited = true;
}
// esp_apptrace_init() is called on every core, so initialize trace channel on every core
for (int i = 0; i < sizeof(s_trace_channels)/sizeof(s_trace_channels[0]); i++) {
for (int i = 0; i < sizeof(s_trace_channels) / sizeof(s_trace_channels[0]); i++) {
esp_apptrace_channel_t *ch = &s_trace_channels[i];
if (ch->hw) {
res = ch->hw->init(ch->hw_data);
@ -73,15 +85,21 @@ void esp_apptrace_down_buffer_config(uint8_t *buf, uint32_t size)
// currently down buffer is supported for JTAG interface only
// TODO: one more argument should be added to this function to specify HW inteface: JTAG, UART0 etc
ch = &s_trace_channels[ESP_APPTRACE_DEST_JTAG];
if (ch->hw == NULL) {
ESP_APPTRACE_LOGE("Trace destination not supported!");
return;
if (ch->hw != NULL) {
if (ch->hw->down_buffer_config != NULL) {
ch->hw->down_buffer_config(ch->hw_data, buf, size);
}
} else {
ESP_APPTRACE_LOGD("Trace destination for JTAG not supported!");
}
if (ch->hw->down_buffer_config == NULL) {
return;
ch = &s_trace_channels[ESP_APPTRACE_DEST_UART];
if (ch->hw != NULL) {
if (ch->hw->down_buffer_config != NULL) {
ch->hw->down_buffer_config(ch->hw_data, buf, size);
}
} else {
ESP_APPTRACE_LOGD("Trace destination for UART not supported!");
}
ch->hw->down_buffer_config(ch->hw_data, buf, size);
}
uint8_t *esp_apptrace_down_buffer_get(esp_apptrace_dest_t dest, uint32_t *size, uint32_t user_tmo)
@ -169,7 +187,7 @@ esp_err_t esp_apptrace_read(esp_apptrace_dest_t dest, void *buf, uint32_t *size,
esp_apptrace_tmo_init(&tmo, user_tmo);
uint32_t act_sz = *size;
*size = 0;
uint8_t * ptr = ch->hw->get_down_buffer(ch->hw_data, &act_sz, &tmo);
uint8_t *ptr = ch->hw->get_down_buffer(ch->hw_data, &act_sz, &tmo);
if (ptr && act_sz > 0) {
ESP_APPTRACE_LOGD("Read %d bytes from host", act_sz);
memcpy(buf, ptr, act_sz);
@ -419,3 +437,10 @@ bool esp_apptrace_host_is_connected(esp_apptrace_dest_t dest)
return ch->hw->host_is_connected(ch->hw_data);
}
#if !CONFIG_APPTRACE_DEST_JTAG
esp_apptrace_hw_t *esp_apptrace_jtag_hw_get(void **data)
{
return NULL;
}
#endif

View File

@ -20,8 +20,8 @@ extern "C" {
typedef enum {
ESP_APPTRACE_DEST_JTAG = 1, ///< JTAG destination
ESP_APPTRACE_DEST_TRAX = ESP_APPTRACE_DEST_JTAG, ///< xxx_TRAX name is obsolete, use more common xxx_JTAG
ESP_APPTRACE_DEST_UART0, ///< UART0 destination
ESP_APPTRACE_DEST_MAX = ESP_APPTRACE_DEST_UART0,
ESP_APPTRACE_DEST_UART, ///< UART destination
ESP_APPTRACE_DEST_MAX = ESP_APPTRACE_DEST_UART+1,
ESP_APPTRACE_DEST_NUM
} esp_apptrace_dest_t;
@ -36,7 +36,7 @@ esp_err_t esp_apptrace_init(void);
/**
* @brief Configures down buffer.
* @note Needs to be called before initiating any data transfer using esp_apptrace_buffer_get and esp_apptrace_write.
* @note Needs to be called before attempting to receive any data using esp_apptrace_down_buffer_get and esp_apptrace_read.
* This function does not protect internal data by lock.
*
* @param buf Address of buffer to use for down channel (host to target) data.

View File

@ -2,6 +2,7 @@
archive: libapp_trace.a
entries:
app_trace (noflash)
port_uart (noflash)
app_trace_util (noflash)
if APPTRACE_SV_ENABLE = y:
SEGGER_SYSVIEW (noflash)

View File

@ -0,0 +1,347 @@
/*
* SPDX-FileCopyrightText: 2017-2021 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#include "soc/soc.h"
#include "esp_log.h"
#include "esp_app_trace_port.h"
#include "driver/uart.h"
#include "hal/uart_ll.h"
#include "string.h"
#include "driver/gpio.h"
#define APPTRACE_DEST_UART (CONFIG_APPTRACE_DEST_UART0 | CONFIG_APPTRACE_DEST_UART1 | CONFIG_APPTRACE_DEST_UART2)
#define APP_TRACE_MAX_TX_BUFF_UART CONFIG_APPTRACE_UART_TX_BUFF_SIZE
#define APP_TRACE_MAX_TX_MSG_UART CONFIG_APPTRACE_UART_TX_MSG_SIZE
/** UART HW transport data */
typedef struct {
uint8_t inited;
#if CONFIG_APPTRACE_LOCK_ENABLE
esp_apptrace_lock_t lock; // sync lock
#endif
uart_port_t port_num;
// TX data ring buffer
uint8_t *tx_data_buff;
int32_t tx_data_buff_in;
int32_t tx_data_buff_out;
// TX message buffer
uint8_t *tx_msg_buff;
uint32_t tx_msg_buff_size;
// RX message buffer
uint8_t *down_buffer;
uint32_t down_buffer_size;
// Buffer overflow flags
bool message_buff_overflow;
bool circular_buff_overflow;
} esp_apptrace_uart_data_t;
#if APPTRACE_DEST_UART
static esp_err_t esp_apptrace_uart_init(esp_apptrace_uart_data_t *hw_data);
static esp_err_t esp_apptrace_uart_flush(esp_apptrace_uart_data_t *hw_data, esp_apptrace_tmo_t *tmo);
static esp_err_t esp_apptrace_uart_flush_nolock(esp_apptrace_uart_data_t *hw_data, uint32_t min_sz, esp_apptrace_tmo_t *tmo);
static uint8_t *esp_apptrace_uart_up_buffer_get(esp_apptrace_uart_data_t *hw_data, uint32_t size, esp_apptrace_tmo_t *tmo);
static esp_err_t esp_apptrace_uart_up_buffer_put(esp_apptrace_uart_data_t *hw_data, uint8_t *ptr, esp_apptrace_tmo_t *tmo);
static void esp_apptrace_uart_down_buffer_config(esp_apptrace_uart_data_t *hw_data, uint8_t *buf, uint32_t size);
static uint8_t *esp_apptrace_uart_down_buffer_get(esp_apptrace_uart_data_t *hw_data, uint32_t *size, esp_apptrace_tmo_t *tmo);
static esp_err_t esp_apptrace_uart_down_buffer_put(esp_apptrace_uart_data_t *hw_data, uint8_t *ptr, esp_apptrace_tmo_t *tmo);
static bool esp_apptrace_uart_host_is_connected(esp_apptrace_uart_data_t *hw_data);
#endif // APPTRACE_DEST_UART
const static char *TAG = "esp_apptrace_uart";
esp_apptrace_hw_t *esp_apptrace_uart_hw_get(int num, void **data)
{
ESP_LOGD(TAG,"esp_apptrace_uart_hw_get - %i", num);
#if APPTRACE_DEST_UART
static esp_apptrace_uart_data_t s_uart_hw_data = {
};
static esp_apptrace_hw_t s_uart_hw = {
.init = (esp_err_t (*)(void *))esp_apptrace_uart_init,
.get_up_buffer = (uint8_t *(*)(void *, uint32_t, esp_apptrace_tmo_t *))esp_apptrace_uart_up_buffer_get,
.put_up_buffer = (esp_err_t (*)(void *, uint8_t *, esp_apptrace_tmo_t *))esp_apptrace_uart_up_buffer_put,
.flush_up_buffer_nolock = (esp_err_t (*)(void *, uint32_t, esp_apptrace_tmo_t *))esp_apptrace_uart_flush_nolock,
.flush_up_buffer = (esp_err_t (*)(void *, esp_apptrace_tmo_t *))esp_apptrace_uart_flush,
.down_buffer_config = (void (*)(void *, uint8_t *, uint32_t ))esp_apptrace_uart_down_buffer_config,
.get_down_buffer = (uint8_t *(*)(void *, uint32_t *, esp_apptrace_tmo_t *))esp_apptrace_uart_down_buffer_get,
.put_down_buffer = (esp_err_t (*)(void *, uint8_t *, esp_apptrace_tmo_t *))esp_apptrace_uart_down_buffer_put,
.host_is_connected = (bool (*)(void *))esp_apptrace_uart_host_is_connected,
};
s_uart_hw_data.port_num = num;
*data = &s_uart_hw_data;
return &s_uart_hw;
#else
return NULL;
#endif
}
#if APPTRACE_DEST_UART
static esp_err_t esp_apptrace_uart_lock(esp_apptrace_uart_data_t *hw_data, esp_apptrace_tmo_t *tmo)
{
#if CONFIG_APPTRACE_LOCK_ENABLE
esp_err_t ret = esp_apptrace_lock_take(&hw_data->lock, tmo);
if (ret != ESP_OK) {
return ESP_FAIL;
}
#endif
return ESP_OK;
}
static esp_err_t esp_apptrace_uart_unlock(esp_apptrace_uart_data_t *hw_data)
{
esp_err_t ret = ESP_OK;
#if CONFIG_APPTRACE_LOCK_ENABLE
ret = esp_apptrace_lock_give(&hw_data->lock);
#endif
return ret;
}
static inline void esp_apptrace_uart_hw_init(void)
{
ESP_APPTRACE_LOGI("Initialized UART on CPU%d", cpu_hal_get_core_id());
}
/*****************************************************************************************/
/***************************** Apptrace HW iface *****************************************/
/*****************************************************************************************/
static esp_err_t esp_apptrace_send_uart_data(esp_apptrace_uart_data_t *hw_data, const char *data, uint32_t size, esp_apptrace_tmo_t *tmo)
{
esp_err_t res = esp_apptrace_uart_lock(hw_data, tmo);
if (res != ESP_OK) {
return res;
}
// We store current out position to handle it without lock
volatile int32_t out_position = hw_data->tx_data_buff_out;
int len_free = APP_TRACE_MAX_TX_BUFF_UART - (hw_data->tx_data_buff_in - out_position);
if (out_position > hw_data->tx_data_buff_in) {
len_free = out_position - hw_data->tx_data_buff_in;
}
int check_len = APP_TRACE_MAX_TX_BUFF_UART - hw_data->tx_data_buff_in;
if (size <= len_free)
{
if ( check_len >= size) {
memcpy(&hw_data->tx_data_buff[hw_data->tx_data_buff_in], data, size);
hw_data->tx_data_buff_in += size;
} else {
memcpy(&hw_data->tx_data_buff[hw_data->tx_data_buff_in], data, APP_TRACE_MAX_TX_BUFF_UART - hw_data->tx_data_buff_in);
memcpy(&hw_data->tx_data_buff[0], &data[APP_TRACE_MAX_TX_BUFF_UART - hw_data->tx_data_buff_in], size - (APP_TRACE_MAX_TX_BUFF_UART - hw_data->tx_data_buff_in));
hw_data->tx_data_buff_in = size - (APP_TRACE_MAX_TX_BUFF_UART - hw_data->tx_data_buff_in);
}
if (hw_data->tx_data_buff_in >= APP_TRACE_MAX_TX_BUFF_UART) {
hw_data->tx_data_buff_in = 0;
}
} else {
hw_data->circular_buff_overflow = true;
}
if (esp_apptrace_uart_unlock(hw_data) != ESP_OK) {
assert(false && "Failed to unlock apptrace data!");
}
return ESP_OK;
}
static void send_buff_data(esp_apptrace_uart_data_t *hw_data, esp_apptrace_tmo_t *tmo)
{
if (hw_data->tx_data_buff_in == hw_data->tx_data_buff_out) {
return;
}
// We store current in position to handle it without lock
volatile int32_t in_position = hw_data->tx_data_buff_in;
if (in_position > hw_data->tx_data_buff_out) {
int bytes_sent = uart_write_bytes(hw_data->port_num, &hw_data->tx_data_buff[hw_data->tx_data_buff_out], in_position - hw_data->tx_data_buff_out);
hw_data->tx_data_buff_out += bytes_sent;
} else {
int bytes_sent = uart_write_bytes(hw_data->port_num, &hw_data->tx_data_buff[hw_data->tx_data_buff_out], APP_TRACE_MAX_TX_BUFF_UART - hw_data->tx_data_buff_out);
hw_data->tx_data_buff_out += bytes_sent;
if (hw_data->tx_data_buff_out >= APP_TRACE_MAX_TX_BUFF_UART) {
hw_data->tx_data_buff_out = 0;
}
}
}
#define APP_TRACE_UART_STOP_WAIT_TMO 1000000 //us
static void esp_apptrace_send_uart_tx_task(void *arg)
{
esp_apptrace_uart_data_t *hw_data = (esp_apptrace_uart_data_t *)arg;
esp_apptrace_tmo_t tmo;
esp_apptrace_tmo_init(&tmo, APP_TRACE_UART_STOP_WAIT_TMO);
vTaskDelay(10);
while (1) {
send_buff_data(hw_data, &tmo);
vTaskDelay(10);
if (hw_data->circular_buff_overflow == true)
{
hw_data->circular_buff_overflow = false;
ESP_LOGE(TAG, "Buffer overflow. Please increase UART baudrate, or increase UART TX ring buffer size in menuconfig.");
}
if (hw_data->message_buff_overflow == true)
{
hw_data->message_buff_overflow = false;
ESP_LOGE(TAG, "Message size more then message buffer!");
}
}
}
static const int APP_TRACE_UART_RX_BUF_SIZE = 4024;
static esp_err_t esp_apptrace_uart_init(esp_apptrace_uart_data_t *hw_data)
{
int core_id = cpu_hal_get_core_id();
if (core_id == 0) {
hw_data->tx_data_buff = (uint8_t *)heap_caps_malloc(APP_TRACE_MAX_TX_BUFF_UART, MALLOC_CAP_INTERNAL|MALLOC_CAP_8BIT);
if (hw_data->tx_data_buff == NULL){
return ESP_ERR_NO_MEM;
}
hw_data->tx_data_buff_in = 0;
hw_data->tx_data_buff_out = 0;
hw_data->tx_msg_buff = (uint8_t *)heap_caps_malloc(APP_TRACE_MAX_TX_MSG_UART, MALLOC_CAP_INTERNAL|MALLOC_CAP_8BIT);
if (hw_data->tx_msg_buff == NULL)
{
return ESP_ERR_NO_MEM;
}
hw_data->tx_msg_buff_size = 0;
hw_data->down_buffer_size = 0;
hw_data->message_buff_overflow = false;
hw_data->circular_buff_overflow = false;
const uart_config_t uart_config = {
.baud_rate = CONFIG_APPTRACE_UART_BAUDRATE,
.data_bits = UART_DATA_8_BITS,
.parity = UART_PARITY_DISABLE,
.stop_bits = UART_STOP_BITS_1,
.flow_ctrl = UART_HW_FLOWCTRL_DISABLE,
.source_clk = UART_SCLK_APB,
};
ESP_LOGI(TAG, "UART baud rate: %i", CONFIG_APPTRACE_UART_BAUDRATE);
// We won't use a buffer for sending data.
esp_err_t err = uart_driver_install(hw_data->port_num, APP_TRACE_UART_RX_BUF_SIZE, APP_TRACE_UART_RX_BUF_SIZE, 0, NULL, 0);
assert((err == ESP_OK) && "Not possible to install UART. Please check and change menuconfig parameters!");
err = uart_param_config(hw_data->port_num, &uart_config);
assert((err == ESP_OK) && "Not possible to configure UART. Please check and change menuconfig parameters!");
err = uart_set_pin(hw_data->port_num, CONFIG_APPTRACE_UART_TX_GPIO, CONFIG_APPTRACE_UART_RX_GPIO, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE);
assert((err == ESP_OK) && "Not possible to configure UART RX/TX pins. Please check and change menuconfig parameters!");
int uart_prio = CONFIG_APPTRACE_UART_TASK_PRIO;
if (uart_prio >= (configMAX_PRIORITIES-1)) uart_prio = configMAX_PRIORITIES - 1;
err = xTaskCreate(esp_apptrace_send_uart_tx_task, "app_trace_uart_tx_task", 2500, hw_data, uart_prio, NULL);
assert((err == pdPASS) && "Not possible to configure UART. Not possible to create task!");
#if CONFIG_APPTRACE_LOCK_ENABLE
esp_apptrace_lock_init(&hw_data->lock);
#endif
}
// init UART on this CPU
esp_apptrace_uart_hw_init();
hw_data->inited |= 1 << core_id;
return ESP_OK;
}
static uint8_t *esp_apptrace_uart_up_buffer_get(esp_apptrace_uart_data_t *hw_data, uint32_t size, esp_apptrace_tmo_t *tmo)
{
uint8_t *ptr;
if (size > APP_TRACE_MAX_TX_MSG_UART) {
hw_data->message_buff_overflow = true;
return NULL;
}
if (hw_data->tx_msg_buff_size != 0)
{
// A previous message was not sent.
return NULL;
}
esp_err_t res = esp_apptrace_uart_lock(hw_data, tmo);
if (res != ESP_OK) {
return NULL;
}
ptr = hw_data->tx_msg_buff;
hw_data->tx_msg_buff_size = size;
// now we can safely unlock apptrace to allow other tasks/ISRs to get other buffers and write their data
if (esp_apptrace_uart_unlock(hw_data) != ESP_OK) {
assert(false && "Failed to unlock apptrace data!");
}
return ptr;
}
static esp_err_t esp_apptrace_uart_up_buffer_put(esp_apptrace_uart_data_t *hw_data, uint8_t *ptr, esp_apptrace_tmo_t *tmo)
{
esp_err_t res = esp_apptrace_send_uart_data(hw_data, (const char *)ptr, hw_data->tx_msg_buff_size, tmo);
// Clear size to indicate that we've sent data
hw_data->tx_msg_buff_size = 0;
return res;
}
static void esp_apptrace_uart_down_buffer_config(esp_apptrace_uart_data_t *hw_data, uint8_t *buf, uint32_t size)
{
hw_data->down_buffer = (uint8_t *)malloc(size);
if (hw_data->down_buffer == NULL){
assert(false && "Failed to allocate apptrace uart down buffer!");
}
hw_data->down_buffer_size = size;
}
static uint8_t *esp_apptrace_uart_down_buffer_get(esp_apptrace_uart_data_t *hw_data, uint32_t *size, esp_apptrace_tmo_t *tmo)
{
uint8_t *ptr = NULL;
if (*size > hw_data->down_buffer_size) {
return NULL;
}
esp_err_t res = esp_apptrace_uart_lock(hw_data, tmo);
if (res != ESP_OK) {
return NULL;
}
size_t uart_fifolen = 0;
uart_get_buffered_data_len(hw_data->port_num, &uart_fifolen);
if (uart_fifolen > 0) {
if (*size < uart_fifolen) {
uart_fifolen = *size;
}
*size = uart_fifolen;
ptr = hw_data->down_buffer;
*size =uart_read_bytes(hw_data->port_num, ptr, uart_fifolen, 0);
}
if (esp_apptrace_uart_unlock(hw_data) != ESP_OK) {
assert(false && "Failed to unlock apptrace data!");
}
return ptr;
}
static esp_err_t esp_apptrace_uart_down_buffer_put(esp_apptrace_uart_data_t *hw_data, uint8_t *ptr, esp_apptrace_tmo_t *tmo)
{
return ESP_OK;
}
static bool esp_apptrace_uart_host_is_connected(esp_apptrace_uart_data_t *hw_data)
{
return hw_data->inited & 1;
}
static esp_err_t esp_apptrace_uart_flush_nolock(esp_apptrace_uart_data_t *hw_data, uint32_t min_sz, esp_apptrace_tmo_t *tmo)
{
return ESP_OK;
}
static esp_err_t esp_apptrace_uart_flush(esp_apptrace_uart_data_t *hw_data, esp_apptrace_tmo_t *tmo)
{
return ESP_OK;
}
#endif // APPTRACE_DEST_UART

View File

@ -57,11 +57,6 @@ const static char *TAG = "esp_apptrace";
static esp_apptrace_riscv_ctrl_block_t s_tracing_ctrl[portNUM_PROCESSORS];
esp_apptrace_hw_t *esp_apptrace_uart_hw_get(int num, void **data)
{
return NULL;
}
esp_apptrace_hw_t *esp_apptrace_jtag_hw_get(void **data)
{
#if CONFIG_APPTRACE_DEST_JTAG

View File

@ -210,12 +210,6 @@ static uint8_t * const s_trax_blocks[] = {
(uint8_t *)TRACEMEM_BLK1_ADDR
};
esp_apptrace_hw_t *esp_apptrace_uart_hw_get(int num, void **data)
{
return NULL;
}
esp_apptrace_hw_t *esp_apptrace_jtag_hw_get(void **data)
{
#if CONFIG_APPTRACE_DEST_JTAG

View File

@ -1686,7 +1686,8 @@ void SEGGER_SYSVIEW_Start(void) {
void SEGGER_SYSVIEW_Stop(void) {
U8* pPayloadStart;
RECORD_START(SEGGER_SYSVIEW_INFO_SIZE);
//
// We should send answer for the Stop command in any case.
_SYSVIEW_Globals.EnableState = 1;
if (_SYSVIEW_Globals.EnableState) {
_SendPacket(pPayloadStart, pPayloadStart, SYSVIEW_EVTID_TRACE_STOP);
_SYSVIEW_Globals.EnableState = 0;
@ -1806,6 +1807,10 @@ void SEGGER_SYSVIEW_SendSysDesc(const char *sSysDesc) {
*/
void SEGGER_SYSVIEW_RecordSystime(void) {
U64 Systime;
// This code requeued because SystemView expect the answer from the device.
// If there is no answer, then communication will be broken.
U8 old_en = _SYSVIEW_Globals.EnableState;
_SYSVIEW_Globals.EnableState = 1;
if (_SYSVIEW_Globals.pOSAPI && _SYSVIEW_Globals.pOSAPI->pfGetTime) {
Systime = _SYSVIEW_Globals.pOSAPI->pfGetTime();
@ -1815,6 +1820,7 @@ void SEGGER_SYSVIEW_RecordSystime(void) {
} else {
SEGGER_SYSVIEW_RecordU32(SYSVIEW_EVTID_SYSTIME_CYCLES, SEGGER_SYSVIEW_GET_TIMESTAMP());
}
_SYSVIEW_Globals.EnableState = old_en;
}
/*********************************************************************

View File

@ -30,6 +30,19 @@ static uint8_t s_events_buf[SYSVIEW_EVENTS_BUF_SZ];
static uint16_t s_events_buf_filled;
static uint8_t s_down_buf[SYSVIEW_DOWN_BUF_SIZE];
#if CONFIG_APPTRACE_SV_DEST_UART
#define ESP_APPTRACE_DEST_SYSVIEW ESP_APPTRACE_DEST_UART
#if CONFIG_APPTRACE_SV_DEST_CPU_0 || CONFIG_FREERTOS_UNICORE
#define APPTRACE_SV_DEST_CPU 0
#else
#define APPTRACE_SV_DEST_CPU 1
#endif // CONFIG_APPTRACE_SV_DEST_CPU_0
#elif CONFIG_APPTRACE_SV_DEST_JTAG || (CONFIG_APPTRACE_ENABLE && CONFIG_APPTRACE_DEST_UART_NONE)
#define ESP_APPTRACE_DEST_SYSVIEW ESP_APPTRACE_DEST_TRAX
#endif
/*********************************************************************
*
* Public code
@ -55,13 +68,13 @@ void SEGGER_RTT_ESP_FlushNoLock(unsigned long min_sz, unsigned long tmo)
{
esp_err_t res;
if (s_events_buf_filled > 0) {
res = esp_apptrace_write(ESP_APPTRACE_DEST_TRAX, s_events_buf, s_events_buf_filled, tmo);
res = esp_apptrace_write(ESP_APPTRACE_DEST_SYSVIEW, s_events_buf, s_events_buf_filled, tmo);
if (res != ESP_OK) {
ESP_LOGE(TAG, "Failed to flush buffered events (%d)!\n", res);
}
}
// flush even if we failed to write buffered events, because no new events will be sent after STOP
res = esp_apptrace_flush_nolock(ESP_APPTRACE_DEST_TRAX, min_sz, tmo);
res = esp_apptrace_flush_nolock(ESP_APPTRACE_DEST_SYSVIEW, min_sz, tmo);
if (res != ESP_OK) {
ESP_LOGE(TAG, "Failed to flush apptrace data (%d)!\n", res);
}
@ -108,7 +121,7 @@ void SEGGER_RTT_ESP_Flush(unsigned long min_sz, unsigned long tmo)
*/
unsigned SEGGER_RTT_ReadNoLock(unsigned BufferIndex, void* pData, unsigned BufferSize) {
uint32_t size = BufferSize;
esp_err_t res = esp_apptrace_read(ESP_APPTRACE_DEST_TRAX, pData, &size, 0);
esp_err_t res = esp_apptrace_read(ESP_APPTRACE_DEST_SYSVIEW, pData, &size, 0);
if (res != ESP_OK) {
return 0;
}
@ -142,11 +155,39 @@ unsigned SEGGER_RTT_ReadNoLock(unsigned BufferIndex, void* pData, unsigned Buffe
unsigned SEGGER_RTT_WriteSkipNoLock(unsigned BufferIndex, const void* pBuffer, unsigned NumBytes) {
uint8_t *pbuf = (uint8_t *)pBuffer;
uint8_t event_id = *pbuf;
#if CONFIG_APPTRACE_SV_DEST_UART
if (
(APPTRACE_SV_DEST_CPU != cpu_hal_get_core_id()) &&
(
(event_id == SYSVIEW_EVTID_ISR_ENTER) ||
(event_id == SYSVIEW_EVTID_ISR_EXIT) ||
(event_id == SYSVIEW_EVTID_TASK_START_EXEC) ||
(event_id == SYSVIEW_EVTID_TASK_STOP_EXEC) ||
(event_id == SYSVIEW_EVTID_TASK_START_READY) ||
(event_id == SYSVIEW_EVTID_TASK_STOP_READY) ||
(event_id == SYSVIEW_EVTID_USER_START) ||
(event_id == SYSVIEW_EVTID_USER_STOP) ||
(event_id == SYSVIEW_EVTID_TIMER_ENTER) ||
(event_id == SYSVIEW_EVTID_TIMER_EXIT) ||
(event_id == SYSVIEW_EVTID_STACK_INFO) ||
(event_id == SYSVIEW_EVTID_MODULEDESC)
)
){
return NumBytes;
}
// This is workaround for SystemView!
// Without this line SystemView will hangs on when heap tracing enabled.
if(event_id == SYSVIEW_EVTID_MODULEDESC){
return NumBytes;
}
#endif // CONFIG_APPTRACE_SV_DEST_UART
if (NumBytes > SYSVIEW_EVENTS_BUF_SZ) {
ESP_LOGE(TAG, "Too large event %u bytes!", NumBytes);
return 0;
}
#if CONFIG_APPTRACE_SV_DEST_JTAG
if (cpu_hal_get_core_id()) { // dual core specific code
// use the highest - 1 bit of event ID to indicate core ID
// the highest bit can not be used due to event ID encoding method
@ -157,16 +198,31 @@ unsigned SEGGER_RTT_WriteSkipNoLock(unsigned BufferIndex, const void* pBuffer, u
*pbuf |= (1 << 6);
}
}
#endif // CONFIG_APPTRACE_SV_DEST_JTAG
#if CONFIG_APPTRACE_SV_DEST_JTAG
if (s_events_buf_filled + NumBytes > SYSVIEW_EVENTS_BUF_SZ) {
esp_err_t res = esp_apptrace_write(ESP_APPTRACE_DEST_TRAX, s_events_buf, s_events_buf_filled, SEGGER_HOST_WAIT_TMO);
esp_err_t res = esp_apptrace_write(ESP_APPTRACE_DEST_SYSVIEW, s_events_buf, s_events_buf_filled, SEGGER_HOST_WAIT_TMO);
if (res != ESP_OK) {
return 0; // skip current data buffer only, accumulated events are kept
}
s_events_buf_filled = 0;
}
#endif
memcpy(&s_events_buf[s_events_buf_filled], pBuffer, NumBytes);
s_events_buf_filled += NumBytes;
if (event_id == SYSVIEW_EVTID_TRACE_STOP) {
#if CONFIG_APPTRACE_SV_DEST_UART
esp_err_t res = esp_apptrace_write(ESP_APPTRACE_DEST_SYSVIEW, pBuffer, NumBytes, SEGGER_HOST_WAIT_TMO);
if (res != ESP_OK)
{
return 0; // skip current data buffer only, accumulated events are kept
}
s_events_buf_filled = 0;
#endif
if (event_id == SYSVIEW_EVTID_TRACE_STOP)
{
SEGGER_RTT_ESP_FlushNoLock(0, SEGGER_STOP_WAIT_TMO);
}
return NumBytes;

View File

@ -5,7 +5,7 @@ Application Level Tracing library
Overview
--------
IDF provides a useful feature for program behavior analysis called **Application Level Tracing**. The feature can be enabled in menuconfig and allows transfer of arbitrary data between the host and {IDF_TARGET_NAME} via JTAG interface with minimal overhead on program execution.
IDF provides useful feature for program behavior analysis: application level tracing. It is implemented in the corresponding library and can be enabled in menuconfig. This feature allows to transfer arbitrary data between host and {IDF_TARGET_NAME} via JTAG, UART or USB interfaces with small overhead on program execution. It is possible to use JTAG and UART interfaces simultaneously. The UART interface are mostly used for connection with SEGGER SystemView tool (see `SystemView <https://www.segger.com/products/development-tools/systemview/>`_).
Developers can use this library to send application specific state of execution to the host and receive commands or other type of info in the opposite direction at runtime. The main use cases of this library are:
@ -29,9 +29,10 @@ Modes of Operation
The library supports two modes of operation:
**Post-mortem mode**. This is the default mode. The mode does not need interaction with the host side. In this mode, the tracing module does not check whether host has read all the data from the *HW UP BUFFER* and overwrites it with new data. This mode is useful when only the latest trace data is interesting to the user, e.g. for analyzing the program's behavior just before a crash. Host can read the data later upon user request, e.g. via a special OpenOCD command in case of working via JTAG interface.
**Post-mortem mode**. This is the default mode. The mode does not need interaction with the host side. In this mode tracing module does not check whether host has read all the data from *HW UP BUFFER* buffer and overwrites old data with the new ones. This mode is useful when only the latest trace data are interesting to the user, e.g. for analyzing program's behavior just before the crash. Host can read the data later on upon user request, e.g. via special OpenOCD command in case of working via JTAG interface.
**Streaming mode.** Tracing module enters this mode when host connects to {IDF_TARGET_NAME}. In this mode, before writing new data to *HW UP BUFFER*, the tracing module checks that whether there is enough space in it and if necessary, waits for the host to read data and free enough memory. Maximum waiting time is controlled via timeout values passed by users to corresponding API routines. So when application tries to write data to the trace buffer using finite value of the maximum waiting time, it is possible situation that this data will be dropped. This is especially true for tracing from time critical code (ISRs, OS scheduler code, etc.) when infinite timeouts can lead to system malfunction. In order to avoid loss of such critical data, developers can enable additional data buffering via menuconfig option :ref:`CONFIG_APPTRACE_PENDING_DATA_SIZE_MAX`. This macro specifies the size of data which can be buffered in above conditions. The option can also help to overcome situation when data transfer to the host is temporarily slowed down, e.g. due to USB bus congestions. But it will not help when the average bitrate of the trace data stream exceeds the hardware interface capabilities.
**Streaming mode.** Tracing module enters this mode when host connects to {IDF_TARGET_NAME}. In this mode, before writing new data to *HW UP BUFFER*, the tracing module checks that there is enough space in it and if necessary waits for the host to read data and free enough memory. Maximum waiting time is controlled via timeout values passed by users to corresponding API routines. When an application tries to write data to the trace buffer with a finite wait time, it is possible that the data will be dropped. This is especially true when tracing from time critical code (ISRs, OS scheduler code etc.) where infinite timeouts can lead to a system malfunction. In order to avoid loss of such critical data, developers can enable additional data buffering via menuconfig option :ref:`CONFIG_APPTRACE_PENDING_DATA_SIZE_MAX`. This macro specifies the size of data which can be buffered in such scenarios. This option can also help to overcome a situation when data transfer to the host is temporarily slowed down, e.g. due to USB bus congestions, etc. But it will not help when the average bitrate of the trace data stream exceeds the HW interface capabilities.
Configuration Options and Dependencies
--------------------------------------
@ -40,31 +41,37 @@ Using of this feature depends on two components:
1. **Host side:** Application tracing is done over JTAG, so it needs OpenOCD to be set up and running on host machine. For instructions on how to set it up, please see :doc:`JTAG Debugging <../api-guides/jtag-debugging/index>` for details.
2. **Target side:** Application tracing functionality can be enabled in menuconfig. *Component config > Application Level Tracing* menu allows selecting destination for the trace data (HW interface for transport). Choosing any of the destinations automatically enables ``CONFIG_APPTRACE_ENABLE`` option.
2. **Target side:** Application tracing functionality can be enabled in menuconfig. *Component config > Application Level Tracing* menu allows selecting
destination for the trace data (HW interface for transport: JTAG or/and UART). Choosing any of the destinations automatically enables ``CONFIG_APPTRACE_ENABLE`` option.
For UART interface user have to define baud rate, TX and RX pins numbers, and additional UART related parameters.
.. note::
In order to achieve higher data rates and minimize the number of dropped packets, it is recommended to optimize the setting of the JTAG clock frequency, so it is at maximum and still provides stable operation of JTAG, see :ref:`jtag-debugging-tip-optimize-jtag-speed`.
In order to achieve higher data rates and minimize number of dropped packets it is recommended to optimize setting of JTAG clock frequency, so it is at maximum and still provides stable operation of JTAG, see :ref:`jtag-debugging-tip-optimize-jtag-speed`.
There are two additional menuconfig options that are available to users:
There are two additional menuconfig options not mentioned above:
1. *Threshold for flushing last trace data to host on panic* (:ref:`CONFIG_APPTRACE_POSTMORTEM_FLUSH_THRESH`). This option is necessary due to the nature of working over JTAG. In that mode trace data are exposed to the host in 16 KB blocks. In post-mortem mode when one block is filled it is exposed to the host and the previous one becomes unavailable. In other words trace data are overwritten in 16 KB granularity. On panic the latest data from the current input block are exposed to host and host can read them for post-analysis. System panic may occur when very small amount of data are not exposed to the host yet. In this case the previous 16 KB of collected data will be lost and host will see the latest, but very small piece of the trace. It can be insufficient to diagnose the problem. This menuconfig option allows avoiding such situations. It controls the threshold for flushing data in case of panic. For example user can decide that it needs not less then 512 bytes of the recent trace data, so if there is less then 512 bytes of pending data at the moment of panic they will not be flushed and will not overwrite previous 16 KB. The option is only meaningful in post-mortem mode and when working over JTAG.
1. *Threshold for flushing last trace data to host on panic* (:ref:`CONFIG_APPTRACE_POSTMORTEM_FLUSH_THRESH`). This option is useful when working over JTAG wherein the trace data is exposed to the host in 16 KB blocks. In post-mortem mode, when one block is filled it is exposed to the host and the previous one becomes unavailable. In other words, the trace data is overwritten in 16 KB granularity. On panic, the latest data from the current input block is exposed to the host and the host can read it for post-analysis. System panic may occur when a very small amount of data has been accumulated but not yet exposed to the host. In this case the previous 16 KB of collected data will be lost and the host will see the latest, very small piece of the trace. This data may be insufficient to diagnose the problem. Thus, this menuconfig option allows avoiding such situations. It controls the threshold for flushing data in case of a panic. For example, users can decide that they need no less than 512 bytes of the recent trace data for meaningful analysis. If there is less than 512 bytes of pending data at the moment of panic, it will not be flushed and will not overwrite the previous 16 KB. The option is only meaningful in post-mortem mode and when working over JTAG.
2. *Timeout for flushing last trace data to host on panic* (:ref:`CONFIG_APPTRACE_ONPANIC_HOST_FLUSH_TMO`). The option is only meaningful in streaming mode and controls the maximum time tracing module will wait for the host to read the last data in case of panic.
3. *UART RX/TX ring buffer size* (:ref:`CONFIG_APPTRACE_UART_TX_BUFF_SIZE`). The size of the buffer depends on amount of data transfered through the UART.
4. *UART TX message size* (:ref:`CONFIG_APPTRACE_UART_TX_MSG_SIZE`). The maximum size of the single message to transfer.
How to use this library
-----------------------
This library provides APIs for transferring arbitrary data between the host and {IDF_TARGET_NAME}. When enabled in menuconfig, target application tracing module is initialized automatically at the system startup. All that the user needs to do is to call corresponding APIs to send, receive or flush the data.
This library provides API for transferring arbitrary data between host and {IDF_TARGET_NAME}. When enabled in menuconfig target application tracing module is initialized automatically at the system startup, so all what the user needs to do is to call corresponding API to send, receive or flush the data.
.. _app_trace-application-specific-tracing:
Application Specific Tracing
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
In general the user should decide what type of data should be transferred in either direction and how this data must be interpreted (processed). The following steps must be performed to transfer data between {IDF_TARGET_NAME} and the host:
In general user should decide what type of data should be transferred in every direction and how these data must be interpreted (processed). The following steps must be performed to transfer data between target and host:
1. On target side user should implement algorithms for writing trace data to the host. The following piece of code demonstrates an example of how to do this.
1. On target side user should implement algorithms for writing trace data to the host. Piece of code below shows an example how to do this.
.. code-block:: c
@ -97,7 +104,7 @@ In general the user should decide what type of data should be transferred in eit
return res;
}
The user may also want to receive data from the host. The following piece of code shows an example of how to do this.
Also according to his needs user may want to receive data from the host. Piece of code below shows an example how to do this.
.. code-block:: c
@ -160,13 +167,13 @@ In general the user should decide what type of data should be transferred in eit
OpenOCD Application Level Tracing Commands
""""""""""""""""""""""""""""""""""""""""""
*HW UP BUFFER* is shared between user data blocks and filling of the allocated memory is performed on behalf of the API caller (in task or ISR context). In a multithreaded environment, it can happen that the task/ISR which fills the buffer is preempted by another high priority task/ISR. It is possible that the user data preparation process is not complete when that chunk is read by the host. To handle such scenarios, the tracing module prepends all user data chunks with a header that contains allocated user buffer size (2 bytes) and the length of the actual written data (2 bytes). So total length of the header is 4 bytes. OpenOCD command which reads trace data reports an error when it reads an incomplete user data chunk. In any case, it puts the contents of the whole user chunk (including unfilled area) to the output file.
*HW UP BUFFER* is shared between user data blocks and filling of the allocated memory is performed on behalf of the API caller (in task or ISR context). In multithreading environment it can happen that task/ISR which fills the buffer is preempted by another high priority task/ISR. So it is possible situation that user data preparation process is not completed at the moment when that chunk is read by the host. To handle such conditions tracing module prepends all user data chunks with header which contains allocated user buffer size (2 bytes) and length of actually written data (2 bytes). So total length of the header is 4 bytes. OpenOCD command which reads trace data reports error when it reads incomplete user data chunk, but in any case it puts contents of the whole user chunk (including unfilled area) to output file.
Below is the description of available OpenOCD application tracing commands.
.. note::
Currently, OpenOCD does not provide commands to send arbitrary user data to the target.
Currently OpenOCD does not provide commands to send arbitrary user data to the target.
Command usage:
@ -192,15 +199,15 @@ Start command syntax:
``outfile``
Path to file to save data from both CPUs. This argument should have the following format: ``file://path/to/file``.
``poll_period``
Data polling period (in ms) for available trace data. If greater than 0 then command runs in non-blocking mode. By default, 1 ms.
Data polling period (in ms) for available trace data. If greater than 0 then command runs in non-blocking mode. By default 1 ms.
``trace_size``
Maximum size of data to collect (in bytes). Tracing is stopped after specified amount of data is received. By default -1 (trace size stop trigger is disabled).
``stop_tmo``
Idle timeout (in sec). Tracing is stopped if there is no data for a specified period of time. By default -1 (disable this stop trigger). Optionally set it to a value longer than the longest pause between tracing commands from the target.
Idle timeout (in sec). Tracing is stopped if there is no data for specified period of time. By default -1 (disable this stop trigger). Optionally set it to value longer than longest pause between tracing commands from target.
``wait4halt``
If 0 start tracing immediately, otherwise command waits for the target to be halted (after reset, by breakpoint etc.) and then automatically resumes it and starts tracing. By default, 0.
If 0 start tracing immediately, otherwise command waits for the target to be halted (after reset, by breakpoint etc.) and then automatically resumes it and starts tracing. By default 0.
``skip_size``
Number of bytes to skip at the start. By default, 0.
Number of bytes to skip at the start. By default 0.
.. note::
@ -220,7 +227,7 @@ Command usage examples:
.. note::
Tracing data is buffered before it is made available to OpenOCD. If you see a "Data timeout!" message, it is likely that the target is not sending enough data to empty the buffer to OpenOCD before the timeout. Either increase the timeout or use a function ``esp_apptrace_flush()`` to flush the data on specific intervals.
Tracing data is buffered before it is made available to OpenOCD. If you see "Data timeout!" message, then the target is likely sending not enough data to empty the buffer to OpenOCD before expiration of timeout. Either increase the timeout or use a function ``esp_apptrace_flush()`` to flush the data on specific intervals.
2. Retrieve tracing data indefinitely in non-blocking mode.
@ -228,7 +235,7 @@ Command usage examples:
esp apptrace start file://trace.log 1 -1 -1 0 0
There is no limitation on the size of collected data and there is no data timeout set. This process may be stopped by issuing ``esp apptrace stop`` command on OpenOCD telnet prompt, or by pressing Ctrl+C in OpenOCD window.
There is no limitation on the size of collected data and there is no any data timeout set. This process may be stopped by issuing ``esp apptrace stop`` command on OpenOCD telnet prompt, or by pressing Ctrl+C in OpenOCD window.
3. Retrieve tracing data and save them indefinitely.
@ -252,19 +259,20 @@ Command usage examples:
Logging to Host
^^^^^^^^^^^^^^^
IDF implements a useful feature: logging to host via application level tracing library. This is a kind of semihosting when all `ESP_LOGx` calls are redirected to the host instead of UART. This can be useful because "printing to host" eliminates some steps performed when logging to UART. Most part of the work is done on the host.
IDF implements useful feature: logging to host via application level tracing library. This is a kind of semihosting when all `ESP_LOGx` calls send strings to be printed to the host instead of UART. This can be useful because "printing to host" eliminates some steps performed when logging to UART. The most part of work is done on the host.
By default, IDF's logging library uses a vprintf-like function to write formatted output to dedicated UART. In general, it involves the following steps:
By default IDF's logging library uses vprintf-like function to write formatted output to dedicated UART. In general it involves the following steps:
1. Format string is parsed to obtain type of each argument.
2. According to its type every argument is converted to string representation.
3. Format string combined with converted arguments is sent to UART.
Though the implementation of a vprintf-like function can be optimized to a certain level, all steps above have to be performed in any case and every step takes some time (especially item 3). Hence, it is quite common to observe that with additional logging added to a program for debugging, the program behavior changes and the problem is not reproduced. In the worst case, the program may not work normally at all and ends up with an error or even hangs.
Though implementation of vprintf-like function can be optimized to a certain level, all steps above have to be performed in any case and every step takes some time (especially item 3). So it frequently occurs that with additional log added to the program to identify the problem, the program behavior is changed and the problem cannot be reproduced or in the worst cases the program cannot work normally at all and ends up with an error or even hangs.
Possible ways to overcome this problem are to use higher UART bitrates (or another faster interface) and/or move string formatting procedure to the host.
Application level tracing feature can be used to transfer log information to the host using ``esp_apptrace_vprintf`` function. This function does not perform full parsing of the format string and arguments, and instead just calculates the number of arguments passed and sends them along with the format string address to the host. On the host, log data are processed and printed out by a special Python script.
Application level tracing feature can be used to transfer log information to host using ``esp_apptrace_vprintf`` function. This function does not perform full parsing of the format string and arguments, instead it just calculates number of arguments passed and sends them along with the format string address to the host. On the host log data are processed and printed out by a special Python script.
Limitations
"""""""""""
@ -282,7 +290,7 @@ How To Use It
In order to use logging via trace module user needs to perform the following steps:
1. On target side, the user must use the :cpp:func:`esp_apptrace_vprintf` function to send log data to the host. Example code is provided in :example:`system/app_trace_to_host`.
1. On target side special vprintf-like function needs to be installed. As it was mentioned earlier this function is ``esp_apptrace_vprintf``. It sends log data to the host. Example code is provided in :example:`system/app_trace_to_host`.
2. Follow instructions in items 2-5 in `Application Specific Tracing`_.
3. To print out collected log records, run the following command in terminal: ``$IDF_PATH/tools/esp_app_trace/logtrace_proc.py /path/to/trace/file /path/to/program/elf/file``.
@ -313,20 +321,21 @@ Optional arguments:
System Behavior Analysis with SEGGER SystemView
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Another useful IDF feature built on top of application tracing library is the system level tracing which produces traces compatible with SEGGER SystemView tool (see `SystemView <https://www.segger.com/products/development-tools/systemview/>`_). SEGGER SystemView is a real-time recording and visualization tool that allows to analyze runtime behavior of an application.
.. note::
Currently, IDF based applications are able to generate SystemView compatible traces in form of files to be opened in the SystemView application. The tracing process cannot yet be controlled using that tool.
Another useful IDF feature built on top of application tracing library is the system level tracing which produces traces
compatible with SEGGER SystemView tool (see `SystemView <https://www.segger.com/products/development-tools/systemview/>`_).
SEGGER SystemView is a real-time recording and visualization tool that allows to analyze runtime behavior of an application.
It is possible to view events in real-time through the UART interface.
How To Use It
"""""""""""""
Support for this feature is enabled by *Component config > Application Level Tracing > FreeRTOS SystemView Tracing* (:ref:`CONFIG_APPTRACE_SV_ENABLE`) menuconfig option. There are several other options enabled under the same menu:
Support for this feature is enabled by *Component config > Application Level Tracing > FreeRTOS SystemView Tracing* (:ref:`CONFIG_APPTRACE_SV_ENABLE`) menuconfig option. There are several other options enabled under the same menu:
1. {IDF_TARGET_NAME} timer to use as SystemView timestamp source: (:ref:`CONFIG_APPTRACE_SV_TS_SOURCE`) selects the source of timestamps for SystemView events. In single core mode timestamps are generated using {IDF_TARGET_NAME} internal cycle counter running at maximum 240 Mhz (~4 ns granularity). In dual-core mode external timer working at 40 Mhz is used, so timestamp granularity is 25 ns.
2. Individually enabled or disabled collection of SystemView events (``CONFIG_APPTRACE_SV_EVT_XXX``):
1. SytemView destination. Select the destination interface: JTAG or UART. In case of UART
it will be possible to connect SystemView application to the {IDF_TARGET_NAME} directly and receive data in real-time.
2. {IDF_TARGET_NAME} timer to use as SystemView timestamp source: (:ref:`CONFIG_APPTRACE_SV_TS_SOURCE`) selects the source of timestamps for SystemView events. In single core mode timestamps are generated using {IDF_TARGET_NAME} internal cycle counter running at maximum 240 Mhz (~4 ns granularity). In dual-core mode external timer working at 40 Mhz is used, so timestamp granularity is 25 ns.
3. Individually enabled or disabled collection of SystemView events (``CONFIG_APPTRACE_SV_EVT_XXX``):
- Trace Buffer Overflow Event
- ISR Enter Event
@ -344,6 +353,8 @@ Support for this feature is enabled by *Component config > Application Level Tra
IDF has all the code required to produce SystemView compatible traces, so user can just configure necessary project options (see above), build, download the image to target and use OpenOCD to collect data as described in the previous sections.
4. Select Pro or App CPU in menuconfig options *Component config > Application Level Tracing > FreeRTOS SystemView Tracing* to trace over UART interface in real-time.
OpenOCD SystemView Tracing Command Options
""""""""""""""""""""""""""""""""""""""""""
@ -370,7 +381,7 @@ Start command syntax:
``outfile2``
Path to file to save data from APP CPU. This argument should have the following format: ``file://path/to/file``.
``poll_period``
Data polling period (in ms) for available trace data. If greater than 0 then command runs in non-blocking mode. By default, 1 ms.
Data polling period (in ms) for available trace data. If greater then 0 then command runs in non-blocking mode. By default 1 ms.
``trace_size``
Maximum size of data to collect (in bytes). Tracing is stopped after specified amount of data is received. By default -1 (trace size stop trigger is disabled).
``stop_tmo``
@ -404,13 +415,15 @@ Command usage examples:
Data Visualization
""""""""""""""""""
After trace data is collected, users can use a special tool to visualize the results and inspect behavior of the program.
After trace data are collected user can use special tool to visualize the results and inspect behavior of the program.
.. only:: not CONFIG_FREERTOS_UNICORE
Unfortunately SystemView does not support tracing from multiple cores. So when tracing from {IDF_TARGET_NAME} working in dual-core mode two files are generated: one for PRO CPU and another one for APP CPU. Users can load both files into separate instances of the tool.
Unfortunately SystemView does not support tracing from multiple cores. So when tracing from {IDF_TARGET_NAME} working with JTAG in dual-core mode two files are
generated: one for PRO CPU and another one for APP CPU. User can load every file into separate instance of the tool. For tracing over UART, user can select in
menuconfig Pro or App *Component config > Application Level Tracing > FreeRTOS SystemView Tracing* with CPU has to be traced.
It is uneasy and awkward to analyze data for every core in separate instance of the tool. Fortunately there is an Eclipse plugin called *Impulse* which can load several trace files and makes it possible to inspect events from both cores in one view. Also, this plugin has no limitation of 1,000,000 events as compared to free version of SystemView.
It is uneasy and awkward to analyze data for every core in separate instance of the tool. Fortunately there is Eclipse plugin called *Impulse* which can load several trace files and makes it possible to inspect events from both cores in one view. Also this plugin has no limitation of 1,000,000 events as compared to free version of SystemView.
Good instruction on how to install, configure and visualize data in Impulse from one core can be found `here <https://mcuoneclipse.com/2016/07/31/impulse-segger-systemview-in-eclipse/>`_.
@ -438,7 +451,7 @@ Good instruction on how to install, configure and visualize data in Impulse from
.. note::
If you have problems with visualization (no data are shown or strange behavior of zoom action is observed) you can try to delete current signal hierarchy and double-click on the necessary file or port. Eclipse will ask you to create new signal hierarchy.
If you have problems with visualization (no data are shown or strange behavior of zoom action is observed) you can try to delete current signal hierarchy and double click on the necessary file or port. Eclipse will ask you to create new signal hierarchy.
.. _app_trace-gcov-source-code-coverage:
@ -462,7 +475,7 @@ Generally, using Gcov to compile and run programs on the Host will undergo these
Gcov and Gcovr in ESP-IDF
"""""""""""""""""""""""""""
Using Gcov in ESP-IDF is complicated due to the fact that the program is running remotely and not on the host (i.e., on the target). The code coverage data (i.e., the ``.gcda`` files) is initially stored on the target itself. OpenOCD is then used to dump the code coverage data from the target to the host via JTAG during runtime. Using Gcov in ESP-IDF can be split into the following steps.
Using Gcov in ESP-IDF is complicated by the fact that the program is running remotely from the Host (i.e., on the target). The code coverage data (i.e., the ``.gcda`` files) is initially stored on the target itself. OpenOCD is then used to dump the code coverage data from the target to the host via JTAG during runtime. Using Gcov in ESP-IDF can be split into the following steps.
1. :ref:`app_trace-gcov-setup-project`
2. :ref:`app_trace-gcov-dumping-data`
@ -479,7 +492,7 @@ Compiler Option
In order to obtain code coverage data in a project, one or more source files within the project must be compiled with the ``--coverage`` option. In ESP-IDF, this can be achieved at the component level or the individual source file level:
- To cause all source files in a component to be compiled with the ``--coverage`` option, you can add ``target_compile_options(${COMPONENT_LIB} PRIVATE --coverage)`` to the ``CMakeLists.txt`` file of the component.
- To cause a select number of source files (e.g. ``source1.c`` and ``source2.c``) in the same component to be compiled with the ``--coverage`` option, you can add ``set_source_files_properties(source1.c source2.c PROPERTIES COMPILE_FLAGS --coverage)`` to the ``CMakeLists.txt`` file of the component.
- To cause a select number of source files (e.g. ``sourec1.c`` and ``source2.c``) in the same component to be compiled with the ``--coverage`` option, you can add ``set_source_files_properties(source1.c source2.c PROPERTIES COMPILE_FLAGS --coverage)`` to the ``CMakeLists.txt`` file of the component.
When a source file is compiled with the ``--coverage`` option (e.g. ``gcov_example.c``), the compiler will generate the ``gcov_example.gcno`` file in the project's build directory.
@ -488,7 +501,7 @@ Project Configuration
Before building a project with source code coverage, ensure that the following project configuration options are enabled by running ``idf.py menuconfig``.
- Enable the application tracing module by choosing *Trace Memory* for the :ref:`CONFIG_APPTRACE_DESTINATION` option.
- Enable the application tracing module by choosing *Trace Memory* for the :ref:`CONFIG_APPTRACE_DESTINATION1` option.
- Enable Gcov to host via the :ref:`CONFIG_APPTRACE_GCOV_ENABLE`
.. _app_trace-gcov-dumping-data:
@ -496,23 +509,23 @@ Before building a project with source code coverage, ensure that the following p
Dumping Code Coverage Data
""""""""""""""""""""""""""
Once a project has been complied with the ``--coverage`` option and flashed onto the target, code coverage data will be stored internally on the target (i.e., in trace memory) whilst the application runs. The process of transferring code coverage data from the target to the Host is known as dumping.
Once a project has been complied with the ``--coverage`` option and flashed onto the target, code coverage data will be stored internally on the target (i.e., in trace memory) whilst the application runs. The process of transferring code coverage data from the target to the Host is know as dumping.
The dumping of coverage data is done via OpenOCD (see :doc:`JTAG Debugging <../api-guides/jtag-debugging/index>` on how to setup and run OpenOCD). A dump is triggered by issuing commands to OpenOCD, therefore a telnet session to OpenOCD must be opened to issue such commands (run ``telnet localhost 4444``). Note that GDB could be used instead of telnet to issue commands to OpenOCD, however all commands issued from GDB will need to be prefixed as ``mon <oocd_command>``.
When the target dumps code coverage data, the ``.gcda`` files are stored in the project's build directory. For example, if ``gcov_example_main.c`` of the ``main`` component was compiled with the ``--coverage`` option, then dumping the code coverage data would generate a ``gcov_example_main.gcda`` in ``build/esp-idf/main/CMakeFiles/__idf_main.dir/gcov_example_main.c.gcda``. Note that the ``.gcno`` files produced during compilation are also placed in the same directory.
The dumping of code coverage data can be done multiple times throughout an application's lifetime. Each dump will simply update the ``.gcda`` file with the newest code coverage information. Code coverage data is accumulative, thus the newest data will contain the total execution count of each code path over the application's entire lifetime.
The dumping of code coverage data can be done multiple times throughout an application's life time. Each dump will simply update the ``.gcda`` file with the newest code coverage information. Code coverage data is accumulative, thus the newest data will contain the total execution count of each code path over the application's entire lifetime.
ESP-IDF supports two methods of dumping code coverage data form the target to the host:
* Instant Run-Time Dump
* Instant Run-Time Dumpgit
* Hard-coded Dump
Instant Run-Time Dump
~~~~~~~~~~~~~~~~~~~~~
An Instant Run-Time Dump is triggered by calling the ``{IDF_TARGET_NAME} gcov`` OpenOCD command (via a telnet session). Once called, OpenOCD will immediately preempt the {IDF_TARGET_NAME}'s current state and execute a builtin IDF Gcov debug stub function. The debug stub function will handle the dumping of data to the Host. Upon completion, the {IDF_TARGET_NAME} will resume its current state.
An Instant Run-Time Dump is triggered by calling the ``{IDF_TARGET_NAME} gcov`` OpenOCD command (via a telnet session). Once called, OpenOCD will immediately preempt the {IDF_TARGET_NAME}'s current state and execute a builtin IDF Gcov debug stub function. The debug stub function will handle the dumping of data to the Host. Upon completion, the {IDF_TARGET_NAME} will resume it's current state.
Hard-coded Dump
~~~~~~~~~~~~~~~
@ -545,10 +558,10 @@ Once the code coverage data has been dumped, the ``.gcno``, ``.gcda`` and the so
Both Gcov and Gcovr can be used to generate code coverage reports. Gcov is provided along with the Xtensa toolchain, whilst Gcovr may need to be installed separately. For details on how to use Gcov or Gcovr, refer to `Gcov documentation <https://gcc.gnu.org/onlinedocs/gcc/Gcov.html>`_ and `Gcovr documentation <http://gcovr.com/>`_.
Adding Gcov Build Target to Project
Adding Gcovr Build Target to Project
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
To make report generation more convenient, users can define additional build targets in their projects such that the report generation can be done with a single build command.
To make report generation more convenient, users can define additional build targets in their projects such report generation can be done with a single build command.
Add the following lines to the ``CMakeLists.txt`` file of your project.

View File

@ -272,7 +272,7 @@ Host-Based Mode
Once you've identified the code which you think is leaking:
- In the project configuration menu, navigate to ``Component settings`` -> ``Heap Memory Debugging`` -> :ref:`CONFIG_HEAP_TRACING_DEST` and select ``Host-Based``.
- In the project configuration menu, navigate to ``Component settings`` -> ``Application Level Tracing`` -> :ref:`CONFIG_APPTRACE_DESTINATION` and select ``Trace memory``.
- In the project configuration menu, navigate to ``Component settings`` -> ``Application Level Tracing`` -> :ref:`CONFIG_APPTRACE_DESTINATION1` and select ``Trace memory``.
- In the project configuration menu, navigate to ``Component settings`` -> ``Application Level Tracing`` -> ``FreeRTOS SystemView Tracing`` and enable :ref:`CONFIG_APPTRACE_SV_ENABLE`.
- Call the function :cpp:func:`heap_trace_init_tohost` early in the program, to initialize JTAG heap tracing module.
- Call the function :cpp:func:`heap_trace_start` to begin recording all mallocs/frees in the system. Call this immediately before the piece of code which you suspect is leaking memory.

View File

@ -492,7 +492,7 @@ ESP-IDF 中 Gcov 和 Gcovr 应用
在构建一个有源代码覆盖的项目之前,请通过运行 ``idf.py menuconfig`` 启用以下项目配置选项。
- 通过 :ref:`CONFIG_APPTRACE_DESTINATION` 选项选择 *Trace Memory* 来启用应用程序跟踪模块。
- 通过 :ref:`CONFIG_APPTRACE_DESTINATION1` 选项选择 *Trace Memory* 来启用应用程序跟踪模块。
- 通过 :ref:`CONFIG_APPTRACE_GCOV_ENABLE` 选项启用 Gcov 主机。
.. _app_trace-gcov-dumping-data: