diff --git a/Kconfig b/Kconfig index deb0cea839..b1f5586dbc 100644 --- a/Kconfig +++ b/Kconfig @@ -46,6 +46,3 @@ endchoice menu "Component config" source "$COMPONENT_KCONFIGS" endmenu - - - diff --git a/components/app_trace/Kconfig b/components/app_trace/Kconfig new file mode 100644 index 0000000000..e88128f333 --- /dev/null +++ b/components/app_trace/Kconfig @@ -0,0 +1,184 @@ +menu "Application Level Tracing" + +choice ESP32_APPTRACE_DESTINATION + prompt "Data Destination" + default ESP32_APPTRACE_DEST_NONE + help + Select destination for application trace: trace memory or none (to disable). + +config ESP32_APPTRACE_DEST_TRAX + bool "Trace memory" + select ESP32_APPTRACE_ENABLE +config ESP32_APPTRACE_DEST_NONE + bool "None" +endchoice + +config ESP32_APPTRACE_ENABLE + bool + depends on !ESP32_TRAX + select MEMMAP_TRACEMEM + select MEMMAP_TRACEMEM_TWOBANKS + default n + help + Enables/disable application tracing module. + +config ESP32_APPTRACE_ONPANIC_HOST_FLUSH_TMO + int "Timeout for flushing last trace data to host on panic" + depends on ESP32_APPTRACE_ENABLE + range -1 5000 + default -1 + help + Timeout for flushing last trace data to host in case of panic. In ms. + Use -1 to disable timeout and wait forever. + +config ESP32_APPTRACE_POSTMORTEM_FLUSH_TRAX_THRESH + int "Threshold for flushing last trace data to host on panic" + depends on ESP32_APPTRACE_DEST_TRAX + range 0 16384 + default 0 + help + Threshold for flushing last trace data to host on panic in post-mortem mode. + This is minimal amount of data needed to perform flush. In bytes. + +config ESP32_APPTRACE_PENDING_DATA_SIZE_MAX + int "Size of the pending data buffer" + depends on ESP32_APPTRACE_DEST_TRAX + default 0 + help + Size of the buffer for events in bytes. It is useful for buffering events from + the time critical code (scheduler, ISRs etc). If this parameter is 0 then + events will be discarded when main HW buffer is full. + +menu "FreeRTOS SystemView Tracing" +config SYSVIEW_ENABLE + bool "SystemView Tracing Enable" + depends on ESP32_APPTRACE_ENABLE + default n + help + Enables supporrt for SEGGER SystemView tracing functionality. + +if !FREERTOS_UNICORE +choice SYSVIEW_TS_SOURCE + prompt "ESP32 timer to use as SystemView timestamp source" + depends on SYSVIEW_ENABLE + default SYSVIEW_TS_SOURCE_TIMER_00 + help + SystemView needs one source for timestamps when tracing events from both cores. + This option selects HW timer for it. + +config SYSVIEW_TS_SOURCE_TIMER_00 + bool "Timer 0, Group 0" + help + Select this to use timer 0 of group 0 + +config SYSVIEW_TS_SOURCE_TIMER_01 + bool "Timer 1, Group 0" + help + Select this to use timer 1 of group 0 + +config SYSVIEW_TS_SOURCE_TIMER_10 + bool "Timer 0, Group 1" + help + Select this to use timer 0 of group 1 + +config SYSVIEW_TS_SOURCE_TIMER_11 + bool "Timer 1, Group 1" + help + Select this to use timer 1 of group 1 + +endchoice +endif #FREERTOS_UNICORE + +config SYSVIEW_EVT_OVERFLOW_ENABLE + bool "Trace Buffer Overflow Event" + depends on SYSVIEW_ENABLE + default y + help + Enables "Trace Buffer Overflow" event. + +config SYSVIEW_EVT_ISR_ENTER_ENABLE + bool "ISR Enter Event" + depends on SYSVIEW_ENABLE + default y + help + Enables "ISR Enter" event. + +config SYSVIEW_EVT_ISR_EXIT_ENABLE + bool "ISR Exit Event" + depends on SYSVIEW_ENABLE + default y + help + Enables "ISR Exit" event. + +config SYSVIEW_EVT_ISR_TO_SCHEDULER_ENABLE + bool "ISR Exit to Scheduler Event" + depends on SYSVIEW_ENABLE + default y + help + Enables "ISR to Scheduler" event. + +config SYSVIEW_EVT_TASK_START_EXEC_ENABLE + bool "Task Start Execution Event" + depends on SYSVIEW_ENABLE + default y + help + Enables "Task Start Execution" event. + +config SYSVIEW_EVT_TASK_STOP_EXEC_ENABLE + bool "Task Stop Execution Event" + depends on SYSVIEW_ENABLE + default y + help + Enables "Task Stop Execution" event. + +config SYSVIEW_EVT_TASK_START_READY_ENABLE + bool "Task Start Ready State Event" + depends on SYSVIEW_ENABLE + default y + help + Enables "Task Start Ready State" event. + +config SYSVIEW_EVT_TASK_STOP_READY_ENABLE + bool "Task Stop Ready State Event" + depends on SYSVIEW_ENABLE + default y + help + Enables "Task Stop Ready State" event. + +config SYSVIEW_EVT_TASK_CREATE_ENABLE + bool "Task Create Event" + depends on SYSVIEW_ENABLE + default y + help + Enables "Task Create" event. + +config SYSVIEW_EVT_TASK_TERMINATE_ENABLE + bool "Task Terminate Event" + depends on SYSVIEW_ENABLE + default y + help + Enables "Task Terminate" event. + +config SYSVIEW_EVT_IDLE_ENABLE + bool "System Idle Event" + depends on SYSVIEW_ENABLE + default y + help + Enables "System Idle" event. + +config SYSVIEW_EVT_TIMER_ENTER_ENABLE + bool "Timer Enter Event" + depends on SYSVIEW_ENABLE + default y + help + Enables "Timer Enter" event. + +config SYSVIEW_EVT_TIMER_EXIT_ENABLE + bool "Timer Exit Event" + depends on SYSVIEW_ENABLE + default y + help + Enables "Timer Exit" event. + +endmenu +endmenu diff --git a/components/esp32/app_trace.c b/components/app_trace/app_trace.c similarity index 50% rename from components/esp32/app_trace.c rename to components/app_trace/app_trace.c index 32efcf5572..0a990b0d1d 100644 --- a/components/esp32/app_trace.c +++ b/components/app_trace/app_trace.c @@ -18,44 +18,49 @@ // 1. Components Overview // ====================== -// Xtensa has useful feature: TRAX debug module. It allows recording program execution flow during run-time without disturbing CPU commands flow. +// Xtensa has useful feature: TRAX debug module. It allows recording program execution flow at run-time without disturbing CPU. // Exectution flow data are written to configurable Trace RAM block. Besides accessing Trace RAM itself TRAX module also allows to read/write // trace memory via its registers by means of JTAG, APB or ERI transactions. // ESP32 has two Xtensa cores with separate TRAX modules on them and provides two special memory regions to be used as trace memory. -// ESP32 allows muxing access to trace memory blocks in such a way that while one block is accessed by CPUs another can be accessed via JTAG by host -// via reading/writing TRAX registers. Block muxing is configurable at run-time and allows switching trace memory blocks between +// Chip allows muxing access to those trace memory blocks in such a way that while one block is accessed by CPUs another one can be accessed by host +// by means of reading/writing TRAX registers via JTAG. Blocks muxing is configurable at run-time and allows switching trace memory blocks between // accessors in round-robin fashion so they can read/write separate memory blocks without disturbing each other. -// This moduile implements application tracing feature based on above mechanisms. This feature allows to transfer arbitrary user data to +// This module implements application tracing feature based on above mechanisms. It allows to transfer arbitrary user data to/from // host via JTAG with minimal impact on system performance. This module is implied to be used in the following tracing scheme. -// ------>------ ----- (host components) ----- -// | | | | -// --------------- ----------------------- ----------------------- ---------------- ------ --------- ----------------- -// |apptrace user|-->|target tracing module|<--->|TRAX_MEM0 | TRAX_MEM1|---->|TRAX_DATA_REGS|<-->|JTAG|<--->|OpenOCD|-->|trace data file| -// --------------- ----------------------- ----------------------- ---------------- ------ --------- ----------------- -// | | | | -// | ------<------ ---------------- | -// |<------------------------------------------->|TRAX_CTRL_REGS|<---->| -// ---------------- +// ------>------ ----- (host components) ----- +// | | | | +// ------------------- ----------------------- ----------------------- ---------------- ------ --------- ----------------- +// |trace data source|-->|target tracing module|<--->|TRAX_MEM0 | TRAX_MEM1|---->|TRAX_DATA_REGS|<-->|JTAG|<--->|OpenOCD|-->|trace data sink| +// ------------------- ----------------------- ----------------------- ---------------- ------ --------- ----------------- +// | | | | +// | ------<------ ---------------- | +// |<------------------------------------------->|TRAX_CTRL_REGS|<---->| +// ---------------- -// In general tracing happens in the following way. User aplication requests tracing module to send some data by calling esp_apptrace_buffer_get(), -// moduile allocates necessary buffer in current input trace block. Then user fills received buffer with data and calls esp_apptrace_buffer_put(). +// In general tracing goes in the following way. User aplication requests tracing module to send some data by calling esp_apptrace_buffer_get(), +// module allocates necessary buffer in current input trace block. Then user fills received buffer with data and calls esp_apptrace_buffer_put(). // When current input trace block is filled with app data it is exposed to host and the second block becomes input one and buffer filling restarts. -// While target application fills one memory block host reads another block via JTAG. +// While target application fills one TRAX block host reads another one via JTAG. +// This module also allows communication in the opposite direction: from host to target. As it was said ESP32 and host can access different TRAX blocks +// simultaneously, so while target writes trace data to one block host can write its own data (e.g. tracing commands) to another one then when +// blocks are switched host receives trace data and target receives data written by host application. Target user application can read host data +// by calling esp_apptrace_read() API. // To control buffer switching and for other communication purposes this implementation uses some TRAX registers. It is safe since HW TRAX tracing // can not be used along with application tracing feature so these registers are freely readable/writeable via JTAG from host and via ERI from ESP32 cores. -// So this implementation's target CPU overhead is produced only by calls to allocate/manage buffers and data copying. -// On host special OpenOCD command must be used to read trace data. +// Overhead of this implementation on target CPU is produced only by allocating/managing buffers and copying of data. +// On the host side special OpenOCD command must be used to read trace data. -// 2.1.1.1 TRAX Registers layout -// ============================= +// 2. TRAX Registers layout +// ======================== // This module uses two TRAX HW registers to communicate with host SW (OpenOCD). // - Control register uses TRAX_DELAYCNT as storage. Only lower 24 bits of TRAX_DELAYCNT are writable. Control register has the following bitfields: // | 31..XXXXXX..24 | 23 .(host_connect). 23| 22..(block_id)..15 | 14..(block_len)..0 | // 14..0 bits - actual length of user data in trace memory block. Target updates it every time it fills memory block and exposes it to host. // Host writes zero to this field when it finishes reading exposed block; -// 22..15 bits - trace memory block transfer ID. Block counter. It can overflow. Updated by target, host should not modify it. Actually can be 1-2 bits; +// 21..15 bits - trace memory block transfer ID. Block counter. It can overflow. Updated by target, host should not modify it. Actually can be 2 bits; +// 22 bit - 'host data present' flag. If set to one there is data from host, otherwise - no host data; // 23 bit - 'host connected' flag. If zero then host is not connected and tracing module works in post-mortem mode, otherwise in streaming mode; // - Status register uses TRAX_TRIGGERPC as storage. If this register is not zero then currentlly CPU is changing TRAX registers and // this register holds address of the instruction which application will execute when it finishes with those registers modifications. @@ -68,22 +73,27 @@ // - Post-mortem mode. This is the default mode. In this mode application tracing module does not check whether host has read all the data from block // exposed to it and switches block in any case. The mode does not need host interaction for operation and so can be useful when only the latest // trace data are necessary, e.g. for analyzing crashes. On panic the latest data from current input block are exposed to host and host can read them. -// There is menuconfig option CONFIG_ESP32_APPTRACE_ONPANIC_HOST_FLUSH_TRAX_THRESH which control the threshold for flushing data on panic. -// - Streaming mode. Tracing module enters this mode when host connects to targets and sets respective bit in control register. In this mode tracing -// module waits for specified time until host read all the data from exposed block. -// On panic tracing module waits (timeout is configured via menuconfig via ESP32_APPTRACE_ONPANIC_HOST_FLUSH_TMO) for the host to read all data -// from the previously exposed block. +// It can happen that system panic occurs when there are very small amount of data which are not exposed to host yet (e.g. crash just after the +// TRAX block switch). In this case the previous 16KB of collected data will be dropped and host will see the latest, but very small piece of trace. +// It can be insufficient to diagnose the problem. To avoid such situations there is menuconfig option CONFIG_ESP32_APPTRACE_POSTMORTEM_FLUSH_TRAX_THRESH +// which controls the threshold for flushing data in case of panic. +// - Streaming mode. Tracing module enters this mode when host connects to target and sets respective bits in control registers (per core). +// In this mode before switching the block tracing module waits for the host to read all the data from the previously exposed block. +// On panic tracing module also waits (timeout is configured via menuconfig via CONFIG_ESP32_APPTRACE_ONPANIC_HOST_FLUSH_TMO) for the host to read all data. // 4. Communication Protocol // ========================= // 4.1 Trace Memory Blocks -// ^^^^^^^^^^^^^^^^^^^^^^^^^ +// ----------------------- // Communication is controlled via special register. Host periodically polls control register on each core to find out if there are any data avalable. -// When current input trace memory block is filled tracing module exposes block to host and updates block_len and block_id fields in control register. -// Host reads new register value and according to it starts reading data from exposed block. Meanwhile target starts filling another trace block. -// When host finishes reading the block it clears block_len field in control register indicating to target that it is ready to accept the next block. +// When current input memory block is filled it is exposed to host and 'block_len' and 'block_id' fields are updated in the control register. +// Host reads new register value and according to it's value starts reading data from exposed block. Meanwhile target starts filling another trace block. +// When host finishes reading the block it clears 'block_len' field in control register indicating to the target that it is ready to accept the next one. +// If the host has some data to transfer to the target it writes them to trace memory block before clearing 'block_len' field. Then it sets +// 'host_data_present' bit and clears 'block_len' field in control register. Upon every block switch target checks 'host_data_present' bit and if it is set +// reads them to down buffer before writing any trace data to switched TRAX block. // 4.2 User Data Chunks Level // -------------------------- @@ -91,11 +101,21 @@ // Since trace memory block is shared between user data chunks and data copying is performed on behalf of the API user (in its normal context) in // multithreading environment it can happen that task/ISR which copies data is preempted by another high prio task/ISR. So it is possible situation // that task/ISR will fail to complete filling its data chunk before the whole trace block is exposed to the host. To handle such conditions tracing -// module prepends all user data chunks with 4 bytes header which contains allocated buffer size and actual data length within it. OpenOCD command -// which reads application traces will report error when it will read incompleted user data block. +// module prepends all user data chunks with header which contains allocated buffer size and actual data length within it. OpenOCD command +// which reads application traces reports error when it reads incompleted user data block. +// Data which are transfered from host to target are also prepended with such header. -// 4.3 Targets Connection/Disconnection -// ------------------------------------ +// 4.3 Data Buffering +// ------------------ + +// It takes some time for the host to read TRAX memory block via JTAG. In streaming mode it can happen that target has filled its TRAX block, but host +// has not completed reading of the previous one yet. So in this case time critical tracing calls (which can not be delayed for too long time due to +// the lack of free memory in TRAX block) can be dropped. To avoid such scenarios tracing module implements data buffering. Buffered data will be sent +// to the host later when TRAX block switch occurs. The maximum size of the buffered data is controlled by menuconfig option +// CONFIG_ESP32_APPTRACE_PENDING_DATA_SIZE_MAX. + +// 4.4 Target Connection/Disconnection +// ----------------------------------- // When host is going to start tracing in streaming mode it needs to put both ESP32 cores into initial state when 'host connected' bit is set // on both cores. To accomplish this host halts both cores and sets this bit in TRAX registers. But target code can be halted in state when it has read control @@ -119,14 +139,11 @@ // When low prio task takes mutex and enables local IRQs gets preempted by high prio task which in its turn can try to acquire mutex using infinite timeout. // So no local task switch occurs when mutex is locked. But this does not apply to tasks on another CPU. // WARNING: Priority inversion can happen when low prio task works on one CPU and medium and high prio tasks work on another. -// There are some differences how mutex behaves when it is used from task and ISR context when timeout is non-zero: -// - In task context when mutex can not be locked portYIELD() is called before check for timeout condition to alow othet tasks work on the same CPU. -// - In ISR context when mutex can not be locked nothing is done before expired time check. -// WARNING: Care must be taken when selecting timeout values for trace calls from ISRs. Tracing module does not care about watchdogs when waiting on internal locks -// and when waiting for host to complete previous block reading, so if wating timeout value exceedes watchdog's one it can lead to system reboot. +// WARNING: Care must be taken when selecting timeout values for trace calls from ISRs. Tracing module does not care about watchdogs when waiting +// on internal locks and for host to complete previous block reading, so if timeout value exceedes watchdog's one it can lead to the system reboot. // 6. Timeouts -// ------------ +// =========== // Timeout mechanism is based on xthal_get_ccount() routine and supports timeout values in micorseconds. // There are two situations when task/ISR can be delayed by tracing API call. Timeout mechanism takes into account both conditions: @@ -135,7 +152,7 @@ // When wating for any of above conditions xthal_get_ccount() is called periodically to calculate time elapsed from trace API routine entry. When elapsed // time exceeds specified timeout value operation is canceled and ESP_ERR_TIMEOUT code is returned. -// ALSO SEE example usage of application tracing module in 'components/log/README.rst' +// ALSO SEE example usage of application tracing module in 'components/app_trace/README.rst' #include #include "soc/soc.h" @@ -149,25 +166,19 @@ #include "soc/timer_group_struct.h" #include "soc/timer_group_reg.h" #include "esp_app_trace.h" +#include "esp_app_trace_util.h" #if CONFIG_ESP32_APPTRACE_ENABLE -#define ESP_APPTRACE_DEBUG_STATS_ENABLE 0 -#define ESP_APPTRACE_BUF_HISTORY_DEPTH (16*100) - #define ESP_APPTRACE_MAX_VPRINTF_ARGS 256 +#define ESP_APPTRACE_HOST_BUF_SIZE 256 -#define ESP_APPTRACE_PRINT_LOCK_NONE 0 -#define ESP_APPTRACE_PRINT_LOCK_SEM 1 -#define ESP_APPTRACE_PRINT_LOCK_MUX 2 -#define ESP_APPTRACE_PRINT_LOCK ESP_APPTRACE_PRINT_LOCK_NONE//ESP_APPTRACE_PRINT_LOCK_SEM +#define ESP_APPTRACE_PRINT_LOCK 0 -#define ESP_APPTRACE_USE_LOCK_SEM 0 // 1 - semaphore (now may be broken), 0 - portMUX_TYPE - -#define LOG_LOCAL_LEVEL ESP_LOG_VERBOSE +#define LOG_LOCAL_LEVEL ESP_LOG_ERROR #include "esp_log.h" const static char *TAG = "esp_apptrace"; -#if ESP_APPTRACE_PRINT_LOCK != ESP_APPTRACE_PRINT_LOCK_NONE +#if ESP_APPTRACE_PRINT_LOCK #define ESP_APPTRACE_LOG( format, ... ) \ do { \ esp_apptrace_log_lock(); \ @@ -204,18 +215,28 @@ const static char *TAG = "esp_apptrace"; #define TRACEMEM_MUX_PROBLK1_APPBLK0 3 // TRAX is disabled, so we use its registers for our own purposes -// | 31..XXXXXX..24 | 23 .(host_connect). 23| 22..(block_id)..15 | 14..(block_len)..0 | +// | 31..XXXXXX..24 | 23 .(host_connect). 23 | 22 .(host_data). 22| 21..(block_id)..15 | 14..(block_len)..0 | #define ESP_APPTRACE_TRAX_CTRL_REG ERI_TRAX_DELAYCNT #define ESP_APPTRACE_TRAX_STAT_REG ERI_TRAX_TRIGGERPC #define ESP_APPTRACE_TRAX_BLOCK_LEN_MSK 0x7FFFUL #define ESP_APPTRACE_TRAX_BLOCK_LEN(_l_) ((_l_) & ESP_APPTRACE_TRAX_BLOCK_LEN_MSK) #define ESP_APPTRACE_TRAX_BLOCK_LEN_GET(_v_) ((_v_) & ESP_APPTRACE_TRAX_BLOCK_LEN_MSK) -#define ESP_APPTRACE_TRAX_BLOCK_ID_MSK 0xFFUL +#define ESP_APPTRACE_TRAX_BLOCK_ID_MSK 0x7FUL #define ESP_APPTRACE_TRAX_BLOCK_ID(_id_) (((_id_) & ESP_APPTRACE_TRAX_BLOCK_ID_MSK) << 15) #define ESP_APPTRACE_TRAX_BLOCK_ID_GET(_v_) (((_v_) >> 15) & ESP_APPTRACE_TRAX_BLOCK_ID_MSK) +#define ESP_APPTRACE_TRAX_HOST_DATA (1 << 22) #define ESP_APPTRACE_TRAX_HOST_CONNECT (1 << 23) +#if CONFIG_SYSVIEW_ENABLE +#define ESP_APPTRACE_USR_BLOCK_CORE(_cid_) (0) +#define ESP_APPTRACE_USR_BLOCK_LEN(_v_) (_v_) +#else +#define ESP_APPTRACE_USR_BLOCK_CORE(_cid_) ((_cid_) << 15) +#define ESP_APPTRACE_USR_BLOCK_LEN(_v_) (~(1 << 15) & (_v_)) +#endif +#define ESP_APPTRACE_USR_BLOCK_RAW_SZ(_s_) ((_s_) + sizeof(esp_tracedata_hdr_t)) + static volatile uint8_t *s_trax_blocks[] = { (volatile uint8_t *) 0x3FFFC000, (volatile uint8_t *) 0x3FFF8000 @@ -223,39 +244,21 @@ static volatile uint8_t *s_trax_blocks[] = { #define ESP_APPTRACE_TRAX_BLOCKS_NUM (sizeof(s_trax_blocks)/sizeof(s_trax_blocks[0])) -//#define ESP_APPTRACE_TRAX_BUFFER_SIZE (ESP_APPTRACE_TRAX_BLOCK_SIZE/4) +#define ESP_APPTRACE_TRAX_BLOCK_SIZE 0x4000UL -#define ESP_APPTRACE_TRAX_INBLOCK_START 0//(ESP_APPTRACE_TRAX_BLOCK_ID_MSK - 4) +#define ESP_APPTRACE_TRAX_INBLOCK_START 0 - -#define ESP_APPTRACE_TRAX_INBLOCK_MARKER_PTR_GET() (&s_trace_buf.trax.state.markers[s_trace_buf.trax.state.in_block % 2]) +#define ESP_APPTRACE_TRAX_INBLOCK_MARKER() (s_trace_buf.trax.state.markers[s_trace_buf.trax.state.in_block % 2]) +#define ESP_APPTRACE_TRAX_INBLOCK_MARKER_UPD(_v_) do {s_trace_buf.trax.state.markers[s_trace_buf.trax.state.in_block % 2] += (_v_);}while(0) #define ESP_APPTRACE_TRAX_INBLOCK_GET() (&s_trace_buf.trax.blocks[s_trace_buf.trax.state.in_block % 2]) -#if ESP_APPTRACE_DEBUG_STATS_ENABLE == 1 -/** keeps info about apptrace API (write/get buffer) caller and internal module's data related to that call - * NOTE: used for module debug purposes, currently this functionality is partially broken, - * but can be useful in future - */ -typedef struct { - uint32_t hnd; // task/ISR handle - uint32_t ts; // timestamp - uint32_t stamp; // test (user) trace buffer stamp - uint32_t in_block; // TRAX input block ID - uint32_t eri_len[2]; // contents of ERI control register upon entry to / exit from API routine - uint32_t wr_err; // number of trace write errors -} esp_trace_buffer_wr_hitem_t; +//TODO: menuconfig +#define ESP_APPTRACE_DOWN_BUF_SIZE 32UL -/** apptrace API calls history. History is organized as ring buffer*/ -typedef struct { - uint32_t hist_rd; // the first history entry index - uint32_t hist_wr; // the last history entry index - esp_trace_buffer_wr_hitem_t hist[ESP_APPTRACE_BUF_HISTORY_DEPTH]; // history data -} esp_trace_buffer_wr_stats_t; - -/** trace module stats */ -typedef struct { - esp_trace_buffer_wr_stats_t wr; -} esp_trace_buffer_stats_t; +#if CONFIG_SYSVIEW_ENABLE +#define ESP_APPTRACE_USR_DATA_LEN_MAX 255UL +#else +#define ESP_APPTRACE_USR_DATA_LEN_MAX (ESP_APPTRACE_TRAX_BLOCK_SIZE - sizeof(esp_tracedata_hdr_t)) #endif /** Trace data header. Every user data chunk is prepended with this header. @@ -265,254 +268,114 @@ typedef struct { * In this case host SW will see that wr_sz < block_sz and will report error. */ typedef struct { +#if CONFIG_SYSVIEW_ENABLE + uint8_t block_sz; // size of allocated block for user data + uint8_t wr_sz; // size of actually written data +#else uint16_t block_sz; // size of allocated block for user data uint16_t wr_sz; // size of actually written data +#endif } esp_tracedata_hdr_t; +/** TODO: docs + */ +typedef struct { + uint16_t block_sz; // size of allocated block for user data +} esp_hostdata_hdr_t; + /** TRAX HW transport state */ typedef struct { uint32_t in_block; // input block ID + // TODO: change to uint16_t uint32_t markers[ESP_APPTRACE_TRAX_BLOCKS_NUM]; // block filling level markers -#if ESP_APPTRACE_DEBUG_STATS_ENABLE == 1 - esp_trace_buffer_stats_t stats; // stats -#endif } esp_apptrace_trax_state_t; /** memory block parameters */ typedef struct { uint8_t *start; // start address - uint32_t sz; // size + uint16_t sz; // size } esp_apptrace_mem_block_t; /** TRAX HW transport data */ typedef struct { volatile esp_apptrace_trax_state_t state; // state esp_apptrace_mem_block_t blocks[ESP_APPTRACE_TRAX_BLOCKS_NUM]; // memory blocks +#if CONFIG_ESP32_APPTRACE_PENDING_DATA_SIZE_MAX > 0 + // ring buffer control struct for pending user blocks + esp_apptrace_rb_t rb_pend; + // storage for pending user blocks + uint8_t pending_data[CONFIG_ESP32_APPTRACE_PENDING_DATA_SIZE_MAX + 1]; +#if CONFIG_ESP32_APPTRACE_PENDING_DATA_SIZE_MAX > ESP_APPTRACE_TRAX_BLOCK_SIZE + // ring buffer control struct for pending user data chunks sizes, + // every chunk contains whole number of user blocks and fit into TRAX memory block + esp_apptrace_rb_t rb_pend_chunk_sz; + // storage for above ring buffer data + uint16_t pending_chunk_sz[CONFIG_ESP32_APPTRACE_PENDING_DATA_SIZE_MAX/ESP_APPTRACE_TRAX_BLOCK_SIZE + 2]; + // current (accumulated) pending user data chunk size + uint16_t cur_pending_chunk_sz; +#endif +#endif } esp_apptrace_trax_data_t; -/** tracing module synchronization lock */ -typedef struct { - volatile unsigned int irq_stat; // local (on 1 CPU) IRQ state - portMUX_TYPE portmux; // mux for synchronization -} esp_apptrace_lock_t; - -#define ESP_APPTRACE_MUX_GET(_m_) (&(_m_)->portmux) - /** tracing module internal data */ typedef struct { -#if ESP_APPTRACE_USE_LOCK_SEM == 1 - SemaphoreHandle_t lock; -#else esp_apptrace_lock_t lock; // sync lock -#endif uint8_t inited; // module initialization state flag + // ring buffer control struct for data from host (down buffer) + esp_apptrace_rb_t rb_down; + // storage for above ring buffer data + uint8_t down_buf[ESP_APPTRACE_DOWN_BUF_SIZE + 1]; esp_apptrace_trax_data_t trax; // TRAX HW transport data } esp_apptrace_buffer_t; -/** waiting timeout data */ -typedef struct { - uint32_t start; // waiting start (in ticks) - uint32_t tmo; // timeout (in us) -} esp_apptrace_tmo_t; +static esp_apptrace_buffer_t s_trace_buf; -static esp_apptrace_buffer_t s_trace_buf; - -#if ESP_APPTRACE_PRINT_LOCK == ESP_APPTRACE_PRINT_LOCK_SEM -static SemaphoreHandle_t s_log_lock; -#elif ESP_APPTRACE_PRINT_LOCK == ESP_APPTRACE_PRINT_LOCK_MUX -static esp_apptrace_lock_t s_log_lock; +#if ESP_APPTRACE_PRINT_LOCK +static esp_apptrace_lock_t s_log_lock = {.irq_stat = 0, .portmux = portMUX_INITIALIZER_UNLOCKED}; #endif -static inline void esp_apptrace_tmo_init(esp_apptrace_tmo_t *tmo, uint32_t user_tmo) -{ - tmo->start = xthal_get_ccount(); - tmo->tmo = user_tmo; -} - -static esp_err_t esp_apptrace_tmo_check(esp_apptrace_tmo_t *tmo) -{ - unsigned cur, elapsed; - - if (tmo->tmo != ESP_APPTRACE_TMO_INFINITE) { - cur = xthal_get_ccount(); - if (tmo->start <= cur) { - elapsed = cur - tmo->start; - } else { - elapsed = 0xFFFFFFFF - tmo->start + cur; - } - if (ESP_APPTRACE_CPUTICKS2US(elapsed) >= tmo->tmo) { - return ESP_ERR_TIMEOUT; - } - } - return ESP_OK; -} - -#if ESP_APPTRACE_PRINT_LOCK == ESP_APPTRACE_PRINT_LOCK_MUX || ESP_APPTRACE_USE_LOCK_SEM == 0 -static inline void esp_apptrace_mux_init(esp_apptrace_lock_t *mux) -{ - ESP_APPTRACE_MUX_GET(mux)->mux = portMUX_FREE_VAL; - mux->irq_stat = 0; -} - -static esp_err_t esp_apptrace_lock_take(esp_apptrace_lock_t *mux, uint32_t tmo) -{ - uint32_t res = ~portMUX_FREE_VAL; - esp_apptrace_tmo_t sleeping_tmo; - - esp_apptrace_tmo_init(&sleeping_tmo, tmo); - while (1) { - res = (xPortGetCoreID() << portMUX_VAL_SHIFT) | portMUX_MAGIC_VAL; - // first disable IRQs on this CPU, this will prevent current task from been - // preempted by higher prio tasks, otherwise deadlock can happen: - // when lower prio task took mux and then preempted by higher prio one which also tries to - // get mux with INFINITE timeout - unsigned int irq_stat = portENTER_CRITICAL_NESTED(); - // Now try to lock mux - uxPortCompareSet(&ESP_APPTRACE_MUX_GET(mux)->mux, portMUX_FREE_VAL, &res); - if (res == portMUX_FREE_VAL) { - // do not enable IRQs, we will held them disabled until mux is unlocked - // we do not need to flush cache region for mux->irq_stat because it is used - // to hold and restore IRQ state only for CPU which took mux, other CPUs will not use this value - mux->irq_stat = irq_stat; - break; - } - // if mux is locked by other task/ISR enable IRQs and let other guys work - portEXIT_CRITICAL_NESTED(irq_stat); - - if (!xPortInIsrContext()) { - portYIELD(); - } - - int err = esp_apptrace_tmo_check(&sleeping_tmo); - if (err != ESP_OK) { - return err; - } - } - - return ESP_OK; -} - -esp_err_t esp_apptrace_mux_give(esp_apptrace_lock_t *mux) -{ - esp_err_t ret = ESP_OK; - uint32_t res = 0; - unsigned int irq_stat; - - res = portMUX_FREE_VAL; - - // first of all save a copy of IRQ status for this locker because uxPortCompareSet will unlock mux and tasks/ISRs - // from other core can overwrite mux->irq_stat - irq_stat = mux->irq_stat; - uxPortCompareSet(&ESP_APPTRACE_MUX_GET(mux)->mux, (xPortGetCoreID() << portMUX_VAL_SHIFT) | portMUX_MAGIC_VAL, &res); - // enable local interrupts - portEXIT_CRITICAL_NESTED(irq_stat); - - if ( ((res & portMUX_VAL_MASK) >> portMUX_VAL_SHIFT) == xPortGetCoreID() ) { - // nothing to do - } else if ( res == portMUX_FREE_VAL ) { - ret = ESP_FAIL; // should never get here - } else { - ret = ESP_FAIL; // should never get here - } - return ret; -} -#endif - -static inline esp_err_t esp_apptrace_log_init() -{ -#if ESP_APPTRACE_PRINT_LOCK == ESP_APPTRACE_PRINT_LOCK_SEM - s_log_lock = xSemaphoreCreateBinary(); - if (!s_log_lock) { - ets_printf("%s: Failed to create print lock sem!", TAG); - return ESP_FAIL; - } - xSemaphoreGive(s_log_lock); -#elif ESP_APPTRACE_PRINT_LOCK == ESP_APPTRACE_PRINT_LOCK_MUX - esp_apptrace_mux_init(&s_log_lock); -#endif - return ESP_OK; -} - -static inline void esp_apptrace_log_cleanup() -{ -#if ESP_APPTRACE_PRINT_LOCK == ESP_APPTRACE_PRINT_LOCK_SEM - vSemaphoreDelete(s_log_lock); -#endif -} +static uint16_t esp_apptrace_trax_write_down_buffer_nolock(uint8_t *data, uint16_t size); +static esp_err_t esp_apptrace_trax_flush(uint32_t min_sz, uint32_t tmo); static inline int esp_apptrace_log_lock() { -#if ESP_APPTRACE_PRINT_LOCK == ESP_APPTRACE_PRINT_LOCK_SEM - BaseType_t ret; - if (xPortInIsrContext()) { - ret = xSemaphoreTakeFromISR(s_print_lock, NULL); - } else { - ret = xSemaphoreTake(s_print_lock, portMAX_DELAY); - } - return ret; -#elif ESP_APPTRACE_PRINT_LOCK == ESP_APPTRACE_PRINT_LOCK_MUX +#if ESP_APPTRACE_PRINT_LOCK int ret = esp_apptrace_lock_take(&s_log_lock, ESP_APPTRACE_TMO_INFINITE); return ret; -#endif +#else return 0; +#endif } static inline void esp_apptrace_log_unlock() { -#if ESP_APPTRACE_PRINT_LOCK == ESP_APPTRACE_PRINT_LOCK_SEM - if (xPortInIsrContext()) { - xSemaphoreGiveFromISR(s_log_lock, NULL); - } else { - xSemaphoreGive(s_log_lock); - } -#elif ESP_APPTRACE_PRINT_LOCK == ESP_APPTRACE_PRINT_LOCK_MUX - esp_apptrace_mux_give(&s_log_lock); + #if ESP_APPTRACE_PRINT_LOCK + esp_apptrace_lock_give(&s_log_lock); #endif } -esp_err_t esp_apptrace_lock_init() +esp_err_t esp_apptrace_lock_initialize() { -#if ESP_APPTRACE_USE_LOCK_SEM == 1 - s_trace_buf.lock = xSemaphoreCreateBinary(); - if (!s_trace_buf.lock) { - ESP_APPTRACE_LOGE("Failed to create lock!"); - return ESP_FAIL; - } - xSemaphoreGive(s_trace_buf.lock); -#else - esp_apptrace_mux_init(&s_trace_buf.lock); +#if CONFIG_SYSVIEW_ENABLE == 0 + esp_apptrace_lock_init(&s_trace_buf.lock); #endif return ESP_OK; } -esp_err_t esp_apptrace_lock_cleanup() +esp_err_t inline esp_apptrace_lock_cleanup() { -#if ESP_APPTRACE_USE_LOCK_SEM == 1 - vSemaphoreDelete(s_trace_buf.lock); -#endif return ESP_OK; } esp_err_t esp_apptrace_lock(uint32_t *tmo) { +#if CONFIG_SYSVIEW_ENABLE == 0 unsigned cur, elapsed, start = xthal_get_ccount(); -#if ESP_APPTRACE_USE_LOCK_SEM == 1 - BaseType_t ret; - if (xPortInIsrContext()) { - ret = xSemaphoreTakeFromISR(s_trace_buf.lock, NULL); - } else { - ret = xSemaphoreTake(s_trace_buf.lock, portTICK_PERIOD_MS * (*tmo) / 1000); - } - if (ret != pdTRUE) { - return ESP_FAIL; - } -#else esp_err_t ret = esp_apptrace_lock_take(&s_trace_buf.lock, *tmo); if (ret != ESP_OK) { return ESP_FAIL; } -#endif // decrease tmo by actual waiting time cur = xthal_get_ccount(); if (start <= cur) { @@ -525,21 +388,15 @@ esp_err_t esp_apptrace_lock(uint32_t *tmo) } else { *tmo -= ESP_APPTRACE_CPUTICKS2US(elapsed); } - +#endif return ESP_OK; } esp_err_t esp_apptrace_unlock() { esp_err_t ret = ESP_OK; -#if ESP_APPTRACE_USE_LOCK_SEM == 1 - if (xPortInIsrContext()) { - xSemaphoreGiveFromISR(s_trace_buf.lock, NULL); - } else { - xSemaphoreGive(s_trace_buf.lock); - } -#else - ret = esp_apptrace_mux_give(&s_trace_buf.lock); +#if CONFIG_SYSVIEW_ENABLE == 0 + ret = esp_apptrace_lock_give(&s_trace_buf.lock); #endif return ret; } @@ -556,6 +413,46 @@ static void esp_apptrace_trax_init() ESP_APPTRACE_LOGI("Initialized TRAX on CPU%d", xPortGetCoreID()); } +#if CONFIG_ESP32_APPTRACE_PENDING_DATA_SIZE_MAX > ESP_APPTRACE_TRAX_BLOCK_SIZE +// keep the size of buffered data for copying to TRAX mem block. +// Only whole user blocks should be copied from buffer to TRAX block upon the switch +static void esp_apptrace_trax_pend_chunk_sz_update(uint16_t size) +{ + ESP_APPTRACE_LOGD("Update chunk enter %d/%d w-r-s %d-%d-%d", s_trace_buf.trax.cur_pending_chunk_sz, size, + s_trace_buf.trax.rb_pend_chunk_sz.wr, s_trace_buf.trax.rb_pend_chunk_sz.rd, s_trace_buf.trax.rb_pend_chunk_sz.cur_size); + + if ((uint32_t)s_trace_buf.trax.cur_pending_chunk_sz + (uint32_t)size <= ESP_APPTRACE_TRAX_BLOCK_SIZE) { + ESP_APPTRACE_LOGD("Update chunk %d/%d", s_trace_buf.trax.cur_pending_chunk_sz, size); + s_trace_buf.trax.cur_pending_chunk_sz += size; + } else { + uint16_t *chunk_sz = (uint16_t *)esp_apptrace_rb_produce(&s_trace_buf.trax.rb_pend_chunk_sz, sizeof(uint16_t)); + if (!chunk_sz) { + assert(false && "Failed to alloc pended chunk sz slot!"); + } else { + ESP_APPTRACE_LOGD("Update new chunk %d/%d", s_trace_buf.trax.cur_pending_chunk_sz, size); + *chunk_sz = s_trace_buf.trax.cur_pending_chunk_sz; + s_trace_buf.trax.cur_pending_chunk_sz = size; + } + } +} + +static uint16_t esp_apptrace_trax_pend_chunk_sz_get() +{ + uint16_t ch_sz; + ESP_APPTRACE_LOGD("Get chunk enter %d w-r-s %d-%d-%d", s_trace_buf.trax.cur_pending_chunk_sz, + s_trace_buf.trax.rb_pend_chunk_sz.wr, s_trace_buf.trax.rb_pend_chunk_sz.rd, s_trace_buf.trax.rb_pend_chunk_sz.cur_size); + + uint16_t *chunk_sz = (uint16_t *)esp_apptrace_rb_consume(&s_trace_buf.trax.rb_pend_chunk_sz, sizeof(uint16_t)); + if (!chunk_sz) { + ch_sz = s_trace_buf.trax.cur_pending_chunk_sz; + s_trace_buf.trax.cur_pending_chunk_sz = 0; + } else { + ch_sz = *chunk_sz; + } + return ch_sz; +} +#endif + // assumed to be protected by caller from multi-core/thread access static esp_err_t esp_apptrace_trax_block_switch() { @@ -573,19 +470,13 @@ static esp_err_t esp_apptrace_trax_block_switch() eri_write(ESP_APPTRACE_TRAX_STAT_REG, (uint32_t)&__esp_apptrace_trax_eri_updated); uint32_t ctrl_reg = eri_read(ESP_APPTRACE_TRAX_CTRL_REG); -#if ESP_APPTRACE_DEBUG_STATS_ENABLE == 1 - if (s_trace_buf.state.stats.wr.hist_wr < ESP_APPTRACE_BUF_HISTORY_DEPTH) { - esp_trace_buffer_wr_hitem_t *hi = (esp_trace_buffer_wr_hitem_t *)&s_trace_buf.state.stats.wr.hist[s_trace_buf.state.stats.wr.hist_wr - 1]; - hi->eri_len[1] = ctrl_reg; - } -#endif uint32_t host_connected = ESP_APPTRACE_TRAX_HOST_CONNECT & ctrl_reg; if (host_connected) { uint32_t acked_block = ESP_APPTRACE_TRAX_BLOCK_ID_GET(ctrl_reg); uint32_t host_to_read = ESP_APPTRACE_TRAX_BLOCK_LEN_GET(ctrl_reg); if (host_to_read != 0 || acked_block != (s_trace_buf.trax.state.in_block & ESP_APPTRACE_TRAX_BLOCK_ID_MSK)) { - // ESP_APPTRACE_LOGE("HC[%d]: Can not switch %x %d %x %x/%lx", xPortGetCoreID(), ctrl_reg, host_to_read, acked_block, - // s_trace_buf.trax.state.in_block & ESP_APPTRACE_TRAX_BLOCK_ID_MSK, s_trace_buf.trax.state.in_block); + ESP_APPTRACE_LOGD("HC[%d]: Can not switch %x %d %x %x/%lx, m %d", xPortGetCoreID(), ctrl_reg, host_to_read, acked_block, + s_trace_buf.trax.state.in_block & ESP_APPTRACE_TRAX_BLOCK_ID_MSK, s_trace_buf.trax.state.in_block, s_trace_buf.trax.state.markers[prev_block_num]); res = ESP_ERR_NO_MEM; goto _on_func_exit; } @@ -595,12 +486,62 @@ static esp_err_t esp_apptrace_trax_block_switch() s_trace_buf.trax.state.in_block++; DPORT_WRITE_PERI_REG(DPORT_TRACEMEM_MUX_MODE_REG, new_block_num ? TRACEMEM_MUX_BLK0_ONLY : TRACEMEM_MUX_BLK1_ONLY); + // handle data from host + esp_hostdata_hdr_t *hdr = (esp_hostdata_hdr_t *)s_trace_buf.trax.blocks[new_block_num].start; + if (ctrl_reg & ESP_APPTRACE_TRAX_HOST_DATA && hdr->block_sz > 0) { + // TODO: add support for multiple blocks from host, currently there is no need for that + uint8_t *p = s_trace_buf.trax.blocks[new_block_num].start + s_trace_buf.trax.blocks[new_block_num].sz; + ESP_APPTRACE_LOGD("Recvd %d bytes from host [%x %x %x .. %x %x]", hdr->block_sz, + *(s_trace_buf.trax.blocks[new_block_num].start+0), *(s_trace_buf.trax.blocks[new_block_num].start+1), + *(s_trace_buf.trax.blocks[new_block_num].start+2), *(p-2), *(p-1)); + uint32_t sz = esp_apptrace_trax_write_down_buffer_nolock((uint8_t *)(hdr+1), hdr->block_sz); + if (sz != hdr->block_sz) { + ESP_APPTRACE_LOGE("Failed to write %d bytes to down buffer!", hdr->block_sz - sz); + } + hdr->block_sz = 0; + } +#if CONFIG_ESP32_APPTRACE_PENDING_DATA_SIZE_MAX > 0 + // copy pending data to TRAX block if any +#if CONFIG_ESP32_APPTRACE_PENDING_DATA_SIZE_MAX > ESP_APPTRACE_TRAX_BLOCK_SIZE + uint16_t max_chunk_sz = esp_apptrace_trax_pend_chunk_sz_get(); +#else + uint16_t max_chunk_sz = s_trace_buf.trax.blocks[new_block_num].sz; +#endif + while (s_trace_buf.trax.state.markers[new_block_num] < max_chunk_sz) { + uint32_t read_sz = esp_apptrace_rb_read_size_get(&s_trace_buf.trax.rb_pend); + if (read_sz == 0) { +#if CONFIG_ESP32_APPTRACE_PENDING_DATA_SIZE_MAX > ESP_APPTRACE_TRAX_BLOCK_SIZE + /* theres is a bug: esp_apptrace_trax_pend_chunk_sz_get returned wrong value, + it must be greater or equal to one returned by esp_apptrace_rb_read_size_get */ + ESP_APPTRACE_LOGE("No pended bytes, must be > 0 and <= %d!", max_chunk_sz); +#endif + break; + } + if (read_sz > max_chunk_sz - s_trace_buf.trax.state.markers[new_block_num]) { + read_sz = max_chunk_sz - s_trace_buf.trax.state.markers[new_block_num]; + } + uint8_t *ptr = esp_apptrace_rb_consume(&s_trace_buf.trax.rb_pend, read_sz); + if (!ptr) { + assert(false && "Failed to consume pended bytes!!"); + break; + } + if (host_connected) { + ESP_APPTRACE_LOGD("Pump %d pend bytes [%x %x %x %x : %x %x %x %x : %x %x %x %x : %x %x...%x %x]", + read_sz, *(ptr+0), *(ptr+1), *(ptr+2), *(ptr+3), *(ptr+4), + *(ptr+5), *(ptr+6), *(ptr+7), *(ptr+8), *(ptr+9), *(ptr+10), *(ptr+11), *(ptr+12), *(ptr+13), *(ptr+read_sz-2), *(ptr+read_sz-1)); + } + memcpy(s_trace_buf.trax.blocks[new_block_num].start + s_trace_buf.trax.state.markers[new_block_num], ptr, read_sz); + s_trace_buf.trax.state.markers[new_block_num] += read_sz; + } +#endif eri_write(ESP_APPTRACE_TRAX_CTRL_REG, ESP_APPTRACE_TRAX_BLOCK_ID(s_trace_buf.trax.state.in_block) | host_connected | ESP_APPTRACE_TRAX_BLOCK_LEN(s_trace_buf.trax.state.markers[prev_block_num])); _on_func_exit: // exit ERI update critical section eri_write(ESP_APPTRACE_TRAX_STAT_REG, 0x0); + // TODO: currently host sets breakpoint, use break instruction to stop; + // it will allow to use ESP_APPTRACE_TRAX_STAT_REG for other purposes asm volatile ( " .global __esp_apptrace_trax_eri_updated\n" "__esp_apptrace_trax_eri_updated:\n"); // host will set bp here to resolve collision at streaming start @@ -623,71 +564,195 @@ static esp_err_t esp_apptrace_trax_block_switch_waitus(uint32_t tmo) return res; } -static uint8_t *esp_apptrace_trax_get_buffer(size_t size, uint32_t *tmo) +static inline void esp_apptrace_trax_down_buf_init() { - uint8_t *buf_ptr = NULL; - volatile uint32_t *cur_block_marker; - esp_apptrace_mem_block_t *cur_block; + esp_apptrace_rb_init(&s_trace_buf.rb_down, s_trace_buf.down_buf, sizeof(s_trace_buf.down_buf)); +} +static inline uint8_t *esp_apptrace_trax_get_down_rdptr(uint32_t *size, uint32_t *tmo) +{ int res = esp_apptrace_lock(tmo); if (res != ESP_OK) { return NULL; } -#if ESP_APPTRACE_DEBUG_STATS_ENABLE == 1 - esp_trace_buffer_wr_hitem_t *hi = NULL; - if (s_trace_buf.state.stats.wr.hist_wr < ESP_APPTRACE_BUF_HISTORY_DEPTH) { - hi = (esp_trace_buffer_wr_hitem_t *)&s_trace_buf.state.stats.wr.hist[s_trace_buf.state.stats.wr.hist_wr++]; - hi->hnd = *(uint32_t *)(buf + 0); - hi->ts = *(uint32_t *)(buf + sizeof(uint32_t)); - hi->stamp = *(buf + 2 * sizeof(uint32_t)); - hi->in_block = s_trace_buf.state.in_block; - hi->wr_err = 0; - hi->eri_len[0] = eri_read(ESP_APPTRACE_TRAX_CTRL_REG); - if (s_trace_buf.state.stats.wr.hist_wr == ESP_APPTRACE_BUF_HISTORY_DEPTH) { - s_trace_buf.state.stats.wr.hist_wr = 0; - } - if (s_trace_buf.state.stats.wr.hist_wr == s_trace_buf.state.stats.wr.hist_rd) { - s_trace_buf.state.stats.wr.hist_rd++; - if (s_trace_buf.state.stats.wr.hist_rd == ESP_APPTRACE_BUF_HISTORY_DEPTH) { - s_trace_buf.state.stats.wr.hist_rd = 0; - } - } - } -#endif - - cur_block_marker = ESP_APPTRACE_TRAX_INBLOCK_MARKER_PTR_GET(); - cur_block = ESP_APPTRACE_TRAX_INBLOCK_GET(); - - if (*cur_block_marker + size + sizeof(esp_tracedata_hdr_t) >= cur_block->sz) { - // flush data, we can not unlock apptrace until we have buffer for all user data - // otherwise other tasks/ISRs can get control and write their data between chunks of this data - res = esp_apptrace_trax_block_switch_waitus(/*size + sizeof(esp_tracedata_hdr_t),*/*tmo); + // may need to flush + uint32_t ctrl_reg = eri_read(ESP_APPTRACE_TRAX_CTRL_REG); + if (ctrl_reg & ESP_APPTRACE_TRAX_HOST_DATA) { + ESP_APPTRACE_LOGD("force flush"); + res = esp_apptrace_trax_block_switch_waitus(*tmo); if (res != ESP_OK) { - if (esp_apptrace_unlock() != ESP_OK) { - ESP_APPTRACE_LOGE("Failed to unlock apptrace data!"); - // there is a bug, should never get here - } - return NULL; + ESP_APPTRACE_LOGE("Failed to switch to another block to recv data from host!"); + } + } + uint8_t *ptr = NULL; + uint32_t sz = esp_apptrace_rb_read_size_get(&s_trace_buf.rb_down); + if (sz > 0) { + ptr = esp_apptrace_rb_consume(&s_trace_buf.rb_down, sz > *size ? *size : sz); + if (!ptr) { + assert(false && "Failed to consume bytes from down buffer!"); + } + } + *size = sz; + + if (esp_apptrace_unlock() != ESP_OK) { + assert(false && "Failed to unlock apptrace data!"); + } + return ptr; +} + +static inline esp_err_t esp_apptrace_trax_put_down_rdptr(uint8_t *ptr, uint32_t size, uint32_t *tmo) +{ + /* nothing todo */ + return ESP_OK; +} + +static uint16_t esp_apptrace_trax_write_down_buffer_nolock(uint8_t *data, uint16_t size) +{ + uint8_t *ptr = esp_apptrace_rb_produce(&s_trace_buf.rb_down, size); + if (ptr) { + memcpy(ptr, data, size); + } else { + return 0; + } + return size; +} + +static inline uint8_t *esp_apptrace_data_header_init(uint8_t *ptr, uint16_t usr_size) +{ + // it is safe to use xPortGetCoreID() in macro call because arg is used only once inside it + ((esp_tracedata_hdr_t *)ptr)->block_sz = ESP_APPTRACE_USR_BLOCK_CORE(xPortGetCoreID()) | usr_size; + ((esp_tracedata_hdr_t *)ptr)->wr_sz = 0; + return ptr + sizeof(esp_tracedata_hdr_t); +} + +static inline uint8_t *esp_apptrace_trax_wait4buf(uint16_t size, uint32_t tmo, int *pended) +{ + uint8_t *ptr = NULL; + + int res = esp_apptrace_trax_block_switch_waitus(tmo); + if (res != ESP_OK) { + return NULL; + } + // check if we still have pending data +#if CONFIG_ESP32_APPTRACE_PENDING_DATA_SIZE_MAX > 0 + if (esp_apptrace_rb_read_size_get(&s_trace_buf.trax.rb_pend) > 0) { + // if after TRAX block switch still have pending data (not all pending data have been pumped to TRAX block) + // alloc new pending buffer + *pended = 1; + ptr = esp_apptrace_rb_produce(&s_trace_buf.trax.rb_pend, size); + if (!ptr) { + ESP_APPTRACE_LOGE("Failed to alloc pend buf 1: w-r-s %d-%d-%d!", s_trace_buf.trax.rb_pend.wr, s_trace_buf.trax.rb_pend.rd, s_trace_buf.trax.rb_pend.cur_size); + } + } else +#endif + { + // update block pointers + if (ESP_APPTRACE_TRAX_INBLOCK_MARKER() + size > ESP_APPTRACE_TRAX_INBLOCK_GET()->sz) { +#if CONFIG_ESP32_APPTRACE_PENDING_DATA_SIZE_MAX > 0 + *pended = 1; + ptr = esp_apptrace_rb_produce(&s_trace_buf.trax.rb_pend, size); + if (ptr == NULL) { + ESP_APPTRACE_LOGE("Failed to alloc pend buf 2: w-r-s %d-%d-%d!", s_trace_buf.trax.rb_pend.wr, s_trace_buf.trax.rb_pend.rd, s_trace_buf.trax.rb_pend.cur_size); + } +#endif + } else { + *pended = 0; + ptr = ESP_APPTRACE_TRAX_INBLOCK_GET()->start + ESP_APPTRACE_TRAX_INBLOCK_MARKER(); } - // we switched to new block, update TRAX block pointers - cur_block_marker = ESP_APPTRACE_TRAX_INBLOCK_MARKER_PTR_GET(); - cur_block = ESP_APPTRACE_TRAX_INBLOCK_GET(); } - buf_ptr = cur_block->start + *cur_block_marker; - ((esp_tracedata_hdr_t *)buf_ptr)->block_sz = size; - ((esp_tracedata_hdr_t *)buf_ptr)->wr_sz = 0; + return ptr; +} - *cur_block_marker += size + sizeof(esp_tracedata_hdr_t); +static uint8_t *esp_apptrace_trax_get_buffer(size_t size, uint32_t *tmo) +{ + uint8_t *buf_ptr = NULL; + + if (size > ESP_APPTRACE_USR_DATA_LEN_MAX) { + ESP_APPTRACE_LOGE("Too large user data size %d!", size); + return NULL; + } + + int res = esp_apptrace_lock(tmo); + if (res != ESP_OK) { + return NULL; + } + // check for data in the pending buffer +#if CONFIG_ESP32_APPTRACE_PENDING_DATA_SIZE_MAX > 0 + if (esp_apptrace_rb_read_size_get(&s_trace_buf.trax.rb_pend) > 0) { + // if we have buffered data try to switch TRAX block + esp_apptrace_trax_block_switch(); + // if switch was successful, part or all pended data have been copied to TRAX block + } + if (esp_apptrace_rb_read_size_get(&s_trace_buf.trax.rb_pend) > 0) { + // if we have buffered data alloc new pending buffer + ESP_APPTRACE_LOGD("Get %d bytes from PEND buffer", size); + buf_ptr = esp_apptrace_rb_produce(&s_trace_buf.trax.rb_pend, ESP_APPTRACE_USR_BLOCK_RAW_SZ(size)); + if (buf_ptr == NULL) { + int pended_buf; + buf_ptr = esp_apptrace_trax_wait4buf(ESP_APPTRACE_USR_BLOCK_RAW_SZ(size), *tmo, &pended_buf); + if (buf_ptr) { + if (pended_buf) { +#if CONFIG_ESP32_APPTRACE_PENDING_DATA_SIZE_MAX > ESP_APPTRACE_TRAX_BLOCK_SIZE + esp_apptrace_trax_pend_chunk_sz_update(ESP_APPTRACE_USR_BLOCK_RAW_SZ(size)); +#endif + } else { + ESP_APPTRACE_LOGD("Got %d bytes from TRAX buffer", size); + // update cur block marker + ESP_APPTRACE_TRAX_INBLOCK_MARKER_UPD(ESP_APPTRACE_USR_BLOCK_RAW_SZ(size)); + } + } + } else { +#if CONFIG_ESP32_APPTRACE_PENDING_DATA_SIZE_MAX > ESP_APPTRACE_TRAX_BLOCK_SIZE + esp_apptrace_trax_pend_chunk_sz_update(ESP_APPTRACE_USR_BLOCK_RAW_SZ(size)); +#endif + } + } else +#endif + if (ESP_APPTRACE_TRAX_INBLOCK_MARKER() + ESP_APPTRACE_USR_BLOCK_RAW_SZ(size) > ESP_APPTRACE_TRAX_INBLOCK_GET()->sz) { +#if CONFIG_ESP32_APPTRACE_PENDING_DATA_SIZE_MAX > 0 + ESP_APPTRACE_LOGD("TRAX full. Get %d bytes from PEND buffer", size); + buf_ptr = esp_apptrace_rb_produce(&s_trace_buf.trax.rb_pend, ESP_APPTRACE_USR_BLOCK_RAW_SZ(size)); + if (buf_ptr) { +#if CONFIG_ESP32_APPTRACE_PENDING_DATA_SIZE_MAX > ESP_APPTRACE_TRAX_BLOCK_SIZE + esp_apptrace_trax_pend_chunk_sz_update(ESP_APPTRACE_USR_BLOCK_RAW_SZ(size)); +#endif + } +#endif + if (buf_ptr == NULL) { + int pended_buf; + ESP_APPTRACE_LOGD("TRAX full. Get %d bytes from pend buffer", size); + buf_ptr = esp_apptrace_trax_wait4buf(ESP_APPTRACE_USR_BLOCK_RAW_SZ(size), *tmo, &pended_buf); + if (buf_ptr) { + if (pended_buf) { +#if CONFIG_ESP32_APPTRACE_PENDING_DATA_SIZE_MAX > ESP_APPTRACE_TRAX_BLOCK_SIZE + esp_apptrace_trax_pend_chunk_sz_update(ESP_APPTRACE_USR_BLOCK_RAW_SZ(size)); +#endif + } else { + ESP_APPTRACE_LOGD("Got %d bytes from TRAX buffer", size); + // update cur block marker + ESP_APPTRACE_TRAX_INBLOCK_MARKER_UPD(ESP_APPTRACE_USR_BLOCK_RAW_SZ(size)); + } + } + } + } else { + ESP_APPTRACE_LOGD("Get %d bytes from TRAX buffer!", size); + // fit to curr TRAX nlock + buf_ptr = ESP_APPTRACE_TRAX_INBLOCK_GET()->start + ESP_APPTRACE_TRAX_INBLOCK_MARKER(); + // update cur block marker + ESP_APPTRACE_TRAX_INBLOCK_MARKER_UPD(ESP_APPTRACE_USR_BLOCK_RAW_SZ(size)); + } + if (buf_ptr) { + buf_ptr = esp_apptrace_data_header_init(buf_ptr, size); + } // now we can safely unlock apptrace to allow other tasks/ISRs to get other buffers and write their data if (esp_apptrace_unlock() != ESP_OK) { - ESP_APPTRACE_LOGE("Failed to unlock apptrace data!"); - // there is a bug, should never get here + assert(false && "Failed to unlock apptrace data!"); } - return buf_ptr + sizeof(esp_tracedata_hdr_t); + return buf_ptr; } static esp_err_t esp_apptrace_trax_put_buffer(uint8_t *ptr, uint32_t *tmo) @@ -709,19 +774,20 @@ static esp_err_t esp_apptrace_trax_put_buffer(uint8_t *ptr, uint32_t *tmo) static esp_err_t esp_apptrace_trax_flush(uint32_t min_sz, uint32_t tmo) { - volatile uint32_t *in_block_marker; int res = ESP_OK; - in_block_marker = ESP_APPTRACE_TRAX_INBLOCK_MARKER_PTR_GET(); - if (*in_block_marker > min_sz) { - ESP_APPTRACE_LOGD("Wait until block switch for %u us", tmo); - res = esp_apptrace_trax_block_switch_waitus(/*0 query any size,*/tmo); + if (ESP_APPTRACE_TRAX_INBLOCK_MARKER() < min_sz) { + ESP_APPTRACE_LOGI("Ignore flush request for min %d bytes. Bytes in TRAX block: %d.", min_sz, ESP_APPTRACE_TRAX_INBLOCK_MARKER()); + return ESP_OK; + } + // switch TRAX block while size of data is more than min size + while (ESP_APPTRACE_TRAX_INBLOCK_MARKER() > 0) { + ESP_APPTRACE_LOGD("Try to flush %d bytes. Wait until block switch for %u us", ESP_APPTRACE_TRAX_INBLOCK_MARKER(), tmo); + res = esp_apptrace_trax_block_switch_waitus(tmo); if (res != ESP_OK) { - ESP_APPTRACE_LOGE("Failed to switch to another block"); + ESP_APPTRACE_LOGE("Failed to switch to another block!"); return res; } - ESP_APPTRACE_LOGD("Flushed last block %u bytes", *in_block_marker); - *in_block_marker = 0; } return res; @@ -735,6 +801,16 @@ static esp_err_t esp_apptrace_trax_dest_init() s_trace_buf.trax.state.markers[i] = 0; } s_trace_buf.trax.state.in_block = ESP_APPTRACE_TRAX_INBLOCK_START; +#if CONFIG_ESP32_APPTRACE_PENDING_DATA_SIZE_MAX > 0 + esp_apptrace_rb_init(&s_trace_buf.trax.rb_pend, s_trace_buf.trax.pending_data, + sizeof(s_trace_buf.trax.pending_data)); +#if CONFIG_ESP32_APPTRACE_PENDING_DATA_SIZE_MAX > ESP_APPTRACE_TRAX_BLOCK_SIZE + s_trace_buf.trax.cur_pending_chunk_sz = 0; + esp_apptrace_rb_init(&s_trace_buf.trax.rb_pend_chunk_sz, (uint8_t *)s_trace_buf.trax.pending_chunk_sz, + sizeof(s_trace_buf.trax.pending_chunk_sz)); +#endif +#endif + esp_apptrace_trax_down_buf_init(); DPORT_WRITE_PERI_REG(DPORT_PRO_TRACEMEM_ENA_REG, DPORT_PRO_TRACEMEM_ENA_M); #if CONFIG_FREERTOS_UNICORE == 0 @@ -752,16 +828,10 @@ esp_err_t esp_apptrace_init() int res; if (!s_trace_buf.inited) { - res = esp_apptrace_log_init(); - if (res != ESP_OK) { - ets_printf("%s: Failed to init log lock (%d)!", TAG, res); - return res; - } - //memset(&s_trace_buf, 0, sizeof(s_trace_buf)); - res = esp_apptrace_lock_init(&s_trace_buf.lock); + memset(&s_trace_buf, 0, sizeof(s_trace_buf)); + res = esp_apptrace_lock_initialize(&s_trace_buf.lock); if (res != ESP_OK) { ESP_APPTRACE_LOGE("Failed to init log lock (%d)!", res); - esp_apptrace_log_cleanup(); return res; } #if CONFIG_ESP32_APPTRACE_DEST_TRAX @@ -769,7 +839,6 @@ esp_err_t esp_apptrace_init() if (res != ESP_OK) { ESP_APPTRACE_LOGE("Failed to init TRAX dest data (%d)!", res); esp_apptrace_lock_cleanup(); - esp_apptrace_log_cleanup(); return res; } #endif @@ -785,7 +854,49 @@ esp_err_t esp_apptrace_init() return ESP_OK; } -esp_err_t esp_apptrace_write(esp_apptrace_dest_t dest, void *data, size_t size, uint32_t user_tmo) +esp_err_t esp_apptrace_read(esp_apptrace_dest_t dest, void *buf, size_t *size, uint32_t user_tmo) +{ + uint8_t *ptr = NULL; + uint32_t tmo = user_tmo; + int res = ESP_OK; + esp_apptrace_tmo_t sleeping_tmo; + //TODO: use ptr to HW transport iface struct + uint8_t *(*apptrace_get_down_buffer)(uint32_t *, uint32_t *); + esp_err_t (*apptrace_put_down_buffer)(uint8_t *, uint32_t , uint32_t *); + + if (dest == ESP_APPTRACE_DEST_TRAX) { +#if CONFIG_ESP32_APPTRACE_DEST_TRAX + apptrace_get_down_buffer = esp_apptrace_trax_get_down_rdptr; + apptrace_put_down_buffer = esp_apptrace_trax_put_down_rdptr; +#else + ESP_APPTRACE_LOGE("Application tracing via TRAX is disabled in menuconfig!"); + return ESP_ERR_NOT_SUPPORTED; +#endif + } else { + ESP_APPTRACE_LOGE("Trace destinations other then TRAX are not supported yet!"); + return ESP_ERR_NOT_SUPPORTED; + } + + //TODO: callback system + esp_apptrace_tmo_init(&sleeping_tmo, tmo); + uint32_t act_sz = *size; + while ((ptr = apptrace_get_down_buffer(&act_sz, &tmo)) == NULL ) { + res = esp_apptrace_tmo_check(&sleeping_tmo); + if (res != ESP_OK) { + break; + } + } + if (ptr && act_sz > 0) { + ESP_APPTRACE_LOGD("Read %d bytes from host", act_sz); + memcpy(buf, ptr, act_sz); + res = apptrace_put_down_buffer(ptr, act_sz, &tmo); + *size = act_sz; + } + + return res; +} + +esp_err_t esp_apptrace_write(esp_apptrace_dest_t dest, const void *data, size_t size, uint32_t user_tmo) { uint8_t *ptr = NULL; uint32_t tmo = user_tmo; @@ -808,12 +919,11 @@ esp_err_t esp_apptrace_write(esp_apptrace_dest_t dest, void *data, size_t size, ptr = apptrace_get_buffer(size, &tmo); if (ptr == NULL) { - //ESP_APPTRACE_LOGE("Failed to get buffer!"); return ESP_ERR_NO_MEM; } // actually can be suspended here by higher prio tasks/ISRs - //TODO: use own memcpy with dead trace calls kick-off algo, and tmo expiration check + //TODO: use own memcpy with dead trace calls kick-off algo and tmo expiration check memcpy(ptr, data, size); // now indicate that this buffer is ready to be sent off to host @@ -842,14 +952,14 @@ int esp_apptrace_vprintf_to(esp_apptrace_dest_t dest, uint32_t user_tmo, const c return ESP_ERR_NOT_SUPPORTED; } - // ESP_APPTRACE_LOGI("fmt %x", fmt); + ESP_APPTRACE_LOGD("fmt %x", fmt); while ((p = (uint8_t *)strchr((char *)p, '%')) && nargs < ESP_APPTRACE_MAX_VPRINTF_ARGS) { p++; if (*p != '%' && *p != 0) { nargs++; } } - // ESP_APPTRACE_LOGI("nargs = %d", nargs); + ESP_APPTRACE_LOGD("nargs = %d", nargs); if (p) { ESP_APPTRACE_LOGE("Failed to store all printf args!"); } @@ -868,7 +978,7 @@ int esp_apptrace_vprintf_to(esp_apptrace_dest_t dest, uint32_t user_tmo, const c uint32_t arg = va_arg(ap, uint32_t); *(uint32_t *)pout = arg; pout += sizeof(uint32_t); - // ESP_APPTRACE_LOGI("arg %x", arg); + ESP_APPTRACE_LOGD("arg %x", arg); } int ret = apptrace_put_buffer(p, &tmo); @@ -959,36 +1069,13 @@ esp_err_t esp_apptrace_flush(esp_apptrace_dest_t dest, uint32_t tmo) res = esp_apptrace_flush_nolock(dest, 0, tmo); if (res != ESP_OK) { - ESP_APPTRACE_LOGE("Failed to fluch apptrace data (%d)!", res); + ESP_APPTRACE_LOGE("Failed to flush apptrace data (%d)!", res); } if (esp_apptrace_unlock() != ESP_OK) { - ESP_APPTRACE_LOGE("Failed to unlock apptrace data (%d)!", res); + assert(false && "Failed to unlock apptrace data!"); } return res; } - -#if ESP_APPTRACE_DEBUG_STATS_ENABLE == 1 -void esp_apptrace_print_stats() -{ - uint32_t i; - uint32_t tmo = ESP_APPTRACE_TMO_INFINITE; - - esp_apptrace_lock(&tmo); - - for (i = s_trace_buf.state.stats.wr.hist_rd; (i < s_trace_buf.state.stats.wr.hist_wr) && (i < ESP_APPTRACE_BUF_HISTORY_DEPTH); i++) { - esp_trace_buffer_wr_hitem_t *hi = (esp_trace_buffer_wr_hitem_t *)&s_trace_buf.state.stats.wr.hist[i]; - ESP_APPTRACE_LOGO("hist[%u] = {%x, %x}", i, hi->hnd, hi->ts); - } - if (i == ESP_APPTRACE_BUF_HISTORY_DEPTH) { - for (i = 0; i < s_trace_buf.state.stats.wr.hist_wr; i++) { - esp_trace_buffer_wr_hitem_t *hi = (esp_trace_buffer_wr_hitem_t *)&s_trace_buf.state.stats.wr.hist[i]; - ESP_APPTRACE_LOGO("hist[%u] = {%x, %x}", i, hi->hnd, hi->ts); - } - } - - esp_apptrace_unlock(); -} -#endif #endif diff --git a/components/app_trace/app_trace_util.c b/components/app_trace/app_trace_util.c new file mode 100644 index 0000000000..17fe170931 --- /dev/null +++ b/components/app_trace/app_trace_util.c @@ -0,0 +1,207 @@ +// Copyright 2017 Espressif Systems (Shanghai) PTE LTD +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at + +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +#include "freertos/FreeRTOS.h" +#include "freertos/task.h" +#include "esp_app_trace_util.h" + +/////////////////////////////////////////////////////////////////////////////// +///////////////////////////////// LOCK //////////////////////////////////////// +/////////////////////////////////////////////////////////////////////////////// + +#define ESP_TEST_CPUTICKS2US(_t_) ((_t_)/(XT_CLOCK_FREQ/1000000)) + +esp_err_t esp_apptrace_tmo_check(esp_apptrace_tmo_t *tmo) +{ + unsigned cur, elapsed; + + if (tmo->tmo != 0xFFFFFFFF) { + cur = portGET_RUN_TIME_COUNTER_VALUE(); + if (tmo->start <= cur) { + elapsed = cur - tmo->start; + } else { + elapsed = 0xFFFFFFFF - tmo->start + cur; + } + if (ESP_TEST_CPUTICKS2US(elapsed) >= tmo->tmo) { + return ESP_ERR_TIMEOUT; + } + } + return ESP_OK; +} + +esp_err_t esp_apptrace_lock_take(esp_apptrace_lock_t *lock, uint32_t tmo) +{ + uint32_t res; +#if CONFIG_SYSVIEW_ENABLE + uint32_t recCnt; +#endif + esp_apptrace_tmo_t sleeping_tmo; + + esp_apptrace_tmo_init(&sleeping_tmo, tmo); + while (1) { + res = (xPortGetCoreID() << portMUX_VAL_SHIFT) | portMUX_MAGIC_VAL; + // first disable IRQs on this CPU, this will prevent current task from been + // preempted by higher prio tasks, otherwise deadlock can happen: + // when lower prio task took mux and then preempted by higher prio one which also tries to + // get mux with INFINITE timeout + unsigned int irq_stat = portENTER_CRITICAL_NESTED(); + // Now try to lock mux + uxPortCompareSet(&lock->portmux.mux, portMUX_FREE_VAL, &res); + if (res == portMUX_FREE_VAL) { + // do not enable IRQs, we will held them disabled until mux is unlocked + // we do not need to flush cache region for mux->irq_stat because it is used + // to hold and restore IRQ state only for CPU which took mux, other CPUs will not use this value + lock->irq_stat = irq_stat; + break; + } +#if CONFIG_SYSVIEW_ENABLE + else if (((res & portMUX_VAL_MASK) >> portMUX_VAL_SHIFT) == xPortGetCoreID()) { + recCnt = (res & portMUX_CNT_MASK) >> portMUX_CNT_SHIFT; + recCnt++; + // ets_printf("Recursive lock: recCnt=%d\n", recCnt); + lock->portmux.mux = portMUX_MAGIC_VAL | (recCnt << portMUX_CNT_SHIFT) | (xPortGetCoreID() << portMUX_VAL_SHIFT); + break; + } +#endif + // if mux is locked by other task/ISR enable IRQs and let other guys work + portEXIT_CRITICAL_NESTED(irq_stat); + + int err = esp_apptrace_tmo_check(&sleeping_tmo); + if (err != ESP_OK) { + return err; + } + } + + return ESP_OK; +} + +esp_err_t esp_apptrace_lock_give(esp_apptrace_lock_t *lock) +{ + esp_err_t ret = ESP_OK; + uint32_t res = 0; + unsigned int irq_stat; +#if CONFIG_SYSVIEW_ENABLE + uint32_t recCnt; +#endif + res = portMUX_FREE_VAL; + + // first of all save a copy of IRQ status for this locker because uxPortCompareSet will unlock mux and tasks/ISRs + // from other core can overwrite mux->irq_stat + irq_stat = lock->irq_stat; + uxPortCompareSet(&lock->portmux.mux, (xPortGetCoreID() << portMUX_VAL_SHIFT) | portMUX_MAGIC_VAL, &res); + + if ( ((res & portMUX_VAL_MASK) >> portMUX_VAL_SHIFT) == xPortGetCoreID() ) { +#if CONFIG_SYSVIEW_ENABLE + //Lock is valid, we can return safely. Just need to check if it's a recursive lock; if so we need to decrease the refcount. + if ( ((res & portMUX_CNT_MASK) >> portMUX_CNT_SHIFT) != 0) { + //We locked this, but the reccount isn't zero. Decrease refcount and continue. + recCnt = (res & portMUX_CNT_MASK) >> portMUX_CNT_SHIFT; + recCnt--; + lock->portmux.mux = portMUX_MAGIC_VAL | (recCnt << portMUX_CNT_SHIFT) | (xPortGetCoreID() << portMUX_VAL_SHIFT); + } +#endif + } else if ( res == portMUX_FREE_VAL ) { + ret = ESP_FAIL; // should never get here + } else { + ret = ESP_FAIL; // should never get here + } + // restore local interrupts + portEXIT_CRITICAL_NESTED(irq_stat); + return ret; +} + +/////////////////////////////////////////////////////////////////////////////// +////////////////////////////// RING BUFFER //////////////////////////////////// +/////////////////////////////////////////////////////////////////////////////// + +uint8_t *esp_apptrace_rb_produce(esp_apptrace_rb_t *rb, uint32_t size) +{ + uint8_t *ptr = rb->data + rb->wr; + // check for avalable space + if (rb->rd <= rb->wr) { + // |?R......W??| + if (rb->wr + size >= rb->size) { + if (rb->rd == 0) { + return NULL; // cannot wrap wr + } + if (rb->wr + size == rb->size) { + rb->wr = 0; + } else { + // check if we can wrap wr earlier to get space for requested size + if (size > rb->rd - 1) { + return NULL; // cannot wrap wr + } + // shrink buffer a bit, full size will be restored at rd wrapping + rb->cur_size = rb->wr; + rb->wr = 0; + ptr = rb->data; + if (rb->rd == rb->cur_size) { + rb->rd = 0; + if (rb->cur_size < rb->size) { + rb->cur_size = rb->size; + } + } + rb->wr += size; + } + } else { + rb->wr += size; + } + } else { + // |?W......R??| + if (size > rb->rd - rb->wr - 1) { + return NULL; + } + rb->wr += size; + } + return ptr; +} + +uint8_t *esp_apptrace_rb_consume(esp_apptrace_rb_t *rb, uint32_t size) +{ + uint8_t *ptr = rb->data + rb->rd; + if (rb->rd <= rb->wr) { + // |?R......W??| + if (rb->rd + size > rb->wr) { + return NULL; + } + rb->rd += size; + } else { + // |?W......R??| + if (rb->rd + size > rb->cur_size) { + return NULL; + } else if (rb->rd + size == rb->cur_size) { + // restore full size usage + if (rb->cur_size < rb->size) { + rb->cur_size = rb->size; + } + rb->rd = 0; + } else { + rb->rd += size; + } + } + return ptr; +} + +uint32_t esp_apptrace_rb_read_size_get(esp_apptrace_rb_t *rb) +{ + uint32_t size = 0; + if (rb->rd <= rb->wr) { + // |?R......W??| + size = rb->wr - rb->rd; + } else { + // |?W......R??| + size = rb->cur_size - rb->rd; + } + return size; +} diff --git a/components/app_trace/component.mk b/components/app_trace/component.mk new file mode 100644 index 0000000000..235f19831d --- /dev/null +++ b/components/app_trace/component.mk @@ -0,0 +1,24 @@ +# +# Component Makefile +# + +COMPONENT_SRCDIRS := . + +COMPONENT_ADD_INCLUDEDIRS := include + +COMPONENT_ADD_LDFLAGS := -lapp_trace + +ifdef CONFIG_SYSVIEW_ENABLE +#COMPONENT_EXTRA_INCLUDES := freertos + +COMPONENT_ADD_INCLUDEDIRS += \ + sys_view/Config \ + sys_view/SEGGER \ + sys_view/Sample/OS + +COMPONENT_SRCDIRS += \ + sys_view/SEGGER \ + sys_view/Sample/OS \ + sys_view/Sample/Config \ + sys_view/esp32 +endif diff --git a/components/esp32/include/esp_app_trace.h b/components/app_trace/include/esp_app_trace.h similarity index 72% rename from components/esp32/include/esp_app_trace.h rename to components/app_trace/include/esp_app_trace.h index bd33e589d3..d043f3935b 100644 --- a/components/esp32/include/esp_app_trace.h +++ b/components/app_trace/include/esp_app_trace.h @@ -16,20 +16,17 @@ #include #include "esp_err.h" +#include "freertos/portmacro.h" -// infinite waiting timeout +/** Infinite waiting timeout */ #define ESP_APPTRACE_TMO_INFINITE ((uint32_t)-1) -// Trace memory block size -#define ESP_APPTRACE_TRAX_BLOCK_SIZE 0x4000UL - /** * Application trace data destinations bits. */ typedef enum { - ESP_APPTRACE_DEST_TRAX = 0x1, - ESP_APPTRACE_DEST_UART0 = 0x2, - //ESP_APPTRACE_DEST_UART1 = 0x4, + ESP_APPTRACE_DEST_TRAX = 0x1, ///< JTAG destination + ESP_APPTRACE_DEST_UART0 = 0x2, ///< UART destination } esp_apptrace_dest_t; /** @@ -37,7 +34,7 @@ typedef enum { * * @note Should be called before any esp_apptrace_xxx call. * - * @return ESP_OK on success, otherwise \see esp_err_t + * @return ESP_OK on success, otherwise see esp_err_t */ esp_err_t esp_apptrace_init(); @@ -61,7 +58,7 @@ uint8_t *esp_apptrace_buffer_get(esp_apptrace_dest_t dest, size_t size, uint32_t * @param ptr Address of trace buffer to release. Should be the value returned by call to esp_apptrace_buffer_get. * @param tmo Timeout for operation (in us). Use ESP_APPTRACE_TMO_INFINITE to wait indefinetly. * - * @return ESP_OK on success, otherwise \see esp_err_t + * @return ESP_OK on success, otherwise see esp_err_t */ esp_err_t esp_apptrace_buffer_put(esp_apptrace_dest_t dest, uint8_t *ptr, uint32_t tmo); @@ -73,20 +70,21 @@ esp_err_t esp_apptrace_buffer_put(esp_apptrace_dest_t dest, uint8_t *ptr, uint32 * @param size Size of data to write to trace buffer. * @param tmo Timeout for operation (in us). Use ESP_APPTRACE_TMO_INFINITE to wait indefinetly. * - * @return ESP_OK on success, otherwise \see esp_err_t + * @return ESP_OK on success, otherwise see esp_err_t */ -esp_err_t esp_apptrace_write(esp_apptrace_dest_t dest, void *data, size_t size, uint32_t tmo); +esp_err_t esp_apptrace_write(esp_apptrace_dest_t dest, const void *data, size_t size, uint32_t tmo); /** * @brief vprintf-like function to sent log messages to host via specified HW interface. * * @param dest Indicates HW interface to send data. + * @param tmo Timeout for operation (in us). Use ESP_APPTRACE_TMO_INFINITE to wait indefinetly. * @param fmt Address of format string. * @param ap List of arguments. * * @return Number of bytes written. */ -int esp_apptrace_vprintf_to(esp_apptrace_dest_t dest, uint32_t user_tmo, const char *fmt, va_list ap); +int esp_apptrace_vprintf_to(esp_apptrace_dest_t dest, uint32_t tmo, const char *fmt, va_list ap); /** * @brief vprintf-like function to sent log messages to host. @@ -99,25 +97,38 @@ int esp_apptrace_vprintf_to(esp_apptrace_dest_t dest, uint32_t user_tmo, const c int esp_apptrace_vprintf(const char *fmt, va_list ap); /** - * @brief Flushes remaining data in trace buffer to host. + * @brief Flushes remaining data in trace buffer to host. * * @param dest Indicates HW interface to flush data on. * @param tmo Timeout for operation (in us). Use ESP_APPTRACE_TMO_INFINITE to wait indefinetly. * - * @return ESP_OK on success, otherwise \see esp_err_t + * @return ESP_OK on success, otherwise see esp_err_t */ esp_err_t esp_apptrace_flush(esp_apptrace_dest_t dest, uint32_t tmo); /** * @brief Flushes remaining data in trace buffer to host without locking internal data. - This is special version of esp_apptrace_flush which should be called from panic handler. + * This is special version of esp_apptrace_flush which should be called from panic handler. * * @param dest Indicates HW interface to flush data on. * @param min_sz Threshold for flushing data. If current filling level is above this value, data will be flushed. TRAX destinations only. * @param tmo Timeout for operation (in us). Use ESP_APPTRACE_TMO_INFINITE to wait indefinetly. * - * @return ESP_OK on success, otherwise \see esp_err_t + * @return ESP_OK on success, otherwise see esp_err_t */ esp_err_t esp_apptrace_flush_nolock(esp_apptrace_dest_t dest, uint32_t min_sz, uint32_t tmo); +/** + * @brief Reads host data from trace buffer. + * + * @param dest Indicates HW interface to read the data on. + * @param data Address of buffer to put data from trace buffer. + * @param size Pointer to store size of read data. Before call to this function pointed memory must hold requested size of data + * @param tmo Timeout for operation (in us). Use ESP_APPTRACE_TMO_INFINITE to wait indefinetly. + * + * @return ESP_OK on success, otherwise see esp_err_t + */ +esp_err_t esp_apptrace_read(esp_apptrace_dest_t dest, void *data, size_t *size, uint32_t tmo); + + #endif diff --git a/components/app_trace/include/esp_app_trace_util.h b/components/app_trace/include/esp_app_trace_util.h new file mode 100644 index 0000000000..83359b8b24 --- /dev/null +++ b/components/app_trace/include/esp_app_trace_util.h @@ -0,0 +1,148 @@ +// Copyright 2017 Espressif Systems (Shanghai) PTE LTD +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at + +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +#ifndef ESP_APP_TRACE_UTIL_H_ +#define ESP_APP_TRACE_UTIL_H_ + +#include "freertos/portmacro.h" +#include "esp_err.h" + +/** Tracing module synchronization lock */ +typedef struct { + volatile unsigned int irq_stat; ///< local (on 1 CPU) IRQ state + portMUX_TYPE portmux; ///< mux for synchronization +} esp_apptrace_lock_t; + +/** + * @brief Initializes lock structure. + * + * @param lock Pointer to lock structure to be initialized. + */ +static inline void esp_apptrace_lock_init(esp_apptrace_lock_t *lock) +{ + lock->portmux.mux = portMUX_FREE_VAL; + lock->irq_stat = 0; +} + +/** + * @brief Tries to acquire lock in specified time period. + * + * @param lock Pointer to lock structure. + * @param tmo Timeout for operation (in us). Use ESP_APPTRACE_TMO_INFINITE to wait indefinetly. + * + * @return ESP_OK on success, otherwise \see esp_err_t + */ +esp_err_t esp_apptrace_lock_take(esp_apptrace_lock_t *lock, uint32_t tmo); + +/** + * @brief Releases lock. + * + * @param lock Pointer to lock structure. + * + * @return ESP_OK on success, otherwise \see esp_err_t + */ +esp_err_t esp_apptrace_lock_give(esp_apptrace_lock_t *lock); + + +/** Structure which holds data necessary for measuring time intervals. + * + * After initialization via esp_apptrace_tmo_init() user needs to call esp_apptrace_tmo_check() + * periodically to check timeout for expiration. + */ +typedef struct { + uint32_t start; ///< time interval start (in ticks) + uint32_t tmo; ///< timeout value (in us) +} esp_apptrace_tmo_t; + +/** + * @brief Initializes timeout structure. + * + * @param tmo Pointer to timeout structure to be initialized. + * @param user_tmo Timeout value (in us). +*/ +static inline void esp_apptrace_tmo_init(esp_apptrace_tmo_t *tmo, uint32_t user_tmo) +{ + tmo->start = portGET_RUN_TIME_COUNTER_VALUE(); + tmo->tmo = user_tmo; +} + +/** + * @brief Checks timeout for expiration. + * + * @param tmo Pointer to timeout structure to be initialized. + * + * @return ESP_OK on success, otherwise \see esp_err_t + */ +esp_err_t esp_apptrace_tmo_check(esp_apptrace_tmo_t *tmo); + + +/** Ring buffer control structure. + * + * @note For purposes of application tracing module if there is no enough space for user data and write pointer can be wrapped + * current ring buffer size can be temporarily shrinked in order to provide buffer with requested size. + */ +typedef struct { + uint8_t *data; ///< pointer to data storage + uint32_t size; ///< size of data storage + uint32_t cur_size; ///< current size of data storage + uint32_t rd; ///< read pointer + uint32_t wr; ///< write pointer +} esp_apptrace_rb_t; + +/** + * @brief Initializes ring buffer control structure. + * + * @param rb Pointer to ring buffer structure to be initialized. + * @param data Pointer to buffer to be used as ring buffer's data storage. + * @param size Size of buffer to be used as ring buffer's data storage. + */ +static inline void esp_apptrace_rb_init(esp_apptrace_rb_t *rb, uint8_t *data, uint32_t size) +{ + rb->data = data; + rb->size = rb->cur_size = size; + rb->rd = 0; + rb->wr = 0; +} + +/** + * @brief Allocates memory chunk in ring buffer. + * + * @param rb Pointer to ring buffer structure. + * @param size Size of the memory to allocate. + * + * @return Pointer to the allocated memory or NULL in case of failure. + */ +uint8_t *esp_apptrace_rb_produce(esp_apptrace_rb_t *rb, uint32_t size); + +/** + * @brief Consumes memory chunk in ring buffer. + * + * @param rb Pointer to ring buffer structure. + * @param size Size of the memory to consume. + * + * @return Pointer to consumed memory chunk or NULL in case of failure. + */ +uint8_t *esp_apptrace_rb_consume(esp_apptrace_rb_t *rb, uint32_t size); + +/** + * @brief Gets size of memory which can consumed with single call to esp_apptrace_rb_consume(). + * + * @param rb Pointer to ring buffer structure. + * + * @return Size of memory which can consumed. + * + * @note Due to read pointer wrapping returned size can be less then the total size of available data. + */ +uint32_t esp_apptrace_rb_read_size_get(esp_apptrace_rb_t *rb); + +#endif //ESP_APP_TRACE_UTIL_H_ \ No newline at end of file diff --git a/components/app_trace/sys_view/Config/Global.h b/components/app_trace/sys_view/Config/Global.h new file mode 100644 index 0000000000..6ba942b7e5 --- /dev/null +++ b/components/app_trace/sys_view/Config/Global.h @@ -0,0 +1,102 @@ +/********************************************************************* +* SEGGER Microcontroller GmbH & Co. KG * +* The Embedded Experts * +********************************************************************** +* * +* (c) 2015 - 2017 SEGGER Microcontroller GmbH & Co. KG * +* * +* www.segger.com Support: support@segger.com * +* * +********************************************************************** +* * +* SEGGER SystemView * Real-time application analysis * +* * +********************************************************************** +* * +* All rights reserved. * +* * +* SEGGER strongly recommends to not make any changes * +* to or modify the source code of this software in order to stay * +* compatible with the RTT protocol and J-Link. * +* * +* Redistribution and use in source and binary forms, with or * +* without modification, are permitted provided that the following * +* conditions are met: * +* * +* o Redistributions of source code must retain the above copyright * +* notice, this list of conditions and the following disclaimer. * +* * +* o Redistributions in binary form must reproduce the above * +* copyright notice, this list of conditions and the following * +* disclaimer in the documentation and/or other materials provided * +* with the distribution. * +* * +* o Neither the name of SEGGER Microcontroller GmbH & Co. KG * +* nor the names of its contributors may be used to endorse or * +* promote products derived from this software without specific * +* prior written permission. * +* * +* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * +* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * +* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * +* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * +* DISCLAIMED. IN NO EVENT SHALL SEGGER Microcontroller BE LIABLE FOR * +* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * +* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * +* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * +* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * +* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * +* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * +* DAMAGE. * +* * +********************************************************************** +* * +* SystemView version: V2.42 * +* * +********************************************************************** +---------------------------------------------------------------------- +File : Global.h +Purpose : Global types + In case your application already has a Global.h, you should + merge the files. In order to use Segger code, the types + U8, U16, U32, I8, I16, I32 need to be defined in Global.h; + additional definitions do not hurt. +---------------------------END-OF-HEADER------------------------------ +*/ + +#ifndef GLOBAL_H // Guard against multiple inclusion +#define GLOBAL_H + +#define U8 unsigned char +#define U16 unsigned short +#define U32 unsigned long +#define I8 signed char +#define I16 signed short +#define I32 signed long + +#ifdef _WIN32 + // + // Microsoft VC6 compiler related + // + #define U64 unsigned __int64 + #define U128 unsigned __int128 + #define I64 __int64 + #define I128 __int128 + #if _MSC_VER <= 1200 + #define U64_C(x) x##UI64 + #else + #define U64_C(x) x##ULL + #endif +#else + // + // C99 compliant compiler + // + #define U64 unsigned long long + #define I64 signed long long + #define U64_C(x) x##ULL +#endif + +#endif // Avoid multiple inclusion + +/*************************** End of file ****************************/ diff --git a/components/app_trace/sys_view/Config/SEGGER_RTT_Conf.h b/components/app_trace/sys_view/Config/SEGGER_RTT_Conf.h new file mode 100644 index 0000000000..49944e739b --- /dev/null +++ b/components/app_trace/sys_view/Config/SEGGER_RTT_Conf.h @@ -0,0 +1,298 @@ +/********************************************************************* +* SEGGER Microcontroller GmbH & Co. KG * +* The Embedded Experts * +********************************************************************** +* * +* (c) 2015 - 2017 SEGGER Microcontroller GmbH & Co. KG * +* * +* www.segger.com Support: support@segger.com * +* * +********************************************************************** +* * +* SEGGER SystemView * Real-time application analysis * +* * +********************************************************************** +* * +* All rights reserved. * +* * +* SEGGER strongly recommends to not make any changes * +* to or modify the source code of this software in order to stay * +* compatible with the RTT protocol and J-Link. * +* * +* Redistribution and use in source and binary forms, with or * +* without modification, are permitted provided that the following * +* conditions are met: * +* * +* o Redistributions of source code must retain the above copyright * +* notice, this list of conditions and the following disclaimer. * +* * +* o Redistributions in binary form must reproduce the above * +* copyright notice, this list of conditions and the following * +* disclaimer in the documentation and/or other materials provided * +* with the distribution. * +* * +* o Neither the name of SEGGER Microcontroller GmbH & Co. KG * +* nor the names of its contributors may be used to endorse or * +* promote products derived from this software without specific * +* prior written permission. * +* * +* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * +* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * +* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * +* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * +* DISCLAIMED. IN NO EVENT SHALL SEGGER Microcontroller BE LIABLE FOR * +* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * +* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * +* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * +* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * +* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * +* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * +* DAMAGE. * +* * +********************************************************************** +* * +* SystemView version: V2.42 * +* * +********************************************************************** +---------------------------END-OF-HEADER------------------------------ +File : SEGGER_RTT_Conf.h +Purpose : Implementation of SEGGER real-time transfer (RTT) which + allows real-time communication on targets which support + debugger memory accesses while the CPU is running. +Revision: $Rev: 5626 $ + +*/ + +#ifndef SEGGER_RTT_CONF_H +#define SEGGER_RTT_CONF_H + +#ifdef __IAR_SYSTEMS_ICC__ + #include +#endif + +/********************************************************************* +* +* Defines, configurable +* +********************************************************************** +*/ + +#define SEGGER_RTT_MAX_NUM_UP_BUFFERS (3) // Max. number of up-buffers (T->H) available on this target (Default: 3) +#define SEGGER_RTT_MAX_NUM_DOWN_BUFFERS (3) // Max. number of down-buffers (H->T) available on this target (Default: 3) + +#define BUFFER_SIZE_UP (1024) // Size of the buffer for terminal output of target, up to host (Default: 1k) +#define BUFFER_SIZE_DOWN (16) // Size of the buffer for terminal input to target from host (Usually keyboard input) (Default: 16) + +#define SEGGER_RTT_PRINTF_BUFFER_SIZE (64u) // Size of buffer for RTT printf to bulk-send chars via RTT (Default: 64) + +#define SEGGER_RTT_MODE_DEFAULT SEGGER_RTT_MODE_NO_BLOCK_SKIP // Mode for pre-initialized terminal channel (buffer 0) + +// +// Target is not allowed to perform other RTT operations while string still has not been stored completely. +// Otherwise we would probably end up with a mixed string in the buffer. +// If using RTT from within interrupts, multiple tasks or multi processors, define the SEGGER_RTT_LOCK() and SEGGER_RTT_UNLOCK() function here. +// +// SEGGER_RTT_MAX_INTERRUPT_PRIORITY can be used in the sample lock routines on Cortex-M3/4. +// Make sure to mask all interrupts which can send RTT data, i.e. generate SystemView events, or cause task switches. +// When high-priority interrupts must not be masked while sending RTT data, SEGGER_RTT_MAX_INTERRUPT_PRIORITY needs to be adjusted accordingly. +// (Higher priority = lower priority number) +// Default value for embOS: 128u +// Default configuration in FreeRTOS: configMAX_SYSCALL_INTERRUPT_PRIORITY: ( configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY << (8 - configPRIO_BITS) ) +// In case of doubt mask all interrupts: 1 << (8 - BASEPRI_PRIO_BITS) i.e. 1 << 5 when 3 bits are implemented in NVIC +// or define SEGGER_RTT_LOCK() to completely disable interrupts. +// + +#define SEGGER_RTT_MAX_INTERRUPT_PRIORITY (0x20) // Interrupt priority to lock on SEGGER_RTT_LOCK on Cortex-M3/4 (Default: 0x20) + +/********************************************************************* +* +* RTT lock configuration for SEGGER Embedded Studio, +* Rowley CrossStudio and GCC +*/ +#if (defined __SES_ARM) || (defined __CROSSWORKS_ARM) || (defined __GNUC__) + #ifdef __ARM_ARCH_6M__ + #define SEGGER_RTT_LOCK() { \ + unsigned int LockState; \ + __asm volatile ("mrs %0, primask \n\t" \ + "mov r1, $1 \n\t" \ + "msr primask, r1 \n\t" \ + : "=r" (LockState) \ + : \ + : "r1" \ + ); + + #define SEGGER_RTT_UNLOCK() __asm volatile ("msr primask, %0 \n\t" \ + : \ + : "r" (LockState) \ + : \ + ); \ + } + + #elif (defined(__ARM_ARCH_7M__) || defined(__ARM_ARCH_7EM__)) + #ifndef SEGGER_RTT_MAX_INTERRUPT_PRIORITY + #define SEGGER_RTT_MAX_INTERRUPT_PRIORITY (0x20) + #endif + #define SEGGER_RTT_LOCK() { \ + unsigned int LockState; \ + __asm volatile ("mrs %0, basepri \n\t" \ + "mov r1, %1 \n\t" \ + "msr basepri, r1 \n\t" \ + : "=r" (LockState) \ + : "i"(SEGGER_RTT_MAX_INTERRUPT_PRIORITY) \ + : "r1" \ + ); + + #define SEGGER_RTT_UNLOCK() __asm volatile ("msr basepri, %0 \n\t" \ + : \ + : "r" (LockState) \ + : \ + ); \ + } + + #elif defined(__ARM_ARCH_7A__) + #define SEGGER_RTT_LOCK() { \ + unsigned int LockState; \ + __asm volatile ("mrs r1, CPSR \n\t" \ + "mov %0, r1 \n\t" \ + "orr r1, r1, #0xC0 \n\t" \ + "msr CPSR_c, r1 \n\t" \ + : "=r" (LockState) \ + : \ + : "r1" \ + ); + + #define SEGGER_RTT_UNLOCK() __asm volatile ("mov r0, %0 \n\t" \ + "mrs r1, CPSR \n\t" \ + "bic r1, r1, #0xC0 \n\t" \ + "and r0, r0, #0xC0 \n\t" \ + "orr r1, r1, r0 \n\t" \ + "msr CPSR_c, r1 \n\t" \ + : \ + : "r" (LockState) \ + : "r0", "r1" \ + ); \ + } +#else + #define SEGGER_RTT_LOCK() + #define SEGGER_RTT_UNLOCK() + #endif +#endif + +/********************************************************************* +* +* RTT lock configuration for IAR EWARM +*/ +#ifdef __ICCARM__ + #if (defined (__ARM6M__) && (__CORE__ == __ARM6M__)) + #define SEGGER_RTT_LOCK() { \ + unsigned int LockState; \ + LockState = __get_PRIMASK(); \ + __set_PRIMASK(1); + + #define SEGGER_RTT_UNLOCK() __set_PRIMASK(LockState); \ + } + #elif ((defined (__ARM7EM__) && (__CORE__ == __ARM7EM__)) || (defined (__ARM7M__) && (__CORE__ == __ARM7M__))) + #ifndef SEGGER_RTT_MAX_INTERRUPT_PRIORITY + #define SEGGER_RTT_MAX_INTERRUPT_PRIORITY (0x20) + #endif + #define SEGGER_RTT_LOCK() { \ + unsigned int LockState; \ + LockState = __get_BASEPRI(); \ + __set_BASEPRI(SEGGER_RTT_MAX_INTERRUPT_PRIORITY); + + #define SEGGER_RTT_UNLOCK() __set_BASEPRI(LockState); \ + } + #endif +#endif + +/********************************************************************* +* +* RTT lock configuration for IAR RX +*/ +#ifdef __ICCRX__ + #define SEGGER_RTT_LOCK() { \ + unsigned long LockState; \ + LockState = __get_interrupt_state(); \ + __disable_interrupt(); + + #define SEGGER_RTT_UNLOCK() __set_interrupt_state(LockState); \ + } +#endif + +/********************************************************************* +* +* RTT lock configuration for KEIL ARM +*/ +#ifdef __CC_ARM + #if (defined __TARGET_ARCH_6S_M) + #define SEGGER_RTT_LOCK() { \ + unsigned int LockState; \ + register unsigned char PRIMASK __asm( "primask"); \ + LockState = PRIMASK; \ + PRIMASK = 1u; \ + __schedule_barrier(); + + #define SEGGER_RTT_UNLOCK() PRIMASK = LockState; \ + __schedule_barrier(); \ + } + #elif (defined(__TARGET_ARCH_7_M) || defined(__TARGET_ARCH_7E_M)) + #ifndef SEGGER_RTT_MAX_INTERRUPT_PRIORITY + #define SEGGER_RTT_MAX_INTERRUPT_PRIORITY (0x20) + #endif + #define SEGGER_RTT_LOCK() { \ + unsigned int LockState; \ + register unsigned char BASEPRI __asm( "basepri"); \ + LockState = BASEPRI; \ + BASEPRI = SEGGER_RTT_MAX_INTERRUPT_PRIORITY; \ + __schedule_barrier(); + + #define SEGGER_RTT_UNLOCK() BASEPRI = LockState; \ + __schedule_barrier(); \ + } + #endif +#endif + +/********************************************************************* +* +* RTT lock configuration for TI ARM +*/ +#ifdef __TI_ARM__ + #if defined (__TI_ARM_V6M0__) + #define SEGGER_RTT_LOCK() { \ + unsigned int LockState; \ + LockState = __get_PRIMASK(); \ + __set_PRIMASK(1); + + #define SEGGER_RTT_UNLOCK() __set_PRIMASK(LockState); \ + } + #elif (defined (__TI_ARM_V7M3__) || defined (__TI_ARM_V7M4__)) + #ifndef SEGGER_RTT_MAX_INTERRUPT_PRIORITY + #define SEGGER_RTT_MAX_INTERRUPT_PRIORITY (0x20) + #endif + #define SEGGER_RTT_LOCK() { \ + unsigned int LockState; \ + LockState = OS_GetBASEPRI(); \ + OS_SetBASEPRI(SEGGER_RTT_MAX_INTERRUPT_PRIORITY); + + #define SEGGER_RTT_UNLOCK() OS_SetBASEPRI(LockState); \ + } + #endif +#endif + +/********************************************************************* +* +* RTT lock configuration fallback +*/ +#ifndef SEGGER_RTT_LOCK + void SEGGER_SYSVIEW_X_RTT_Lock(); + #define SEGGER_RTT_LOCK() SEGGER_SYSVIEW_X_RTT_Lock() // Lock RTT (nestable) (i.e. disable interrupts) +#endif + +#ifndef SEGGER_RTT_UNLOCK + void SEGGER_SYSVIEW_X_RTT_Unlock(); + #define SEGGER_RTT_UNLOCK() SEGGER_SYSVIEW_X_RTT_Unlock() // Unlock RTT (nestable) (i.e. enable previous interrupt lock state) +#endif + +#endif +/*************************** End of file ****************************/ diff --git a/components/app_trace/sys_view/Config/SEGGER_SYSVIEW_Conf.h b/components/app_trace/sys_view/Config/SEGGER_SYSVIEW_Conf.h new file mode 100644 index 0000000000..f6c5f09375 --- /dev/null +++ b/components/app_trace/sys_view/Config/SEGGER_SYSVIEW_Conf.h @@ -0,0 +1,176 @@ +/********************************************************************* +* SEGGER Microcontroller GmbH & Co. KG * +* The Embedded Experts * +********************************************************************** +* * +* (c) 2015 - 2017 SEGGER Microcontroller GmbH & Co. KG * +* * +* www.segger.com Support: support@segger.com * +* * +********************************************************************** +* * +* SEGGER SystemView * Real-time application analysis * +* * +********************************************************************** +* * +* All rights reserved. * +* * +* SEGGER strongly recommends to not make any changes * +* to or modify the source code of this software in order to stay * +* compatible with the RTT protocol and J-Link. * +* * +* Redistribution and use in source and binary forms, with or * +* without modification, are permitted provided that the following * +* conditions are met: * +* * +* o Redistributions of source code must retain the above copyright * +* notice, this list of conditions and the following disclaimer. * +* * +* o Redistributions in binary form must reproduce the above * +* copyright notice, this list of conditions and the following * +* disclaimer in the documentation and/or other materials provided * +* with the distribution. * +* * +* o Neither the name of SEGGER Microcontroller GmbH & Co. KG * +* nor the names of its contributors may be used to endorse or * +* promote products derived from this software without specific * +* prior written permission. * +* * +* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * +* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * +* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * +* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * +* DISCLAIMED. IN NO EVENT SHALL SEGGER Microcontroller BE LIABLE FOR * +* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * +* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * +* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * +* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * +* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * +* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * +* DAMAGE. * +* * +********************************************************************** +* * +* SystemView version: V2.42 * +* * +********************************************************************** +-------------------------- END-OF-HEADER ----------------------------- + +File : SEGGER_SYSVIEW_Conf.h +Purpose : SEGGER SystemView configuration. +Revision: $Rev: 5927 $ +*/ + +#ifndef SEGGER_SYSVIEW_CONF_H +#define SEGGER_SYSVIEW_CONF_H + +/********************************************************************* +* +* Defines, fixed +* +********************************************************************** +*/ +// +// Constants for known core configuration +// +#define SEGGER_SYSVIEW_CORE_OTHER 0 +#define SEGGER_SYSVIEW_CORE_CM0 1 // Cortex-M0/M0+/M1 +#define SEGGER_SYSVIEW_CORE_CM3 2 // Cortex-M3/M4/M7 +#define SEGGER_SYSVIEW_CORE_RX 3 // Renesas RX + +#if (defined __SES_ARM) || (defined __CROSSWORKS_ARM) || (defined __GNUC__) + #ifdef __ARM_ARCH_6M__ + #define SEGGER_SYSVIEW_CORE SEGGER_SYSVIEW_CORE_CM0 + #elif (defined(__ARM_ARCH_7M__) || defined(__ARM_ARCH_7EM__)) + #define SEGGER_SYSVIEW_CORE SEGGER_SYSVIEW_CORE_CM3 + #endif +#elif defined(__ICCARM__) + #if (defined (__ARM6M__) && (__CORE__ == __ARM6M__)) + #define SEGGER_SYSVIEW_CORE SEGGER_SYSVIEW_CORE_CM0 + #elif ((defined (__ARM7M__) && (__CORE__ == __ARM7M__)) || (defined (__ARM7EM__) && (__CORE__ == __ARM7EM__))) + #define SEGGER_SYSVIEW_CORE SEGGER_SYSVIEW_CORE_CM3 + #endif +#elif defined(__CC_ARM) + #if (defined(__TARGET_ARCH_6S_M)) + #define SEGGER_SYSVIEW_CORE SEGGER_SYSVIEW_CORE_CM0 + #elif (defined(__TARGET_ARCH_7_M) || defined(__TARGET_ARCH_7E_M)) + #define SEGGER_SYSVIEW_CORE SEGGER_SYSVIEW_CORE_CM3 + #endif +#elif defined(__TI_ARM__) + #ifdef __TI_ARM_V6M0__ + #define SEGGER_SYSVIEW_CORE SEGGER_SYSVIEW_CORE_CM0 + #elif (defined(__TI_ARM_V7M3__) || defined(__TI_ARM_V7M4__)) + #define SEGGER_SYSVIEW_CORE SEGGER_SYSVIEW_CORE_CM3 + #endif +#elif defined(__ICCRX__) + #define SEGGER_SYSVIEW_CORE SEGGER_SYSVIEW_CORE_RX +#elif defined(__RX) + #define SEGGER_SYSVIEW_CORE SEGGER_SYSVIEW_CORE_RX +#endif + +#ifndef SEGGER_SYSVIEW_CORE + #define SEGGER_SYSVIEW_CORE SEGGER_SYSVIEW_CORE_OTHER +#endif + +/********************************************************************* +* +* Defines, configurable +* +********************************************************************** +*/ +/********************************************************************* +* +* SystemView buffer configuration +*/ +#define SEGGER_SYSVIEW_RTT_BUFFER_SIZE 1024 // Number of bytes that SystemView uses for the buffer. +#define SEGGER_SYSVIEW_RTT_CHANNEL 1 // The RTT channel that SystemView will use. 0: Auto selection + +#define SEGGER_SYSVIEW_USE_STATIC_BUFFER 1 // Use a static buffer to generate events instead of a buffer on the stack + +#define SEGGER_SYSVIEW_POST_MORTEM_MODE 0 // 1: Enable post mortem analysis mode + +/********************************************************************* +* +* SystemView timestamp configuration +*/ +#if SEGGER_SYSVIEW_CORE == SEGGER_SYSVIEW_CORE_CM3 + #define SEGGER_SYSVIEW_GET_TIMESTAMP() (*(U32 *)(0xE0001004)) // Retrieve a system timestamp. Cortex-M cycle counter. + #define SEGGER_SYSVIEW_TIMESTAMP_BITS 32 // Define number of valid bits low-order delivered by clock source +#else + #define SEGGER_SYSVIEW_GET_TIMESTAMP() SEGGER_SYSVIEW_X_GetTimestamp() // Retrieve a system timestamp via user-defined function + #define SEGGER_SYSVIEW_TIMESTAMP_BITS 32 // Define number of valid bits low-order delivered by SEGGER_SYSVIEW_X_GetTimestamp() +#endif + +/********************************************************************* +* +* SystemView Id configuration +*/ +//TODO: optimise it +#define SEGGER_SYSVIEW_ID_BASE 0x3F400000 // Default value for the lowest Id reported by the application. Can be overridden by the application via SEGGER_SYSVIEW_SetRAMBase(). (i.e. 0x20000000 when all Ids are an address in this RAM) +#define SEGGER_SYSVIEW_ID_SHIFT 0 // Number of bits to shift the Id to save bandwidth. (i.e. 2 when Ids are 4 byte aligned) + +/********************************************************************* +* +* SystemView interrupt configuration +*/ +#if SEGGER_SYSVIEW_CORE == SEGGER_SYSVIEW_CORE_CM3 + #define SEGGER_SYSVIEW_GET_INTERRUPT_ID() ((*(U32 *)(0xE000ED04)) & 0x1FF) // Get the currently active interrupt Id. (i.e. read Cortex-M ICSR[8:0] = active vector) +#elif SEGGER_SYSVIEW_CORE == SEGGER_SYSVIEW_CORE_CM0 + #if defined(__ICCARM__) + #define SEGGER_SYSVIEW_GET_INTERRUPT_ID() (__get_IPSR()) // Workaround for IAR, which might do a byte-access to 0xE000ED04. Read IPSR instead. + #else + #define SEGGER_SYSVIEW_GET_INTERRUPT_ID() ((*(U32 *)(0xE000ED04)) & 0x3F) // Get the currently active interrupt Id. (i.e. read Cortex-M ICSR[5:0] = active vector) + #endif +#else + #define SEGGER_SYSVIEW_GET_INTERRUPT_ID() SEGGER_SYSVIEW_X_GetInterruptId() // Get the currently active interrupt Id from the user-provided function. +#endif + +void SEGGER_SYSVIEW_X_SysView_Lock(); +void SEGGER_SYSVIEW_X_SysView_Unlock(); +#define SEGGER_SYSVIEW_LOCK() SEGGER_SYSVIEW_X_SysView_Lock() +#define SEGGER_SYSVIEW_UNLOCK() SEGGER_SYSVIEW_X_SysView_Unlock() + +#endif // SEGGER_SYSVIEW_CONF_H + +/*************************** End of file ****************************/ diff --git a/components/app_trace/sys_view/SEGGER/SEGGER.h b/components/app_trace/sys_view/SEGGER/SEGGER.h new file mode 100644 index 0000000000..6b38e9cce3 --- /dev/null +++ b/components/app_trace/sys_view/SEGGER/SEGGER.h @@ -0,0 +1,155 @@ +/********************************************************************* +* SEGGER Microcontroller GmbH & Co. KG * +* The Embedded Experts * +********************************************************************** +* * +* (c) 2015 - 2017 SEGGER Microcontroller GmbH & Co. KG * +* * +* www.segger.com Support: support@segger.com * +* * +********************************************************************** +* * +* SEGGER SystemView * Real-time application analysis * +* * +********************************************************************** +* * +* All rights reserved. * +* * +* SEGGER strongly recommends to not make any changes * +* to or modify the source code of this software in order to stay * +* compatible with the RTT protocol and J-Link. * +* * +* Redistribution and use in source and binary forms, with or * +* without modification, are permitted provided that the following * +* conditions are met: * +* * +* o Redistributions of source code must retain the above copyright * +* notice, this list of conditions and the following disclaimer. * +* * +* o Redistributions in binary form must reproduce the above * +* copyright notice, this list of conditions and the following * +* disclaimer in the documentation and/or other materials provided * +* with the distribution. * +* * +* o Neither the name of SEGGER Microcontroller GmbH & Co. KG * +* nor the names of its contributors may be used to endorse or * +* promote products derived from this software without specific * +* prior written permission. * +* * +* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * +* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * +* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * +* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * +* DISCLAIMED. IN NO EVENT SHALL SEGGER Microcontroller BE LIABLE FOR * +* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * +* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * +* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * +* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * +* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * +* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * +* DAMAGE. * +* * +********************************************************************** +* * +* SystemView version: V2.42 * +* * +********************************************************************** +---------------------------------------------------------------------- +File : SEGGER.h +Purpose : Global types etc & general purpose utility functions +---------------------------END-OF-HEADER------------------------------ +*/ + +#ifndef SEGGER_H // Guard against multiple inclusion +#define SEGGER_H + +#include "Global.h" // Type definitions: U8, U16, U32, I8, I16, I32 + +#if defined(__cplusplus) +extern "C" { /* Make sure we have C-declarations in C++ programs */ +#endif + +/********************************************************************* +* +* Keywords/specifiers +* +********************************************************************** +*/ + +#ifndef INLINE + #ifdef _WIN32 + // + // Microsoft VC6 and newer. + // Force inlining without cost checking. + // + #define INLINE __forceinline + #else + #if (defined(__ICCARM__) || defined(__CC_ARM) || defined(__GNUC__) || defined(__RX) || defined(__ICCRX__)) + // + // Other known compilers. + // + #define INLINE inline + #else + // + // Unknown compilers. + // + #define INLINE + #endif + #endif +#endif + +/********************************************************************* +* +* Function-like macros +* +********************************************************************** +*/ + +#define SEGGER_COUNTOF(a) (sizeof((a))/sizeof((a)[0])) +#define SEGGER_MIN(a,b) (((a) < (b)) ? (a) : (b)) +#define SEGGER_MAX(a,b) (((a) > (b)) ? (a) : (b)) + +/********************************************************************* +* +* Types +* +********************************************************************** +*/ + +typedef struct { + char *pBuffer; + int BufferSize; + int Cnt; +} SEGGER_BUFFER_DESC; + +typedef struct { + int CacheLineSize; // 0: No Cache. Most Systems such as ARM9 use a 32 bytes cache line size. + void (*pfDMB) (void); // Optional DMB function for Data Memory Barrier to make sure all memory operations are completed. + void (*pfClean) (void *p, unsigned NumBytes); // Optional clean function for cached memory. + void (*pfInvalidate)(void *p, unsigned NumBytes); // Optional invalidate function for cached memory. +} SEGGER_CACHE_CONFIG; + +/********************************************************************* +* +* Utility functions +* +********************************************************************** +*/ + +void SEGGER_ARM_memcpy (void *pDest, const void *pSrc, int NumBytes); +void SEGGER_memcpy (void *pDest, const void *pSrc, int NumBytes); +void SEGGER_memxor (void *pDest, const void *pSrc, unsigned NumBytes); +void SEGGER_StoreChar (SEGGER_BUFFER_DESC *p, char c); +void SEGGER_PrintUnsigned(SEGGER_BUFFER_DESC *pBufferDesc, U32 v, unsigned Base, int NumDigits); +void SEGGER_PrintInt (SEGGER_BUFFER_DESC *pBufferDesc, I32 v, unsigned Base, unsigned NumDigits); +int SEGGER_snprintf (char *pBuffer, int BufferSize, const char *sFormat, ...); + + +#if defined(__cplusplus) +} /* Make sure we have C-declarations in C++ programs */ +#endif + +#endif // Avoid multiple inclusion + +/*************************** End of file ****************************/ diff --git a/components/app_trace/sys_view/SEGGER/SEGGER_RTT.h b/components/app_trace/sys_view/SEGGER/SEGGER_RTT.h new file mode 100644 index 0000000000..a4673f5aad --- /dev/null +++ b/components/app_trace/sys_view/SEGGER/SEGGER_RTT.h @@ -0,0 +1,251 @@ +/********************************************************************* +* SEGGER Microcontroller GmbH & Co. KG * +* The Embedded Experts * +********************************************************************** +* * +* (c) 2015 - 2017 SEGGER Microcontroller GmbH & Co. KG * +* * +* www.segger.com Support: support@segger.com * +* * +********************************************************************** +* * +* SEGGER SystemView * Real-time application analysis * +* * +********************************************************************** +* * +* All rights reserved. * +* * +* SEGGER strongly recommends to not make any changes * +* to or modify the source code of this software in order to stay * +* compatible with the RTT protocol and J-Link. * +* * +* Redistribution and use in source and binary forms, with or * +* without modification, are permitted provided that the following * +* conditions are met: * +* * +* o Redistributions of source code must retain the above copyright * +* notice, this list of conditions and the following disclaimer. * +* * +* o Redistributions in binary form must reproduce the above * +* copyright notice, this list of conditions and the following * +* disclaimer in the documentation and/or other materials provided * +* with the distribution. * +* * +* o Neither the name of SEGGER Microcontroller GmbH & Co. KG * +* nor the names of its contributors may be used to endorse or * +* promote products derived from this software without specific * +* prior written permission. * +* * +* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * +* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * +* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * +* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * +* DISCLAIMED. IN NO EVENT SHALL SEGGER Microcontroller BE LIABLE FOR * +* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * +* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * +* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * +* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * +* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * +* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * +* DAMAGE. * +* * +********************************************************************** +* * +* SystemView version: V2.42 * +* * +********************************************************************** +---------------------------END-OF-HEADER------------------------------ +File : SEGGER_RTT.h +Purpose : Implementation of SEGGER real-time transfer which allows + real-time communication on targets which support debugger + memory accesses while the CPU is running. +Revision: $Rev: 5626 $ +---------------------------------------------------------------------- +*/ + +#ifndef SEGGER_RTT_H +#define SEGGER_RTT_H + +#include "SEGGER_RTT_Conf.h" + +/********************************************************************* +* +* Defines, fixed +* +********************************************************************** +*/ + +/********************************************************************* +* +* Types +* +********************************************************************** +*/ + +// +// Description for a circular buffer (also called "ring buffer") +// which is used as up-buffer (T->H) +// +typedef struct { + const char* sName; // Optional name. Standard names so far are: "Terminal", "SysView", "J-Scope_t4i4" + char* pBuffer; // Pointer to start of buffer + unsigned SizeOfBuffer; // Buffer size in bytes. Note that one byte is lost, as this implementation does not fill up the buffer in order to avoid the problem of being unable to distinguish between full and empty. + unsigned WrOff; // Position of next item to be written by either target. + volatile unsigned RdOff; // Position of next item to be read by host. Must be volatile since it may be modified by host. + unsigned Flags; // Contains configuration flags +} SEGGER_RTT_BUFFER_UP; + +// +// Description for a circular buffer (also called "ring buffer") +// which is used as down-buffer (H->T) +// +typedef struct { + const char* sName; // Optional name. Standard names so far are: "Terminal", "SysView", "J-Scope_t4i4" + char* pBuffer; // Pointer to start of buffer + unsigned SizeOfBuffer; // Buffer size in bytes. Note that one byte is lost, as this implementation does not fill up the buffer in order to avoid the problem of being unable to distinguish between full and empty. + volatile unsigned WrOff; // Position of next item to be written by host. Must be volatile since it may be modified by host. + unsigned RdOff; // Position of next item to be read by target (down-buffer). + unsigned Flags; // Contains configuration flags +} SEGGER_RTT_BUFFER_DOWN; + +// +// RTT control block which describes the number of buffers available +// as well as the configuration for each buffer +// +// +typedef struct { + char acID[16]; // Initialized to "SEGGER RTT" + int MaxNumUpBuffers; // Initialized to SEGGER_RTT_MAX_NUM_UP_BUFFERS (type. 2) + int MaxNumDownBuffers; // Initialized to SEGGER_RTT_MAX_NUM_DOWN_BUFFERS (type. 2) + SEGGER_RTT_BUFFER_UP aUp[SEGGER_RTT_MAX_NUM_UP_BUFFERS]; // Up buffers, transferring information up from target via debug probe to host + SEGGER_RTT_BUFFER_DOWN aDown[SEGGER_RTT_MAX_NUM_DOWN_BUFFERS]; // Down buffers, transferring information down from host via debug probe to target +} SEGGER_RTT_CB; + +/********************************************************************* +* +* Global data +* +********************************************************************** +*/ +extern SEGGER_RTT_CB _SEGGER_RTT; + +/********************************************************************* +* +* RTT API functions +* +********************************************************************** +*/ +#ifdef __cplusplus + extern "C" { +#endif +int SEGGER_RTT_AllocDownBuffer (const char* sName, void* pBuffer, unsigned BufferSize, unsigned Flags); +int SEGGER_RTT_AllocUpBuffer (const char* sName, void* pBuffer, unsigned BufferSize, unsigned Flags); +int SEGGER_RTT_ConfigUpBuffer (unsigned BufferIndex, const char* sName, void* pBuffer, unsigned BufferSize, unsigned Flags); +int SEGGER_RTT_ConfigDownBuffer (unsigned BufferIndex, const char* sName, void* pBuffer, unsigned BufferSize, unsigned Flags); +int SEGGER_RTT_GetKey (void); +unsigned SEGGER_RTT_HasData (unsigned BufferIndex); +int SEGGER_RTT_HasKey (void); +void SEGGER_RTT_Init (void); +unsigned SEGGER_RTT_Read (unsigned BufferIndex, void* pBuffer, unsigned BufferSize); +unsigned SEGGER_RTT_ReadNoLock (unsigned BufferIndex, void* pData, unsigned BufferSize); +int SEGGER_RTT_SetNameDownBuffer (unsigned BufferIndex, const char* sName); +int SEGGER_RTT_SetNameUpBuffer (unsigned BufferIndex, const char* sName); +int SEGGER_RTT_SetFlagsDownBuffer (unsigned BufferIndex, unsigned Flags); +int SEGGER_RTT_SetFlagsUpBuffer (unsigned BufferIndex, unsigned Flags); +int SEGGER_RTT_WaitKey (void); +unsigned SEGGER_RTT_Write (unsigned BufferIndex, const void* pBuffer, unsigned NumBytes); +unsigned SEGGER_RTT_WriteNoLock (unsigned BufferIndex, const void* pBuffer, unsigned NumBytes); +unsigned SEGGER_RTT_WriteSkipNoLock (unsigned BufferIndex, const void* pBuffer, unsigned NumBytes); +unsigned SEGGER_RTT_WriteString (unsigned BufferIndex, const char* s); +void SEGGER_RTT_WriteWithOverwriteNoLock(unsigned BufferIndex, const void* pBuffer, unsigned NumBytes); +void SEGGER_RTT_ESP32_FlushNoLock (unsigned long min_sz, unsigned long tmo); +// +// Function macro for performance optimization +// +// @AGv: This macro is used inside SEGGER SystemView code. +// For ESP32 we use our own implementation of RTT, so this macro should not check SEGGER's RTT buffer state. +#define SEGGER_RTT_HASDATA(n) (1) + +/********************************************************************* +* +* RTT "Terminal" API functions +* +********************************************************************** +*/ +int SEGGER_RTT_SetTerminal (char TerminalId); +int SEGGER_RTT_TerminalOut (char TerminalId, const char* s); + +/********************************************************************* +* +* RTT printf functions (require SEGGER_RTT_printf.c) +* +********************************************************************** +*/ +int SEGGER_RTT_printf(unsigned BufferIndex, const char * sFormat, ...); +#ifdef __cplusplus + } +#endif + +/********************************************************************* +* +* Defines +* +********************************************************************** +*/ + +// +// Operating modes. Define behavior if buffer is full (not enough space for entire message) +// +#define SEGGER_RTT_MODE_NO_BLOCK_SKIP (0U) // Skip. Do not block, output nothing. (Default) +#define SEGGER_RTT_MODE_NO_BLOCK_TRIM (1U) // Trim: Do not block, output as much as fits. +#define SEGGER_RTT_MODE_BLOCK_IF_FIFO_FULL (2U) // Block: Wait until there is space in the buffer. +#define SEGGER_RTT_MODE_MASK (3U) + +// +// Control sequences, based on ANSI. +// Can be used to control color, and clear the screen +// +#define RTT_CTRL_RESET "" // Reset to default colors +#define RTT_CTRL_CLEAR "" // Clear screen, reposition cursor to top left + +#define RTT_CTRL_TEXT_BLACK "" +#define RTT_CTRL_TEXT_RED "" +#define RTT_CTRL_TEXT_GREEN "" +#define RTT_CTRL_TEXT_YELLOW "" +#define RTT_CTRL_TEXT_BLUE "" +#define RTT_CTRL_TEXT_MAGENTA "" +#define RTT_CTRL_TEXT_CYAN "" +#define RTT_CTRL_TEXT_WHITE "" + +#define RTT_CTRL_TEXT_BRIGHT_BLACK "" +#define RTT_CTRL_TEXT_BRIGHT_RED "" +#define RTT_CTRL_TEXT_BRIGHT_GREEN "" +#define RTT_CTRL_TEXT_BRIGHT_YELLOW "" +#define RTT_CTRL_TEXT_BRIGHT_BLUE "" +#define RTT_CTRL_TEXT_BRIGHT_MAGENTA "" +#define RTT_CTRL_TEXT_BRIGHT_CYAN "" +#define RTT_CTRL_TEXT_BRIGHT_WHITE "" + +#define RTT_CTRL_BG_BLACK "" +#define RTT_CTRL_BG_RED "" +#define RTT_CTRL_BG_GREEN "" +#define RTT_CTRL_BG_YELLOW "" +#define RTT_CTRL_BG_BLUE "" +#define RTT_CTRL_BG_MAGENTA "" +#define RTT_CTRL_BG_CYAN "" +#define RTT_CTRL_BG_WHITE "" + +#define RTT_CTRL_BG_BRIGHT_BLACK "" +#define RTT_CTRL_BG_BRIGHT_RED "" +#define RTT_CTRL_BG_BRIGHT_GREEN "" +#define RTT_CTRL_BG_BRIGHT_YELLOW "" +#define RTT_CTRL_BG_BRIGHT_BLUE "" +#define RTT_CTRL_BG_BRIGHT_MAGENTA "" +#define RTT_CTRL_BG_BRIGHT_CYAN "" +#define RTT_CTRL_BG_BRIGHT_WHITE "" + + +#endif + +/*************************** End of file ****************************/ diff --git a/components/app_trace/sys_view/SEGGER/SEGGER_SYSVIEW.c b/components/app_trace/sys_view/SEGGER/SEGGER_SYSVIEW.c new file mode 100644 index 0000000000..b588d723d0 --- /dev/null +++ b/components/app_trace/sys_view/SEGGER/SEGGER_SYSVIEW.c @@ -0,0 +1,2763 @@ +/********************************************************************* +* SEGGER Microcontroller GmbH & Co. KG * +* The Embedded Experts * +********************************************************************** +* * +* (c) 2015 - 2017 SEGGER Microcontroller GmbH & Co. KG * +* * +* www.segger.com Support: support@segger.com * +* * +********************************************************************** +* * +* SEGGER SystemView * Real-time application analysis * +* * +********************************************************************** +* * +* All rights reserved. * +* * +* SEGGER strongly recommends to not make any changes * +* to or modify the source code of this software in order to stay * +* compatible with the RTT protocol and J-Link. * +* * +* Redistribution and use in source and binary forms, with or * +* without modification, are permitted provided that the following * +* conditions are met: * +* * +* o Redistributions of source code must retain the above copyright * +* notice, this list of conditions and the following disclaimer. * +* * +* o Redistributions in binary form must reproduce the above * +* copyright notice, this list of conditions and the following * +* disclaimer in the documentation and/or other materials provided * +* with the distribution. * +* * +* o Neither the name of SEGGER Microcontroller GmbH & Co. KG * +* nor the names of its contributors may be used to endorse or * +* promote products derived from this software without specific * +* prior written permission. * +* * +* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * +* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * +* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * +* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * +* DISCLAIMED. IN NO EVENT SHALL SEGGER Microcontroller BE LIABLE FOR * +* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * +* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * +* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * +* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * +* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * +* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * +* DAMAGE. * +* * +********************************************************************** +* * +* SystemView version: V2.42 * +* * +********************************************************************** +-------------------------- END-OF-HEADER ----------------------------- + +File : SEGGER_SYSVIEW.c +Purpose : System visualization API implementation. +Revision: $Rev: 5927 $ + +Additional information: + Packet format: + Packets with IDs 0..23 are standard packets with known structure. + For efficiency, they do *NOT* contain a length field. + + + Packets with IDs 24..31 are standard packets with extendible + structure and contain a length field. + + + Packets with IDs >= 32 always contain a length field. + + + Packet IDs: + 0.. 31 : Standard packets, known by SystemViewer. + 32..1023 : OS-definable packets, described in a SystemView description file. + 1024..2047 : User-definable packets, described in a SystemView description file. + 2048..32767: Undefined. + + Data encoding: + Basic types (int, short, char, ...): + Basic types are encoded little endian with most-significant bit variant + encoding. + Each encoded byte contains 7 data bits [6:0] and the MSB continuation bit. + The continuation bit indicates whether the next byte belongs to the data + (bit set) or this is the last byte (bit clear). + The most significant bits of data are encoded first, proceeding to the + least significant bits in the final byte (little endian). + + Example encoding: + Data: 0x1F4 (500) + Encoded: 0xF4 (First 7 data bits 74 | Continuation bit) + 0x03 (Second 7 data bits 03, no continuation) + + Data: 0xFFFFFFFF + Encoded: 0xFF 0xFF 0xFF 0xFF 0x0F + + Data: 0xA2 (162), 0x03 (3), 0x7000 + Encoded: 0xA2 0x01 0x03 0x80 0xE0 0x01 + + Byte arrays and strings: + Byte arrays and strings are encoded as followed by the raw data. + NumBytes is encoded as a basic type with a theoretical maximum of 4G. + + Example encoding: + Data: "Hello World\0" (0x48 0x65 0x6C 0x6C 0x6F 0x20 0x57 0x6F 0x72 0x6C 0x64 0x00) + Encoded: 0x0B 0x48 0x65 0x6C 0x6C 0x6F 0x20 0x57 0x6F 0x72 0x6C 0x64 + + Examples packets: + 01 F4 03 80 80 10 // Overflow packet. Data is a single U32. + This packet means: 500 packets lost, Timestamp is 0x40000 + + 02 0F 50 // ISR(15) Enter. Timestamp 80 (0x50) + + 03 20 // ISR Exit. Timestamp 32 (0x20) (Shortest possible packet.) + + Sample code for user defined Packets: + #define MY_ID 0x400 // Any value between 0x400 and 0x7FF + void SendMyPacket(unsigned Para0, unsigned Para1, const char* s) { + U8 aPacket[SEGGER_SYSVIEW_INFO_SIZE + 2 * SEGGER_SYSVIEW_QUANTA_U32 + MAX_STR_LEN + 1]; + U8* pPayload; + // + pPayload = SEGGER_SYSVIEW_PPREPARE_PACKET(aPacket); // Prepare the packet for SystemView + pPayload = SEGGER_SYSVIEW_EncodeU32(pPayload, Para0); // Add the first parameter to the packet + pPayload = SEGGER_SYSVIEW_EncodeU32(pPayload, Para1); // Add the second parameter to the packet + pPayload = SEGGER_SYSVIEW_EncodeString(pPayload, s, MAX_STR_LEN); // Add the string to the packet + // + SEGGER_SYSVIEW_SendPacket(&aPacket[0], pPayload, MY_ID); // Send the packet with EventId = MY_ID + } + + #define MY_ID_1 0x401 + void SendOnePara(unsigned Para0) { + SEGGER_SYSVIEW_RecordU32(MY_ID_1, Para0); + } + +*/ + +/********************************************************************* +* +* #include section +* +********************************************************************** +*/ + +#include "SEGGER_SYSVIEW_Int.h" +#include "SEGGER_RTT.h" +#include +#include +#include + +/********************************************************************* +* +* Defines, fixed +* +********************************************************************** +*/ +#if SEGGER_SYSVIEW_ID_SHIFT + #define SHRINK_ID(Id) (((Id) - _SYSVIEW_Globals.RAMBaseAddress) >> SEGGER_SYSVIEW_ID_SHIFT) +#else + #define SHRINK_ID(Id) ((Id) - _SYSVIEW_Globals.RAMBaseAddress) +#endif + +#if SEGGER_SYSVIEW_RTT_CHANNEL > 0 + #define CHANNEL_ID_UP SEGGER_SYSVIEW_RTT_CHANNEL + #define CHANNEL_ID_DOWN SEGGER_SYSVIEW_RTT_CHANNEL +#else + #define CHANNEL_ID_UP _SYSVIEW_Globals.UpChannel + #define CHANNEL_ID_DOWN _SYSVIEW_Globals.DownChannel +#endif + +/********************************************************************* +* +* Defines, configurable +* +********************************************************************** +*/ +// Timestamps may be less than full 32-bits, in which case we need to zero +// the unused bits to properly handle overflows. +// Note that this is a quite common scenario, as a 32-bit time such as +// SysTick might be scaled down to reduce bandwith +// or a 16-bit hardware time might be used. +#if SEGGER_SYSVIEW_TIMESTAMP_BITS < 32 // Eliminate unused bits in case hardware timestamps are less than 32 bits + #define MAKE_DELTA_32BIT(Delta) Delta <<= 32 - SEGGER_SYSVIEW_TIMESTAMP_BITS; \ + Delta >>= 32 - SEGGER_SYSVIEW_TIMESTAMP_BITS; +#else + #define MAKE_DELTA_32BIT(Delta) +#endif + + +/********************************************************************* +* +* Defines, fixed +* +********************************************************************** +*/ +#define ENABLE_STATE_OFF 0 +#define ENABLE_STATE_ON 1 +#define ENABLE_STATE_DROPPING 2 + +#define FORMAT_FLAG_LEFT_JUSTIFY (1u << 0) +#define FORMAT_FLAG_PAD_ZERO (1u << 1) +#define FORMAT_FLAG_PRINT_SIGN (1u << 2) +#define FORMAT_FLAG_ALTERNATE (1u << 3) + +#define MODULE_EVENT_OFFSET (512) + +/********************************************************************* +* +* Types, local +* +********************************************************************** +*/ +typedef struct { + U8* pBuffer; + U8* pPayload; + U8* pPayloadStart; + U32 Options; + unsigned Cnt; +} SEGGER_SYSVIEW_PRINTF_DESC; + +typedef struct { + U8 EnableState; // 0: Disabled, 1: Enabled, (2: Dropping) + U8 UpChannel; + U8 RecursionCnt; + U32 SysFreq; + U32 CPUFreq; + U32 LastTxTimeStamp; + U32 RAMBaseAddress; +#if (SEGGER_SYSVIEW_POST_MORTEM_MODE == 1) + U32 PacketCount; +#else + U32 DropCount; + U8 DownChannel; +#endif + U32 DisabledEvents; + const SEGGER_SYSVIEW_OS_API* pOSAPI; + SEGGER_SYSVIEW_SEND_SYS_DESC_FUNC* pfSendSysDesc; +} SEGGER_SYSVIEW_GLOBALS; + +/********************************************************************* +* +* Function prototypes, required +* +********************************************************************** +*/ +static void _SendPacket(U8* pStartPacket, U8* pEndPacket, unsigned int EventId); + +/********************************************************************* +* +* Static data +* +********************************************************************** +*/ +static const U8 _abSync[10] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; + +#ifdef SEGGER_SYSVIEW_SECTION + #if (defined __GNUC__) + __attribute__ ((section (SEGGER_SYSVIEW_SECTION))) static char _UpBuffer [SEGGER_SYSVIEW_RTT_BUFFER_SIZE]; + #if (SEGGER_SYSVIEW_POST_MORTEM_MODE != 1) + __attribute__ ((section (SEGGER_SYSVIEW_SECTION))) static char _DownBuffer[8]; // Small, fixed-size buffer, for back-channel comms + #endif + #elif (defined __ICCARM__) || (defined __ICCRX__) + #pragma location=SEGGER_SYSVIEW_SECTION + static char _UpBuffer [SEGGER_SYSVIEW_RTT_BUFFER_SIZE]; + #pragma location=SEGGER_SYSVIEW_SECTION + static char _DownBuffer[8]; // Small, fixed-size buffer, for back-channel comms + #elif (defined __CC_ARM) + __attribute__ ((section (SEGGER_SYSVIEW_SECTION), zero_init)) static char _UpBuffer [SEGGER_SYSVIEW_RTT_BUFFER_SIZE]; + #if (SEGGER_SYSVIEW_POST_MORTEM_MODE != 1) + __attribute__ ((section (SEGGER_SYSVIEW_SECTION), zero_init)) static char _DownBuffer[8]; // Small, fixed-size buffer, for back-channel comms + #endif + #else + static char _UpBuffer [SEGGER_SYSVIEW_RTT_BUFFER_SIZE]; + #if (SEGGER_SYSVIEW_POST_MORTEM_MODE != 1) + static char _DownBuffer[8]; // Small, fixed-size buffer, for back-channel comms + #endif + #endif +#else + static char _UpBuffer [SEGGER_SYSVIEW_RTT_BUFFER_SIZE]; + #if (SEGGER_SYSVIEW_POST_MORTEM_MODE != 1) + static char _DownBuffer[8]; // Small, fixed-size buffer, for back-channel comms + #endif +#endif + +static SEGGER_SYSVIEW_GLOBALS _SYSVIEW_Globals; + +static SEGGER_SYSVIEW_MODULE* _pFirstModule; +static U8 _NumModules; + +/********************************************************************* +* +* Static code +* +********************************************************************** +*/ + +#define ENCODE_U32(pDest, Value) { \ + U8* pSysviewPointer; \ + U32 SysViewData; \ + pSysviewPointer = pDest; \ + SysViewData = Value; \ + while(SysViewData > 0x7F) { \ + *pSysviewPointer++ = (U8)(SysViewData | 0x80); \ + SysViewData >>= 7; \ + }; \ + *pSysviewPointer++ = (U8)SysViewData; \ + pDest = pSysviewPointer; \ + }; + + + +#if (SEGGER_SYSVIEW_USE_STATIC_BUFFER == 1) +static U8 _aPacket[SEGGER_SYSVIEW_MAX_PACKET_SIZE]; + +#define RECORD_START(PacketSize) SEGGER_SYSVIEW_LOCK(); \ + pPayloadStart = _PreparePacket(_aPacket); + +#define RECORD_END() SEGGER_SYSVIEW_UNLOCK() + +#else + +#define RECORD_START(PacketSize) U8 aPacket[(PacketSize)]; \ + pPayloadStart = _PreparePacket(aPacket); \ + +#define RECORD_END() + +#endif + +/********************************************************************* +* +* _EncodeData() +* +* Function description +* Encode a byte buffer in variable-length format. +* +* Parameters +* pPayload - Pointer to where string will be encoded. +* pSrc - Pointer to data buffer to be encoded. +* NumBytes - Number of bytes in the buffer to be encoded. +* +* Return value +* Pointer to the byte following the value, i.e. the first free +* byte in the payload and the next position to store payload +* content. +* +* Additional information +* The data is encoded as a count byte followed by the contents +* of the data buffer. +* Make sure NumBytes + 1 bytes are free for the payload. +*/ +static U8* _EncodeData(U8* pPayload, const char* pSrc, unsigned int NumBytes) { + unsigned int n; + // + n = 0; + *pPayload++ = NumBytes; + while (n < NumBytes) { + *pPayload++ = *pSrc++; + n++; + } + return pPayload; +} + +/********************************************************************* +* +* _EncodeStr() +* +* Function description +* Encode a string in variable-length format. +* +* Parameters +* pPayload - Pointer to where string will be encoded. +* pText - String to encode. +* Limit - Maximum number of characters to encode from string. +* +* Return value +* Pointer to the byte following the value, i.e. the first free +* byte in the payload and the next position to store payload +* content. +* +* Additional information +* The string is encoded as a count byte followed by the contents +* of the string. +* No more than 1 + Limit bytes will be encoded to the payload. +*/ +static U8 *_EncodeStr(U8 *pPayload, const char *pText, unsigned int Limit) { + unsigned int n; + unsigned int Len; + // + // Compute string len + // + Len = 0; + while(*(pText + Len) != 0) { + Len++; + } + if (Len > Limit) { + Len = Limit; + } + // + // Write Len + // + if (Len < 255) { + *pPayload++ = Len; + } else { + *pPayload++ = 255; + *pPayload++ = (Len & 255); + *pPayload++ = ((Len >> 8) & 255); + } + // + // copy string + // + n = 0; + while (n < Len) { + *pPayload++ = *pText++; + n++; + } + return pPayload; +} + +/********************************************************************* +* +* _PreparePacket() +* +* Function description +* Prepare a SystemView event packet header. +* +* Parameters +* pPacket - Pointer to start of packet to initialize. +* +* Return value +* Pointer to first byte of packet payload. +* +* Additional information +* The payload length and evnetId are not initialized. +* PreparePacket only reserves space for them and they are +* computed and filled in by the sending function. +*/ +static U8* _PreparePacket(U8* pPacket) { + return pPacket + 4; +} + +/********************************************************************* +* +* _HandleIncomingPacket() +* +* Function description +* Read an incoming command from the down channel and process it. +* +* Additional information +* This function is called each time after sending a packet. +* Processing incoming packets is done asynchronous. SystemView might +* already have sent event packets after the host has sent a command. +*/ +#if (SEGGER_SYSVIEW_POST_MORTEM_MODE != 1) +static void _HandleIncomingPacket(void) { + U8 Cmd; + int Status; + // + Status = SEGGER_RTT_ReadNoLock(CHANNEL_ID_DOWN, &Cmd, 1); + if (Status > 0) { + switch (Cmd) { + case SEGGER_SYSVIEW_COMMAND_ID_START: + SEGGER_SYSVIEW_Start(); + break; + case SEGGER_SYSVIEW_COMMAND_ID_STOP: + SEGGER_SYSVIEW_Stop(); + break; + case SEGGER_SYSVIEW_COMMAND_ID_GET_SYSTIME: + SEGGER_SYSVIEW_RecordSystime(); + break; + case SEGGER_SYSVIEW_COMMAND_ID_GET_TASKLIST: + SEGGER_SYSVIEW_SendTaskList(); + break; + case SEGGER_SYSVIEW_COMMAND_ID_GET_SYSDESC: + SEGGER_SYSVIEW_GetSysDesc(); + break; + case SEGGER_SYSVIEW_COMMAND_ID_GET_NUMMODULES: + SEGGER_SYSVIEW_SendNumModules(); + break; + case SEGGER_SYSVIEW_COMMAND_ID_GET_MODULEDESC: + SEGGER_SYSVIEW_SendModuleDescription(); + break; + case SEGGER_SYSVIEW_COMMAND_ID_GET_MODULE: + Status = SEGGER_RTT_ReadNoLock(CHANNEL_ID_DOWN, &Cmd, 1); + if (Status > 0) { + SEGGER_SYSVIEW_SendModule(Cmd); + } + break; + default: + if (Cmd >= 128) { // Unknown extended command. Dummy read its parameter. + SEGGER_RTT_ReadNoLock(CHANNEL_ID_DOWN, &Cmd, 1); + } + break; + } + } +} +#endif // (SEGGER_SYSVIEW_POST_MORTEM_MODE != 1) + +/********************************************************************* +* +* _TrySendOverflowPacket() +* +* Function description +* Try to transmit an SystemView Overflow packet containing the +* number of dropped packets. +* +* Additional information +* Format as follows: +* 01 Max. packet len is 1 + 5 + 5 = 11 +* +* Example packets sent +* 01 20 40 +* +* Return value +* !=0: Success, Message sent (stored in RTT-Buffer) +* ==0: Buffer full, Message *NOT* stored +* +*/ +#if (SEGGER_SYSVIEW_POST_MORTEM_MODE != 1) +static int _TrySendOverflowPacket(void) { + U32 TimeStamp; + I32 Delta; + int Status; + U8 aPacket[11]; + U8* pPayload; + + aPacket[0] = SYSVIEW_EVTID_OVERFLOW; // 1 + pPayload = &aPacket[1]; + ENCODE_U32(pPayload, _SYSVIEW_Globals.DropCount); + // + // Compute time stamp delta and append it to packet. + // + TimeStamp = SEGGER_SYSVIEW_GET_TIMESTAMP(); + Delta = TimeStamp - _SYSVIEW_Globals.LastTxTimeStamp; + MAKE_DELTA_32BIT(Delta); + ENCODE_U32(pPayload, Delta); + // + // Try to store packet in RTT buffer and update time stamp when this was successful + // + Status = SEGGER_RTT_WriteSkipNoLock(CHANNEL_ID_UP, aPacket, pPayload - aPacket); + if (Status) { + _SYSVIEW_Globals.LastTxTimeStamp = TimeStamp; + _SYSVIEW_Globals.EnableState--; // EnableState has been 2, will be 1. Always. + } else { + _SYSVIEW_Globals.DropCount++; + } + // + return Status; +} +#endif // (SEGGER_SYSVIEW_POST_MORTEM_MODE != 1) + +/********************************************************************* +* +* _SendSyncInfo() +* +* Function description +* Send SystemView sync packet and system information in +* post mortem mode. +* +* Additional information +* Sync is 10 * 0x00 without timestamp +*/ +#if (SEGGER_SYSVIEW_POST_MORTEM_MODE == 1) +static void _SendSyncInfo(void) { + // + // Add sync packet ( 10 * 0x00) + // Send system description + // Send system time + // Send task list + // Send module description + // Send module information + // + SEGGER_RTT_WriteWithOverwriteNoLock(CHANNEL_ID_UP, _abSync, 10); + SEGGER_SYSVIEW_RecordVoid(SYSVIEW_EVTID_TRACE_START); + { + U8* pPayload; + U8* pPayloadStart; + RECORD_START(SEGGER_SYSVIEW_INFO_SIZE + 4 * SEGGER_SYSVIEW_QUANTA_U32); + // + pPayload = pPayloadStart; + ENCODE_U32(pPayload, _SYSVIEW_Globals.SysFreq); + ENCODE_U32(pPayload, _SYSVIEW_Globals.CPUFreq); + ENCODE_U32(pPayload, _SYSVIEW_Globals.RAMBaseAddress); + ENCODE_U32(pPayload, SEGGER_SYSVIEW_ID_SHIFT); + _SendPacket(pPayloadStart, pPayload, SYSVIEW_EVTID_INIT); + RECORD_END(); + } + if (_SYSVIEW_Globals.pfSendSysDesc) { + _SYSVIEW_Globals.pfSendSysDesc(); + } + SEGGER_SYSVIEW_RecordSystime(); + SEGGER_SYSVIEW_SendTaskList(); + if (_NumModules > 0) { + SEGGER_SYSVIEW_SendNumModules(); + for (int n = 0; n < _NumModules; n++) { + SEGGER_SYSVIEW_SendModule(n); + } + SEGGER_SYSVIEW_SendModuleDescription(); + } +} +#endif // (SEGGER_SYSVIEW_POST_MORTEM_MODE == 1) + +/********************************************************************* +* +* _SendPacket() +* +* Function description +* Send a SystemView packet over RTT. RTT channel and mode are +* configured by macros when the SystemView component is initialized. +* This function takes care of maintaining the packet drop count +* and sending overflow packets when necessary. +* The packet must be passed without Id and Length because this +* function prepends it to the packet before transmission. +* +* Parameters +* pStartPacket - Pointer to start of packet payload. +* There must be at least 4 bytes free to prepend Id and Length. +* pEndPacket - Pointer to end of packet payload. +* EventId - Id of the event to send. +* +*/ +static void _SendPacket(U8* pStartPacket, U8* pEndPacket, unsigned int EventId) { + unsigned int NumBytes; + U32 TimeStamp; + U32 Delta; +#if (SEGGER_SYSVIEW_POST_MORTEM_MODE != 1) + int Status; +#endif + +#if (SEGGER_SYSVIEW_USE_STATIC_BUFFER == 0) + SEGGER_SYSVIEW_LOCK(); +#endif + +#if (SEGGER_SYSVIEW_POST_MORTEM_MODE == 1) + if (_SYSVIEW_Globals.EnableState == 0) { + goto SendDone; + } +#else + if (_SYSVIEW_Globals.EnableState == 1) { // Enabled, no dropped packets remaining + goto Send; + } + if (_SYSVIEW_Globals.EnableState == 0) { + goto SendDone; + } + // + // Handle buffer full situations: + // Have packets been dropped before because buffer was full? + // In this case try to send and overflow packet. + // + if (_SYSVIEW_Globals.EnableState == 2) { + _TrySendOverflowPacket(); + if (_SYSVIEW_Globals.EnableState != 1) { + goto SendDone; + } + } +Send: +#endif + // + // Check if event is disabled from being recorded. + // + if (EventId < 32) { + if (_SYSVIEW_Globals.DisabledEvents & ((U32)1u << EventId)) { + goto SendDone; + } + } + // + // Prepare actual packet. + // If it is a known packet, prepend eventId only, + // otherwise prepend packet length and eventId. + // + if (EventId < 24) { + *--pStartPacket = EventId; + } else { + NumBytes = pEndPacket - pStartPacket; + if (NumBytes > 127) { + *--pStartPacket = (NumBytes >> 7); + *--pStartPacket = NumBytes | 0x80; + } else { + *--pStartPacket = NumBytes; + } + if (EventId > 127) { + *--pStartPacket = (EventId >> 7); + *--pStartPacket = EventId | 0x80; + } else { + *--pStartPacket = EventId; + } + } + // + // Compute time stamp delta and append it to packet. + // + TimeStamp = SEGGER_SYSVIEW_GET_TIMESTAMP(); + Delta = TimeStamp - _SYSVIEW_Globals.LastTxTimeStamp; + MAKE_DELTA_32BIT(Delta); + ENCODE_U32(pEndPacket, Delta); +#if (SEGGER_SYSVIEW_POST_MORTEM_MODE == 1) + // + // Store packet in RTT buffer by overwriting old data and update time stamp + // + SEGGER_RTT_WriteWithOverwriteNoLock(CHANNEL_ID_UP, pStartPacket, pEndPacket - pStartPacket); + _SYSVIEW_Globals.LastTxTimeStamp = TimeStamp; +#else + // + // Try to store packet in RTT buffer and update time stamp when this was successful + // + Status = SEGGER_RTT_WriteSkipNoLock(CHANNEL_ID_UP, pStartPacket, pEndPacket - pStartPacket); + if (Status) { + _SYSVIEW_Globals.LastTxTimeStamp = TimeStamp; + } else { + _SYSVIEW_Globals.EnableState++; // EnableState has been 1, will be 2. Always. + } +#endif + +#if (SEGGER_SYSVIEW_POST_MORTEM_MODE == 1) + // + // Add sync and system information periodically if we are in post mortem mode + // + if (_SYSVIEW_Globals.RecursionCnt == 0) { // Avoid uncontrolled nesting. This way, this routine can call itself once, but no more often than that. + _SYSVIEW_Globals.RecursionCnt = 1; + if (_SYSVIEW_Globals.PacketCount++ & (1 << SEGGER_SYSVIEW_SYNC_PERIOD_SHIFT)) { + _SendSyncInfo(); + _SYSVIEW_Globals.PacketCount = 0; + } + _SYSVIEW_Globals.RecursionCnt = 0; + } +SendDone: + ; // Avoid "label at end of compound statement" error when using static buffer +#else +SendDone: + // + // Check if host is sending data which needs to be processed. + // Note that since this code is called for every packet, it is very time critical, so we do + // only what is really needed here, which is checking if there is any data + // + if (SEGGER_RTT_HASDATA(CHANNEL_ID_DOWN)) { + if (_SYSVIEW_Globals.RecursionCnt == 0) { // Avoid uncontrolled nesting. This way, this routine can call itself once, but no more often than that. + _SYSVIEW_Globals.RecursionCnt = 1; + _HandleIncomingPacket(); + _SYSVIEW_Globals.RecursionCnt = 0; + } + } +#endif + // +#if (SEGGER_SYSVIEW_USE_STATIC_BUFFER == 0) + SEGGER_SYSVIEW_UNLOCK(); // We are done. Unlock and return +#endif +} + +#ifndef SEGGER_SYSVIEW_EXCLUDE_PRINTF // Define in project to avoid warnings about variable parameter list +/********************************************************************* +* +* _APrintHost() +* +* Function description +* Prepares a string and its parameters to be formatted on the host. +* +* Parameters +* s Pointer to format string. +* Options Options to be sent to the host. +* pArguments Pointer to array of arguments for the format string. +* NumArguments Number of arguments in the array. +*/ +static void _APrintHost(const char* s, U32 Options, U32* pArguments, U32 NumArguments) { + U8* pPayload; + U8* pPayloadStart; + + RECORD_START(SEGGER_SYSVIEW_INFO_SIZE + SEGGER_SYSVIEW_MAX_STRING_LEN + 2 * SEGGER_SYSVIEW_QUANTA_U32 + SEGGER_SYSVIEW_MAX_ARGUMENTS * SEGGER_SYSVIEW_QUANTA_U32); + pPayload = _EncodeStr(pPayloadStart, s, SEGGER_SYSVIEW_MAX_STRING_LEN); + ENCODE_U32(pPayload, Options); + ENCODE_U32(pPayload, NumArguments); + while (NumArguments--) { + ENCODE_U32(pPayload, (*pArguments++)); + } + _SendPacket(pPayloadStart, pPayload, SYSVIEW_EVTID_PRINT_FORMATTED); + RECORD_END(); +} + +/********************************************************************* +* +* _VPrintHost() +* +* Function description +* Prepares a string and its parameters to be formatted on the host. +* +* Parameters +* s Pointer to format string. +* Options Options to be sent to the host. +* pParamList Pointer to the list of arguments for the format string. +*/ +static void _VPrintHost(const char* s, U32 Options, va_list* pParamList) { + U32 aParas[SEGGER_SYSVIEW_MAX_ARGUMENTS]; + U32 NumArguments; + const char* p; + + p = s; + NumArguments = 0; + while (*p) { + if (*p == '%') { + aParas[NumArguments++] = va_arg(*pParamList, int); + if (NumArguments == SEGGER_SYSVIEW_MAX_ARGUMENTS) { + break; + } + } + p++; + } + _APrintHost(s, Options, aParas, NumArguments); +} + +/********************************************************************* +* +* _StoreChar() +* +* Function description +* Stores a character in the printf-buffer and sends the buffer when +* it is filled. +* +* Parameters +* p Pointer to the buffer description. +* c Character to be printed. +*/ +static void _StoreChar(SEGGER_SYSVIEW_PRINTF_DESC * p, char c) { + unsigned int Cnt; + U8* pPayload; + U32 Options; + + Cnt = p->Cnt; + if ((Cnt + 1u) <= SEGGER_SYSVIEW_MAX_STRING_LEN) { + *(p->pPayload++) = c; + p->Cnt = Cnt + 1u; + } + // + // Write part of string, when the buffer is full + // + if (p->Cnt == SEGGER_SYSVIEW_MAX_STRING_LEN) { + *(p->pPayloadStart) = p->Cnt; + pPayload = p->pPayload; + Options = p->Options; + ENCODE_U32(pPayload, Options); + ENCODE_U32(pPayload, 0); + _SendPacket(p->pPayloadStart, pPayload, SYSVIEW_EVTID_PRINT_FORMATTED); + p->pPayloadStart = _PreparePacket(p->pBuffer); + p->pPayload = p->pPayloadStart + 1u; + p->Cnt = 0u; + } +} + +/********************************************************************* +* +* _PrintUnsigned() +* +* Function description +* Print an unsigned integer with the given formatting into the +* formatted string. +* +* Parameters +* pBufferDesc Pointer to the buffer description. +* v Value to be printed. +* Base Base of the value. +* NumDigits Number of digits to be printed. +* FieldWidth Width of the printed field. +* FormatFlags Flags for formatting the value. +*/ +static void _PrintUnsigned(SEGGER_SYSVIEW_PRINTF_DESC * pBufferDesc, unsigned int v, unsigned int Base, unsigned int NumDigits, unsigned int FieldWidth, unsigned int FormatFlags) { + static const char _aV2C[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; + unsigned int Div; + unsigned int Digit; + unsigned int Number; + unsigned int Width; + char c; + + Number = v; + Digit = 1u; + // + // Get actual field width + // + Width = 1u; + while (Number >= Base) { + Number = (Number / Base); + Width++; + } + if (NumDigits > Width) { + Width = NumDigits; + } + // + // Print leading chars if necessary + // + if ((FormatFlags & FORMAT_FLAG_LEFT_JUSTIFY) == 0u) { + if (FieldWidth != 0u) { + if (((FormatFlags & FORMAT_FLAG_PAD_ZERO) == FORMAT_FLAG_PAD_ZERO) && (NumDigits == 0u)) { + c = '0'; + } else { + c = ' '; + } + while ((FieldWidth != 0u) && (Width < FieldWidth)) { + FieldWidth--; + _StoreChar(pBufferDesc, c); + } + } + } + // + // Compute Digit. + // Loop until Digit has the value of the highest digit required. + // Example: If the output is 345 (Base 10), loop 2 times until Digit is 100. + // + while (1) { + if (NumDigits > 1u) { // User specified a min number of digits to print? => Make sure we loop at least that often, before checking anything else (> 1 check avoids problems with NumDigits being signed / unsigned) + NumDigits--; + } else { + Div = v / Digit; + if (Div < Base) { // Is our divider big enough to extract the highest digit from value? => Done + break; + } + } + Digit *= Base; + } + // + // Output digits + // + do { + Div = v / Digit; + v -= Div * Digit; + _StoreChar(pBufferDesc, _aV2C[Div]); + Digit /= Base; + } while (Digit); + // + // Print trailing spaces if necessary + // + if ((FormatFlags & FORMAT_FLAG_LEFT_JUSTIFY) == FORMAT_FLAG_LEFT_JUSTIFY) { + if (FieldWidth != 0u) { + while ((FieldWidth != 0u) && (Width < FieldWidth)) { + FieldWidth--; + _StoreChar(pBufferDesc, ' '); + } + } + } +} + +/********************************************************************* +* +* _PrintInt() +* +* Function description +* Print a signed integer with the given formatting into the +* formatted string. +* +* Parameters +* pBufferDesc Pointer to the buffer description. +* v Value to be printed. +* Base Base of the value. +* NumDigits Number of digits to be printed. +* FieldWidth Width of the printed field. +* FormatFlags Flags for formatting the value. +*/ +static void _PrintInt(SEGGER_SYSVIEW_PRINTF_DESC * pBufferDesc, int v, unsigned int Base, unsigned int NumDigits, unsigned int FieldWidth, unsigned int FormatFlags) { + unsigned int Width; + int Number; + + Number = (v < 0) ? -v : v; + + // + // Get actual field width + // + Width = 1u; + while (Number >= (int)Base) { + Number = (Number / (int)Base); + Width++; + } + if (NumDigits > Width) { + Width = NumDigits; + } + if ((FieldWidth > 0u) && ((v < 0) || ((FormatFlags & FORMAT_FLAG_PRINT_SIGN) == FORMAT_FLAG_PRINT_SIGN))) { + FieldWidth--; + } + + // + // Print leading spaces if necessary + // + if ((((FormatFlags & FORMAT_FLAG_PAD_ZERO) == 0u) || (NumDigits != 0u)) && ((FormatFlags & FORMAT_FLAG_LEFT_JUSTIFY) == 0u)) { + if (FieldWidth != 0u) { + while ((FieldWidth != 0u) && (Width < FieldWidth)) { + FieldWidth--; + _StoreChar(pBufferDesc, ' '); + } + } + } + // + // Print sign if necessary + // + if (v < 0) { + v = -v; + _StoreChar(pBufferDesc, '-'); + } else if ((FormatFlags & FORMAT_FLAG_PRINT_SIGN) == FORMAT_FLAG_PRINT_SIGN) { + _StoreChar(pBufferDesc, '+'); + } else { + + } + // + // Print leading zeros if necessary + // + if (((FormatFlags & FORMAT_FLAG_PAD_ZERO) == FORMAT_FLAG_PAD_ZERO) && ((FormatFlags & FORMAT_FLAG_LEFT_JUSTIFY) == 0u) && (NumDigits == 0u)) { + if (FieldWidth != 0u) { + while ((FieldWidth != 0u) && (Width < FieldWidth)) { + FieldWidth--; + _StoreChar(pBufferDesc, '0'); + } + } + } + // + // Print number without sign + // + _PrintUnsigned(pBufferDesc, (unsigned int)v, Base, NumDigits, FieldWidth, FormatFlags); +} + +/********************************************************************* +* +* _VPrintTarget() +* +* Function description +* Stores a formatted string. +* This data is read by the host. +* +* Parameters +* sFormat Pointer to format string. +* Options Options to be sent to the host. +* pParamList Pointer to the list of arguments for the format string. +*/ +static void _VPrintTarget(const char* sFormat, U32 Options, va_list* pParamList) { + SEGGER_SYSVIEW_PRINTF_DESC BufferDesc; + char c; + int v; + unsigned int NumDigits; + unsigned int FormatFlags; + unsigned int FieldWidth; + U8* pPayloadStart; +#if SEGGER_SYSVIEW_USE_STATIC_BUFFER == 0 + RECORD_START(SEGGER_SYSVIEW_INFO_SIZE + SEGGER_SYSVIEW_MAX_STRING_LEN + 1 + 2 * SEGGER_SYSVIEW_QUANTA_U32); + SEGGER_SYSVIEW_LOCK(); +#else + RECORD_START(SEGGER_SYSVIEW_INFO_SIZE + SEGGER_SYSVIEW_MAX_STRING_LEN + 1 + 2 * SEGGER_SYSVIEW_QUANTA_U32); +#endif + +#if SEGGER_SYSVIEW_USE_STATIC_BUFFER == 0 + BufferDesc.pBuffer = aPacket; +#else + BufferDesc.pBuffer = _aPacket; +#endif + BufferDesc.Cnt = 0u; + BufferDesc.pPayloadStart = pPayloadStart; + BufferDesc.pPayload = BufferDesc.pPayloadStart + 1u; + BufferDesc.Options = Options; + + do { + c = *sFormat; + sFormat++; + if (c == 0u) { + break; + } + if (c == '%') { + // + // Filter out flags + // + FormatFlags = 0u; + v = 1; + do { + c = *sFormat; + switch (c) { + case '-': FormatFlags |= FORMAT_FLAG_LEFT_JUSTIFY; sFormat++; break; + case '0': FormatFlags |= FORMAT_FLAG_PAD_ZERO; sFormat++; break; + case '+': FormatFlags |= FORMAT_FLAG_PRINT_SIGN; sFormat++; break; + case '#': FormatFlags |= FORMAT_FLAG_ALTERNATE; sFormat++; break; + default: v = 0; break; + } + } while (v); + // + // filter out field with + // + FieldWidth = 0u; + do { + c = *sFormat; + if ((c < '0') || (c > '9')) { + break; + } + sFormat++; + FieldWidth = (FieldWidth * 10u) + ((unsigned int)c - '0'); + } while (1); + + // + // Filter out precision (number of digits to display) + // + NumDigits = 0u; + c = *sFormat; + if (c == '.') { + sFormat++; + do { + c = *sFormat; + if ((c < '0') || (c > '9')) { + break; + } + sFormat++; + NumDigits = NumDigits * 10u + ((unsigned int)c - '0'); + } while (1); + } + // + // Filter out length modifier + // + c = *sFormat; + do { + if ((c == 'l') || (c == 'h')) { + c = *sFormat; + sFormat++; + } else { + break; + } + } while (1); + // + // Handle specifiers + // + switch (c) { + case 'c': { + char c0; + v = va_arg(*pParamList, int); + c0 = (char)v; + _StoreChar(&BufferDesc, c0); + break; + } + case 'd': + v = va_arg(*pParamList, int); + _PrintInt(&BufferDesc, v, 10u, NumDigits, FieldWidth, FormatFlags); + break; + case 'u': + v = va_arg(*pParamList, int); + _PrintUnsigned(&BufferDesc, (unsigned int)v, 10u, NumDigits, FieldWidth, FormatFlags); + break; + case 'x': + case 'X': + v = va_arg(*pParamList, int); + _PrintUnsigned(&BufferDesc, (unsigned int)v, 16u, NumDigits, FieldWidth, FormatFlags); + break; + case 'p': + v = va_arg(*pParamList, int); + _PrintUnsigned(&BufferDesc, (unsigned int)v, 16u, 8u, 8u, 0u); + break; + case '%': + _StoreChar(&BufferDesc, '%'); + break; + default: + break; + } + sFormat++; + } else { + _StoreChar(&BufferDesc, c); + } + } while (*sFormat); + + // + // Write remaining data, if any + // + if (BufferDesc.Cnt != 0u) { + *(BufferDesc.pPayloadStart) = BufferDesc.Cnt; + ENCODE_U32(BufferDesc.pPayload, BufferDesc.Options); + ENCODE_U32(BufferDesc.pPayload, 0); + _SendPacket(BufferDesc.pPayloadStart, BufferDesc.pPayload, SYSVIEW_EVTID_PRINT_FORMATTED); + } +#if SEGGER_SYSVIEW_USE_STATIC_BUFFER == 0 + SEGGER_SYSVIEW_UNLOCK(); + RECORD_END(); +#else + RECORD_END(); +#endif +} +#endif // SEGGER_SYSVIEW_EXCLUDE_PRINTF + +/********************************************************************* +* +* Public functions +* +********************************************************************** +*/ + +/********************************************************************* +* +* SEGGER_SYSVIEW_Init() +* +* Function description +* Initializes the SYSVIEW module. +* Must be called before SystemViewer attaches to the system. +* +* Parameters +* SysFreq - Frequency of timestamp, i.e. CPU core clock frequency. +* CPUFreq - CPU core clock frequency. +* pOSAPI - Pointer to the API structure for OS-specific functions. +* pfSendSysDesc - Pointer to SendSysDesc callback function. +* +* Additional information +* This function initializes the RTT channel used to transport +* SEGGER SystemView packets. +* The channel is assigned the label "SysView" for client software +* to identify the SystemView channel. +* +* Notes +* The channel is configured by the macro SEGGER_SYSVIEW_RTT_CHANNEL. +*/ +void SEGGER_SYSVIEW_Init(U32 SysFreq, U32 CPUFreq, const SEGGER_SYSVIEW_OS_API *pOSAPI, SEGGER_SYSVIEW_SEND_SYS_DESC_FUNC pfSendSysDesc) { +#ifdef SEGGER_RTT_SECTION + // + // Explicitly initialize the RTT Control Block if it is in its dedicated section. + // + SEGGER_RTT_Init(); +#endif +#if (SEGGER_SYSVIEW_POST_MORTEM_MODE == 1) +#if SEGGER_SYSVIEW_RTT_CHANNEL > 0 + SEGGER_RTT_ConfigUpBuffer(SEGGER_SYSVIEW_RTT_CHANNEL, "SysView", &_UpBuffer[0], sizeof(_UpBuffer), SEGGER_RTT_MODE_NO_BLOCK_SKIP); +#else + _SYSVIEW_Globals.UpChannel = SEGGER_RTT_AllocUpBuffer ("SysView", &_UpBuffer[0], sizeof(_UpBuffer), SEGGER_RTT_MODE_NO_BLOCK_SKIP); +#endif + _SYSVIEW_Globals.RAMBaseAddress = SEGGER_SYSVIEW_ID_BASE; + _SYSVIEW_Globals.LastTxTimeStamp = SEGGER_SYSVIEW_GET_TIMESTAMP(); + _SYSVIEW_Globals.pOSAPI = pOSAPI; + _SYSVIEW_Globals.SysFreq = SysFreq; + _SYSVIEW_Globals.CPUFreq = CPUFreq; + _SYSVIEW_Globals.pfSendSysDesc = pfSendSysDesc; + _SYSVIEW_Globals.EnableState = 0; + _SYSVIEW_Globals.PacketCount = 0; +#else // (SEGGER_SYSVIEW_POST_MORTEM_MODE == 1) +#if SEGGER_SYSVIEW_RTT_CHANNEL > 0 + SEGGER_RTT_ConfigUpBuffer (SEGGER_SYSVIEW_RTT_CHANNEL, "SysView", &_UpBuffer[0], sizeof(_UpBuffer), SEGGER_RTT_MODE_NO_BLOCK_SKIP); + SEGGER_RTT_ConfigDownBuffer (SEGGER_SYSVIEW_RTT_CHANNEL, "SysView", &_DownBuffer[0], sizeof(_DownBuffer), SEGGER_RTT_MODE_NO_BLOCK_SKIP); +#else + _SYSVIEW_Globals.UpChannel = SEGGER_RTT_AllocUpBuffer ("SysView", &_UpBuffer[0], sizeof(_UpBuffer), SEGGER_RTT_MODE_NO_BLOCK_SKIP); + // + // TODO: Use SEGGER_RTT_AllocDownBuffer when SystemViewer is able to handle another Down Channel than Up Channel. + // + _SYSVIEW_Globals.DownChannel = _SYSVIEW_Globals.UpChannel; + SEGGER_RTT_ConfigDownBuffer (_SYSVIEW_Globals.DownChannel, "SysView", &_DownBuffer[0], sizeof(_DownBuffer), SEGGER_RTT_MODE_NO_BLOCK_SKIP); +#endif + _SYSVIEW_Globals.RAMBaseAddress = SEGGER_SYSVIEW_ID_BASE; + _SYSVIEW_Globals.LastTxTimeStamp = SEGGER_SYSVIEW_GET_TIMESTAMP(); + _SYSVIEW_Globals.pOSAPI = pOSAPI; + _SYSVIEW_Globals.SysFreq = SysFreq; + _SYSVIEW_Globals.CPUFreq = CPUFreq; + _SYSVIEW_Globals.pfSendSysDesc = pfSendSysDesc; + _SYSVIEW_Globals.EnableState = 0; +#endif // (SEGGER_SYSVIEW_POST_MORTEM_MODE == 1) +} + +/********************************************************************* +* +* SEGGER_SYSVIEW_SetRAMBase() +* +* Function description +* Sets the RAM base address, which is subtracted from IDs in order +* to save bandwidth. +* +* Parameters +* RAMBaseAddress - Lowest RAM Address. (i.e. 0x20000000 on most Cortex-M) +*/ +void SEGGER_SYSVIEW_SetRAMBase(U32 RAMBaseAddress) { + _SYSVIEW_Globals.RAMBaseAddress = RAMBaseAddress; +} + +/********************************************************************* +* +* SEGGER_SYSVIEW_RecordVoid() +* +* Function description +* Formats and sends a SystemView packet with an empty payload. +* +* Parameters +* EventID - SystemView event ID. +*/ +void SEGGER_SYSVIEW_RecordVoid(unsigned int EventID) { + U8* pPayloadStart; + RECORD_START(SEGGER_SYSVIEW_INFO_SIZE); + // + _SendPacket(pPayloadStart, pPayloadStart, EventID); + RECORD_END(); +} + +/********************************************************************* +* +* SEGGER_SYSVIEW_RecordU32() +* +* Function description +* Formats and sends a SystemView packet containing a single U32 +* parameter payload. +* +* Parameters +* EventID - SystemView event ID. +* Value - The 32-bit parameter encoded to SystemView packet payload. +*/ +void SEGGER_SYSVIEW_RecordU32(unsigned int EventID, U32 Value) { + U8* pPayload; + U8* pPayloadStart; + RECORD_START(SEGGER_SYSVIEW_INFO_SIZE + SEGGER_SYSVIEW_QUANTA_U32); + // + pPayload = pPayloadStart; + ENCODE_U32(pPayload, Value); + _SendPacket(pPayloadStart, pPayload, EventID); + RECORD_END(); +} + +/********************************************************************* +* +* SEGGER_SYSVIEW_RecordU32x2() +* +* Function description +* Formats and sends a SystemView packet containing 2 U32 parameter payload. +* +* Parameters +* EventID - SystemView event ID. +* Para0 - The 32-bit parameter encoded to SystemView packet payload. +* Para1 - The 32-bit parameter encoded to SystemView packet payload. +*/ +void SEGGER_SYSVIEW_RecordU32x2(unsigned int EventID, U32 Para0, U32 Para1) { + U8* pPayload; + U8* pPayloadStart; + RECORD_START(SEGGER_SYSVIEW_INFO_SIZE + 2 * SEGGER_SYSVIEW_QUANTA_U32); + // + pPayload = pPayloadStart; + ENCODE_U32(pPayload, Para0); + ENCODE_U32(pPayload, Para1); + _SendPacket(pPayloadStart, pPayload, EventID); + RECORD_END(); +} + +/********************************************************************* +* +* SEGGER_SYSVIEW_RecordU32x3() +* +* Function description +* Formats and sends a SystemView packet containing 3 U32 parameter payload. +* +* Parameters +* EventID - SystemView event ID. +* Para0 - The 32-bit parameter encoded to SystemView packet payload. +* Para1 - The 32-bit parameter encoded to SystemView packet payload. +* Para2 - The 32-bit parameter encoded to SystemView packet payload. +*/ +void SEGGER_SYSVIEW_RecordU32x3(unsigned int EventID, U32 Para0, U32 Para1, U32 Para2) { + U8* pPayload; + U8* pPayloadStart; + RECORD_START(SEGGER_SYSVIEW_INFO_SIZE + 3 * SEGGER_SYSVIEW_QUANTA_U32); + // + pPayload = pPayloadStart; + ENCODE_U32(pPayload, Para0); + ENCODE_U32(pPayload, Para1); + ENCODE_U32(pPayload, Para2); + _SendPacket(pPayloadStart, pPayload, EventID); + RECORD_END(); +} + +/********************************************************************* +* +* SEGGER_SYSVIEW_RecordU32x4() +* +* Function description +* Formats and sends a SystemView packet containing 4 U32 parameter payload. +* +* Parameters +* EventID - SystemView event ID. +* Para0 - The 32-bit parameter encoded to SystemView packet payload. +* Para1 - The 32-bit parameter encoded to SystemView packet payload. +* Para2 - The 32-bit parameter encoded to SystemView packet payload. +* Para3 - The 32-bit parameter encoded to SystemView packet payload. +*/ +void SEGGER_SYSVIEW_RecordU32x4(unsigned int EventID, U32 Para0, U32 Para1, U32 Para2, U32 Para3) { + U8* pPayload; + U8* pPayloadStart; + RECORD_START(SEGGER_SYSVIEW_INFO_SIZE + 4 * SEGGER_SYSVIEW_QUANTA_U32); + // + pPayload = pPayloadStart; + ENCODE_U32(pPayload, Para0); + ENCODE_U32(pPayload, Para1); + ENCODE_U32(pPayload, Para2); + ENCODE_U32(pPayload, Para3); + _SendPacket(pPayloadStart, pPayload, EventID); + RECORD_END(); +} + +/********************************************************************* +* +* SEGGER_SYSVIEW_RecordU32x5() +* +* Function description +* Formats and sends a SystemView packet containing 5 U32 parameter payload. +* +* Parameters +* EventID - SystemView event ID. +* Para0 - The 32-bit parameter encoded to SystemView packet payload. +* Para1 - The 32-bit parameter encoded to SystemView packet payload. +* Para2 - The 32-bit parameter encoded to SystemView packet payload. +* Para3 - The 32-bit parameter encoded to SystemView packet payload. +* Para4 - The 32-bit parameter encoded to SystemView packet payload. +*/ +void SEGGER_SYSVIEW_RecordU32x5(unsigned int EventID, U32 Para0, U32 Para1, U32 Para2, U32 Para3, U32 Para4) { + U8* pPayload; + U8* pPayloadStart; + RECORD_START(SEGGER_SYSVIEW_INFO_SIZE + 5 * SEGGER_SYSVIEW_QUANTA_U32); + // + pPayload = pPayloadStart; + ENCODE_U32(pPayload, Para0); + ENCODE_U32(pPayload, Para1); + ENCODE_U32(pPayload, Para2); + ENCODE_U32(pPayload, Para3); + ENCODE_U32(pPayload, Para4); + _SendPacket(pPayloadStart, pPayload, EventID); + RECORD_END(); +} + +/********************************************************************* +* +* SEGGER_SYSVIEW_RecordU32x6() +* +* Function description +* Formats and sends a SystemView packet containing 6 U32 parameter payload. +* +* Parameters +* EventID - SystemView event ID. +* Para0 - The 32-bit parameter encoded to SystemView packet payload. +* Para1 - The 32-bit parameter encoded to SystemView packet payload. +* Para2 - The 32-bit parameter encoded to SystemView packet payload. +* Para3 - The 32-bit parameter encoded to SystemView packet payload. +* Para4 - The 32-bit parameter encoded to SystemView packet payload. +* Para5 - The 32-bit parameter encoded to SystemView packet payload. +*/ +void SEGGER_SYSVIEW_RecordU32x6(unsigned int EventID, U32 Para0, U32 Para1, U32 Para2, U32 Para3, U32 Para4, U32 Para5) { + U8* pPayload; + U8* pPayloadStart; + RECORD_START(SEGGER_SYSVIEW_INFO_SIZE + 6 * SEGGER_SYSVIEW_QUANTA_U32); + // + pPayload = pPayloadStart; + ENCODE_U32(pPayload, Para0); + ENCODE_U32(pPayload, Para1); + ENCODE_U32(pPayload, Para2); + ENCODE_U32(pPayload, Para3); + ENCODE_U32(pPayload, Para4); + ENCODE_U32(pPayload, Para5); + _SendPacket(pPayloadStart, pPayload, EventID); + RECORD_END(); +} + +/********************************************************************* +* +* SEGGER_SYSVIEW_RecordU32x7() +* +* Function description +* Formats and sends a SystemView packet containing 7 U32 parameter payload. +* +* Parameters +* EventID - SystemView event ID. +* Para0 - The 32-bit parameter encoded to SystemView packet payload. +* Para1 - The 32-bit parameter encoded to SystemView packet payload. +* Para2 - The 32-bit parameter encoded to SystemView packet payload. +* Para3 - The 32-bit parameter encoded to SystemView packet payload. +* Para4 - The 32-bit parameter encoded to SystemView packet payload. +* Para5 - The 32-bit parameter encoded to SystemView packet payload. +* Para6 - The 32-bit parameter encoded to SystemView packet payload. +*/ +void SEGGER_SYSVIEW_RecordU32x7(unsigned int EventID, U32 Para0, U32 Para1, U32 Para2, U32 Para3, U32 Para4, U32 Para5, U32 Para6) { + U8* pPayload; + U8* pPayloadStart; + RECORD_START(SEGGER_SYSVIEW_INFO_SIZE + 7 * SEGGER_SYSVIEW_QUANTA_U32); + // + pPayload = pPayloadStart; + ENCODE_U32(pPayload, Para0); + ENCODE_U32(pPayload, Para1); + ENCODE_U32(pPayload, Para2); + ENCODE_U32(pPayload, Para3); + ENCODE_U32(pPayload, Para4); + ENCODE_U32(pPayload, Para5); + ENCODE_U32(pPayload, Para6); + _SendPacket(pPayloadStart, pPayload, EventID); + RECORD_END(); +} + +/********************************************************************* +* +* SEGGER_SYSVIEW_RecordU32x8() +* +* Function description +* Formats and sends a SystemView packet containing 8 U32 parameter payload. +* +* Parameters +* EventID - SystemView event ID. +* Para0 - The 32-bit parameter encoded to SystemView packet payload. +* Para1 - The 32-bit parameter encoded to SystemView packet payload. +* Para2 - The 32-bit parameter encoded to SystemView packet payload. +* Para3 - The 32-bit parameter encoded to SystemView packet payload. +* Para4 - The 32-bit parameter encoded to SystemView packet payload. +* Para5 - The 32-bit parameter encoded to SystemView packet payload. +* Para6 - The 32-bit parameter encoded to SystemView packet payload. +* Para7 - The 32-bit parameter encoded to SystemView packet payload. +*/ +void SEGGER_SYSVIEW_RecordU32x8(unsigned int EventID, U32 Para0, U32 Para1, U32 Para2, U32 Para3, U32 Para4, U32 Para5, U32 Para6, U32 Para7) { + U8* pPayload; + U8* pPayloadStart; + RECORD_START(SEGGER_SYSVIEW_INFO_SIZE + 8 * SEGGER_SYSVIEW_QUANTA_U32); + // + pPayload = pPayloadStart; + ENCODE_U32(pPayload, Para0); + ENCODE_U32(pPayload, Para1); + ENCODE_U32(pPayload, Para2); + ENCODE_U32(pPayload, Para3); + ENCODE_U32(pPayload, Para4); + ENCODE_U32(pPayload, Para5); + ENCODE_U32(pPayload, Para6); + ENCODE_U32(pPayload, Para7); + _SendPacket(pPayloadStart, pPayload, EventID); + RECORD_END(); +} + +/********************************************************************* +* +* SEGGER_SYSVIEW_RecordU32x9() +* +* Function description +* Formats and sends a SystemView packet containing 9 U32 parameter payload. +* +* Parameters +* EventID - SystemView event ID. +* Para0 - The 32-bit parameter encoded to SystemView packet payload. +* Para1 - The 32-bit parameter encoded to SystemView packet payload. +* Para2 - The 32-bit parameter encoded to SystemView packet payload. +* Para3 - The 32-bit parameter encoded to SystemView packet payload. +* Para4 - The 32-bit parameter encoded to SystemView packet payload. +* Para5 - The 32-bit parameter encoded to SystemView packet payload. +* Para6 - The 32-bit parameter encoded to SystemView packet payload. +* Para7 - The 32-bit parameter encoded to SystemView packet payload. +* Para8 - The 32-bit parameter encoded to SystemView packet payload. +*/ +void SEGGER_SYSVIEW_RecordU32x9(unsigned int EventID, U32 Para0, U32 Para1, U32 Para2, U32 Para3, U32 Para4, U32 Para5, U32 Para6, U32 Para7, U32 Para8) { + U8* pPayload; + U8* pPayloadStart; + RECORD_START(SEGGER_SYSVIEW_INFO_SIZE + 9 * SEGGER_SYSVIEW_QUANTA_U32); + // + pPayload = pPayloadStart; + ENCODE_U32(pPayload, Para0); + ENCODE_U32(pPayload, Para1); + ENCODE_U32(pPayload, Para2); + ENCODE_U32(pPayload, Para3); + ENCODE_U32(pPayload, Para4); + ENCODE_U32(pPayload, Para5); + ENCODE_U32(pPayload, Para6); + ENCODE_U32(pPayload, Para7); + ENCODE_U32(pPayload, Para8); + _SendPacket(pPayloadStart, pPayload, EventID); + RECORD_END(); +} + +/********************************************************************* +* +* SEGGER_SYSVIEW_RecordU32x10() +* +* Function description +* Formats and sends a SystemView packet containing 10 U32 parameter payload. +* +* Parameters +* EventID - SystemView event ID. +* Para0 - The 32-bit parameter encoded to SystemView packet payload. +* Para1 - The 32-bit parameter encoded to SystemView packet payload. +* Para2 - The 32-bit parameter encoded to SystemView packet payload. +* Para3 - The 32-bit parameter encoded to SystemView packet payload. +* Para4 - The 32-bit parameter encoded to SystemView packet payload. +* Para5 - The 32-bit parameter encoded to SystemView packet payload. +* Para6 - The 32-bit parameter encoded to SystemView packet payload. +* Para7 - The 32-bit parameter encoded to SystemView packet payload. +* Para8 - The 32-bit parameter encoded to SystemView packet payload. +* Para9 - The 32-bit parameter encoded to SystemView packet payload. +*/ +void SEGGER_SYSVIEW_RecordU32x10(unsigned int EventID, U32 Para0, U32 Para1, U32 Para2, U32 Para3, U32 Para4, U32 Para5, U32 Para6, U32 Para7, U32 Para8, U32 Para9) { + U8* pPayload; + U8* pPayloadStart; + RECORD_START(SEGGER_SYSVIEW_INFO_SIZE + 10 * SEGGER_SYSVIEW_QUANTA_U32); + // + pPayload = pPayloadStart; + ENCODE_U32(pPayload, Para0); + ENCODE_U32(pPayload, Para1); + ENCODE_U32(pPayload, Para2); + ENCODE_U32(pPayload, Para3); + ENCODE_U32(pPayload, Para4); + ENCODE_U32(pPayload, Para5); + ENCODE_U32(pPayload, Para6); + ENCODE_U32(pPayload, Para7); + ENCODE_U32(pPayload, Para8); + ENCODE_U32(pPayload, Para9); + _SendPacket(pPayloadStart, pPayload, EventID); + RECORD_END(); +} +/********************************************************************* +* +* SEGGER_SYSVIEW_RecordString() +* +* Function description +* Formats and sends a SystemView packet containing a string. +* +* Parameters +* EventID - SystemView event ID. +* pString - The string to be sent in the SystemView packet payload. +* +* Additional information +* The string is encoded as a count byte followed by the contents +* of the string. +* No more than SEGGER_SYSVIEW_MAX_STRING_LEN bytes will be encoded to the payload. +*/ +void SEGGER_SYSVIEW_RecordString(unsigned int EventID, const char* pString) { + U8* pPayload; + U8* pPayloadStart; + RECORD_START(SEGGER_SYSVIEW_INFO_SIZE + 1 + SEGGER_SYSVIEW_MAX_STRING_LEN); + // + pPayload = _EncodeStr(pPayloadStart, pString, SEGGER_SYSVIEW_MAX_STRING_LEN); + _SendPacket(pPayloadStart, pPayload, EventID); + RECORD_END(); +} + +/********************************************************************* +* +* SEGGER_SYSVIEW_Start() +* +* Function description +* Start recording SystemView events. +* This function is triggered by the host application. +* +* Additional information +* This function enables transmission of SystemView packets recorded +* by subsequent trace calls and records a SystemView Start event. +* +* As part of start, a SystemView Init packet is sent, containing the system +* frequency. The list of current tasks, the current system time and the +* system description string is sent, too. +* +* Notes +* SEGGER_SYSVIEW_Start and SEGGER_SYSVIEW_Stop do not nest. +*/ +void SEGGER_SYSVIEW_Start(void) { + if (_SYSVIEW_Globals.EnableState == 0) { + _SYSVIEW_Globals.EnableState = 1; +#if (SEGGER_SYSVIEW_POST_MORTEM_MODE == 1) + _SendSyncInfo(); +#else + SEGGER_SYSVIEW_LOCK(); + SEGGER_RTT_WriteSkipNoLock(CHANNEL_ID_UP, _abSync, 10); + SEGGER_SYSVIEW_UNLOCK(); + SEGGER_SYSVIEW_RecordVoid(SYSVIEW_EVTID_TRACE_START); + { + U8* pPayload; + U8* pPayloadStart; + RECORD_START(SEGGER_SYSVIEW_INFO_SIZE + 4 * SEGGER_SYSVIEW_QUANTA_U32); + // + pPayload = pPayloadStart; + ENCODE_U32(pPayload, _SYSVIEW_Globals.SysFreq); + ENCODE_U32(pPayload, _SYSVIEW_Globals.CPUFreq); + ENCODE_U32(pPayload, _SYSVIEW_Globals.RAMBaseAddress); + ENCODE_U32(pPayload, SEGGER_SYSVIEW_ID_SHIFT); + _SendPacket(pPayloadStart, pPayload, SYSVIEW_EVTID_INIT); + RECORD_END(); + } + if (_SYSVIEW_Globals.pfSendSysDesc) { + _SYSVIEW_Globals.pfSendSysDesc(); + } + SEGGER_SYSVIEW_RecordSystime(); + SEGGER_SYSVIEW_SendTaskList(); + SEGGER_SYSVIEW_SendNumModules(); +#endif + } +} + +/********************************************************************* +* +* SEGGER_SYSVIEW_Stop() +* +* Function description +* Stop recording SystemView events. +* +* Additional information +* This function disables transmission of SystemView packets recorded +* by subsequent trace calls. If transmission is enabled when +* this function is called, a single SystemView Stop event is recorded +* to the trace, send, and then trace transmission is halted. +*/ +void SEGGER_SYSVIEW_Stop(void) { + U8* pPayloadStart; + RECORD_START(SEGGER_SYSVIEW_INFO_SIZE); + // + if (_SYSVIEW_Globals.EnableState) { + _SendPacket(pPayloadStart, pPayloadStart, SYSVIEW_EVTID_TRACE_STOP); + _SYSVIEW_Globals.EnableState = 0; + } + RECORD_END(); +} + +/********************************************************************* +* +* SEGGER_SYSVIEW_GetSysDesc() +* +* Function description +* Triggers a send of the system information and description. +* +*/ +void SEGGER_SYSVIEW_GetSysDesc(void) { + U8* pPayload; + U8* pPayloadStart; + RECORD_START(SEGGER_SYSVIEW_INFO_SIZE + 4 * SEGGER_SYSVIEW_QUANTA_U32); + // + pPayload = pPayloadStart; + ENCODE_U32(pPayload, _SYSVIEW_Globals.SysFreq); + ENCODE_U32(pPayload, _SYSVIEW_Globals.CPUFreq); + ENCODE_U32(pPayload, _SYSVIEW_Globals.RAMBaseAddress); + ENCODE_U32(pPayload, SEGGER_SYSVIEW_ID_SHIFT); + _SendPacket(pPayloadStart, pPayload, SYSVIEW_EVTID_INIT); + RECORD_END(); + if (_SYSVIEW_Globals.pfSendSysDesc) { + _SYSVIEW_Globals.pfSendSysDesc(); + } +} + +/********************************************************************* +* +* SEGGER_SYSVIEW_SendTaskInfo() +* +* Function description +* Send a Task Info Packet, containing TaskId for identification, +* task priority and task name. +* +* Parameters +* pInfo - Pointer to task information to send. +*/ +void SEGGER_SYSVIEW_SendTaskInfo(const SEGGER_SYSVIEW_TASKINFO *pInfo) { + U8* pPayload; + U8* pPayloadStart; + RECORD_START(SEGGER_SYSVIEW_INFO_SIZE + SEGGER_SYSVIEW_QUANTA_U32 + 1 + 32); + // + pPayload = pPayloadStart; + ENCODE_U32(pPayload, SHRINK_ID(pInfo->TaskID)); + ENCODE_U32(pPayload, pInfo->Prio); + pPayload = _EncodeStr(pPayload, pInfo->sName, 32); + _SendPacket(pPayloadStart, pPayload, SYSVIEW_EVTID_TASK_INFO); + // + pPayload = pPayloadStart; + ENCODE_U32(pPayload, SHRINK_ID(pInfo->TaskID)); + ENCODE_U32(pPayload, pInfo->StackBase); + ENCODE_U32(pPayload, pInfo->StackSize); + ENCODE_U32(pPayload, 0); // Stack End, future use + _SendPacket(pPayloadStart, pPayload, SYSVIEW_EVTID_STACK_INFO); + RECORD_END(); +} + +/********************************************************************* +* +* SEGGER_SYSVIEW_SendTaskList() +* +* Function description +* Send all tasks descriptors to the host. +*/ +void SEGGER_SYSVIEW_SendTaskList(void) { + if (_SYSVIEW_Globals.pOSAPI && _SYSVIEW_Globals.pOSAPI->pfSendTaskList) { + _SYSVIEW_Globals.pOSAPI->pfSendTaskList(); + } +} + +/********************************************************************* +* +* SEGGER_SYSVIEW_SendSysDesc() +* +* Function description +* Send the system description string to the host. +* The system description is used by SystemViewer to identify the +* current application and handle events accordingly. +* +* Parameters +* sSysDesc - Pointer to the 0-terminated system description string. +* +* Additional information +* One system description string may not exceed SEGGER_SYSVIEW_MAX_STRING_LEN characters. +* +* The Following items can be described in a system description string. +* Each item is identified by its identifier, followed by '=' and the value. +* Items are separated by ','. +*/ +void SEGGER_SYSVIEW_SendSysDesc(const char *sSysDesc) { + U8* pPayload; + U8* pPayloadStart; + RECORD_START(SEGGER_SYSVIEW_INFO_SIZE + 1 + SEGGER_SYSVIEW_MAX_STRING_LEN); + // + pPayload = _EncodeStr(pPayloadStart, sSysDesc, SEGGER_SYSVIEW_MAX_STRING_LEN); + _SendPacket(pPayloadStart, pPayload, SYSVIEW_EVTID_SYSDESC); + RECORD_END(); +} + +/********************************************************************* +* +* SEGGER_SYSVIEW_RecordSystime() +* +* Function description +* Formats and sends a SystemView Systime containing a single U64 or U32 +* parameter payload. +*/ +void SEGGER_SYSVIEW_RecordSystime(void) { + U64 Systime; + + if (_SYSVIEW_Globals.pOSAPI && _SYSVIEW_Globals.pOSAPI->pfGetTime) { + Systime = _SYSVIEW_Globals.pOSAPI->pfGetTime(); + SEGGER_SYSVIEW_RecordU32x2(SYSVIEW_EVTID_SYSTIME_US, + (U32)(Systime), + (U32)(Systime >> 32)); + } else { + SEGGER_SYSVIEW_RecordU32(SYSVIEW_EVTID_SYSTIME_CYCLES, SEGGER_SYSVIEW_GET_TIMESTAMP()); + } +} + +/********************************************************************* +* +* SEGGER_SYSVIEW_RecordEnterISR() +* +* Function description +* Format and send an ISR entry event. +* +* Additional information +* Example packets sent +* 02 0F 50 // ISR(15) Enter. Timestamp is 80 (0x50) +*/ +void SEGGER_SYSVIEW_RecordEnterISR(U32 IrqId) { + unsigned v; + U8* pPayload; + U8* pPayloadStart; + RECORD_START(SEGGER_SYSVIEW_INFO_SIZE + SEGGER_SYSVIEW_QUANTA_U32); + // + pPayload = pPayloadStart; + v = IrqId;//SEGGER_SYSVIEW_GET_INTERRUPT_ID(); + ENCODE_U32(pPayload, v); + _SendPacket(pPayloadStart, pPayload, SYSVIEW_EVTID_ISR_ENTER); + RECORD_END(); +} + +/********************************************************************* +* +* SEGGER_SYSVIEW_RecordExitISR() +* +* Function description +* Format and send an ISR exit event. +* +* Additional information +* Format as follows: +* 03 // Max. packet len is 6 +* +* Example packets sent +* 03 20 // ISR Exit. Timestamp is 32 (0x20) +*/ +void SEGGER_SYSVIEW_RecordExitISR(void) { + U8* pPayloadStart; + RECORD_START(SEGGER_SYSVIEW_INFO_SIZE); + // + _SendPacket(pPayloadStart, pPayloadStart, SYSVIEW_EVTID_ISR_EXIT); + RECORD_END(); +} + +/********************************************************************* +* +* SEGGER_SYSVIEW_RecordExitISRToScheduler() +* +* Function description +* Format and send an ISR exit into scheduler event. +* +* Additional information +* Format as follows: +* 18 // Max. packet len is 6 +* +* Example packets sent +* 18 20 // ISR Exit to Scheduler. Timestamp is 32 (0x20) +*/ +void SEGGER_SYSVIEW_RecordExitISRToScheduler(void) { + U8* pPayloadStart; + RECORD_START(SEGGER_SYSVIEW_INFO_SIZE); + // + _SendPacket(pPayloadStart, pPayloadStart, SYSVIEW_EVTID_ISR_TO_SCHEDULER); + RECORD_END(); +} + +/********************************************************************* +* +* SEGGER_SYSVIEW_RecordEnterTimer() +* +* Function description +* Format and send a Timer entry event. +* +* Parameters +* TimerId - Id of the timer which starts. +*/ +void SEGGER_SYSVIEW_RecordEnterTimer(U32 TimerId) { + U8* pPayload; + U8* pPayloadStart; + RECORD_START(SEGGER_SYSVIEW_INFO_SIZE + SEGGER_SYSVIEW_QUANTA_U32); + // + pPayload = pPayloadStart; + ENCODE_U32(pPayload, SHRINK_ID(TimerId)); + _SendPacket(pPayloadStart, pPayload, SYSVIEW_EVTID_TIMER_ENTER); + RECORD_END(); +} + +/********************************************************************* +* +* SEGGER_SYSVIEW_RecordExitTimer() +* +* Function description +* Format and send a Timer exit event. +*/ +void SEGGER_SYSVIEW_RecordExitTimer(void) { + U8* pPayloadStart; + RECORD_START(SEGGER_SYSVIEW_INFO_SIZE); + // + _SendPacket(pPayloadStart, pPayloadStart, SYSVIEW_EVTID_TIMER_EXIT); + RECORD_END(); +} + +/********************************************************************* +* +* SEGGER_SYSVIEW_RecordEndCall() +* +* Function description +* Format and send an End API Call event without return value. +* +* Parameters +* EventID - Id of API function which ends. +*/ +void SEGGER_SYSVIEW_RecordEndCall(unsigned int EventID) { + U8* pPayload; + U8* pPayloadStart; + RECORD_START(SEGGER_SYSVIEW_INFO_SIZE + SEGGER_SYSVIEW_QUANTA_U32); + // + pPayload = pPayloadStart; + ENCODE_U32(pPayload, EventID); + _SendPacket(pPayloadStart, pPayload, SYSVIEW_EVTID_END_CALL); + RECORD_END(); +} + +/********************************************************************* +* +* SEGGER_SYSVIEW_RecordEndCallU32() +* +* Function description +* Format and send an End API Call event with return value. +* +* Parameters +* EventID - Id of API function which ends. +* Para0 - Return value which will be returned by the API function. +*/ +void SEGGER_SYSVIEW_RecordEndCallU32(unsigned int EventID, U32 Para0) { + U8* pPayload; + U8* pPayloadStart; + RECORD_START(SEGGER_SYSVIEW_INFO_SIZE + 2 * SEGGER_SYSVIEW_QUANTA_U32); + // + pPayload = pPayloadStart; + ENCODE_U32(pPayload, EventID); + ENCODE_U32(pPayload, Para0); + _SendPacket(pPayloadStart, pPayload, SYSVIEW_EVTID_END_CALL); + RECORD_END(); +} + +/********************************************************************* +* +* SEGGER_SYSVIEW_OnIdle() +* +* Function description +* Record an Idle event. +*/ +void SEGGER_SYSVIEW_OnIdle(void) { + U8* pPayloadStart; + RECORD_START(SEGGER_SYSVIEW_INFO_SIZE); + // + _SendPacket(pPayloadStart, pPayloadStart, SYSVIEW_EVTID_IDLE); + RECORD_END(); +} + +/********************************************************************* +* +* SEGGER_SYSVIEW_OnTaskCreate() +* +* Function description +* Record a Task Create event. The Task Create event corresponds +* to creating a task in the OS. +* +* Parameters +* TaskId - Task ID of created task. +*/ +void SEGGER_SYSVIEW_OnTaskCreate(U32 TaskId) { + U8* pPayload; + U8* pPayloadStart; + RECORD_START(SEGGER_SYSVIEW_INFO_SIZE + SEGGER_SYSVIEW_QUANTA_U32); + // + pPayload = pPayloadStart; + TaskId = SHRINK_ID(TaskId); + ENCODE_U32(pPayload, TaskId); + _SendPacket(pPayloadStart, pPayload, SYSVIEW_EVTID_TASK_CREATE); + RECORD_END(); +} + +/********************************************************************* +* +* SEGGER_SYSVIEW_OnTaskTerminate() +* +* Function description +* Record a Task termination event. +* The Task termination event corresponds to terminating a task in +* the OS. If the TaskId is the currently active task, +* SEGGER_SYSVIEW_OnTaskStopExec may be used, either. +* +* Parameters +* TaskId - Task ID of terminated task. +*/ +void SEGGER_SYSVIEW_OnTaskTerminate(U32 TaskId) { + U8* pPayload; + U8* pPayloadStart; + RECORD_START(SEGGER_SYSVIEW_INFO_SIZE + SEGGER_SYSVIEW_QUANTA_U32); + // + pPayload = pPayloadStart; + TaskId = SHRINK_ID(TaskId); + ENCODE_U32(pPayload, TaskId); + _SendPacket(pPayloadStart, pPayload, SYSVIEW_EVTID_TASK_TERMINATE); + RECORD_END(); +} + +/********************************************************************* +* +* SEGGER_SYSVIEW_OnTaskStartExec() +* +* Function description +* Record a Task Start Execution event. The Task Start event +* corresponds to when a task has started to execute rather than +* when it is ready to execute. +* +* Parameters +* TaskId - Task ID of task that started to execute. +*/ +void SEGGER_SYSVIEW_OnTaskStartExec(U32 TaskId) { + U8* pPayload; + U8* pPayloadStart; + RECORD_START(SEGGER_SYSVIEW_INFO_SIZE + SEGGER_SYSVIEW_QUANTA_U32); + // + pPayload = pPayloadStart; + TaskId = SHRINK_ID(TaskId); + ENCODE_U32(pPayload, TaskId); + _SendPacket(pPayloadStart, pPayload, SYSVIEW_EVTID_TASK_START_EXEC); + RECORD_END(); +} + +/********************************************************************* +* +* SEGGER_SYSVIEW_OnTaskStopExec() +* +* Function description +* Record a Task Stop Execution event. The Task Stop event +* corresponds to when a task stops executing and terminates. +*/ +void SEGGER_SYSVIEW_OnTaskStopExec(void) { + U8* pPayloadStart; + RECORD_START(SEGGER_SYSVIEW_INFO_SIZE); + // + _SendPacket(pPayloadStart, pPayloadStart, SYSVIEW_EVTID_TASK_STOP_EXEC); + RECORD_END(); +} + +/********************************************************************* +* +* SEGGER_SYSVIEW_OnTaskStartReady() +* +* Function description +* Record a Task Start Ready event. +* +* Parameters +* TaskId - Task ID of task that started to execute. +*/ +void SEGGER_SYSVIEW_OnTaskStartReady(U32 TaskId) { + U8* pPayload; + U8* pPayloadStart; + RECORD_START(SEGGER_SYSVIEW_INFO_SIZE + SEGGER_SYSVIEW_QUANTA_U32); + // + pPayload = pPayloadStart; + TaskId = SHRINK_ID(TaskId); + ENCODE_U32(pPayload, TaskId); + _SendPacket(pPayloadStart, pPayload, SYSVIEW_EVTID_TASK_START_READY); + RECORD_END(); +} + +/********************************************************************* +* +* SEGGER_SYSVIEW_OnTaskStopReady() +* +* Function description +* Record a Task Stop Ready event. +* +* Parameters +* TaskId - Task ID of task that completed execution. +* Cause - Reason for task to stop (i.e. Idle/Sleep) +*/ +void SEGGER_SYSVIEW_OnTaskStopReady(U32 TaskId, unsigned int Cause) { + U8* pPayload; + U8* pPayloadStart; + RECORD_START(SEGGER_SYSVIEW_INFO_SIZE + 2 * SEGGER_SYSVIEW_QUANTA_U32); + // + pPayload = pPayloadStart; + TaskId = SHRINK_ID(TaskId); + ENCODE_U32(pPayload, TaskId); + ENCODE_U32(pPayload, Cause); + _SendPacket(pPayloadStart, pPayload, SYSVIEW_EVTID_TASK_STOP_READY); + RECORD_END(); +} + +/********************************************************************* +* +* SEGGER_SYSVIEW_OnUserStart() +* +* Function description +* Send a user event start, such as start of a subroutine for profiling. +* +* Parameters +* UserId - User defined ID for the event. +*/ +void SEGGER_SYSVIEW_OnUserStart(unsigned UserId) { + U8* pPayload; + U8* pPayloadStart; + RECORD_START(SEGGER_SYSVIEW_INFO_SIZE + SEGGER_SYSVIEW_QUANTA_U32); + // + pPayload = pPayloadStart; + ENCODE_U32(pPayload, UserId); + _SendPacket(pPayloadStart, pPayload, SYSVIEW_EVTID_USER_START); + RECORD_END(); +} + +/********************************************************************* +* +* SEGGER_SYSVIEW_OnUserStop() +* +* Function description +* Send a user event stop, such as return of a subroutine for profiling. +* +* Parameters +* UserId - User defined ID for the event. +*/ +void SEGGER_SYSVIEW_OnUserStop(unsigned UserId) { + U8 * pPayload; + U8 * pPayloadStart; + RECORD_START(SEGGER_SYSVIEW_INFO_SIZE + SEGGER_SYSVIEW_QUANTA_U32); + // + pPayload = pPayloadStart; + ENCODE_U32(pPayload, UserId); + _SendPacket(pPayloadStart, pPayload, SYSVIEW_EVTID_USER_STOP); + RECORD_END(); +} + +/********************************************************************* +* +* SEGGER_SYSVIEW_NameResource() +* +* Function description +* Send the name of a resource to be displayed in SystemViewer. +* +* Parameters +* ResourceId - Id of the resource to be named. i.e. its address. +* sName - Pointer to the resource name. (Max. SEGGER_SYSVIEW_MAX_STRING_LEN Bytes) +*/ +void SEGGER_SYSVIEW_NameResource(U32 ResourceId, const char* sName) { + U8* pPayload; + U8* pPayloadStart; + RECORD_START(SEGGER_SYSVIEW_INFO_SIZE + SEGGER_SYSVIEW_QUANTA_U32 + 1 + SEGGER_SYSVIEW_MAX_STRING_LEN); + // + pPayload = pPayloadStart; + ENCODE_U32(pPayload, SHRINK_ID(ResourceId)); + pPayload = _EncodeStr(pPayload, sName, SEGGER_SYSVIEW_MAX_STRING_LEN); + _SendPacket(pPayloadStart, pPayload, SYSVIEW_EVTID_NAME_RESOURCE); + RECORD_END(); +} + +/********************************************************************* +* +* SEGGER_SYSVIEW_SendPacket() +* +* Function description +* Send an event packet. +* +* Parameters +* pPacket - Pointer to the start of the packet. +* pPayloadEnd - Pointer to the end of the payload. +* Make sure there are at least 5 bytes free after the payload. +* EventId - Id of the event packet. +* +* Return value +* !=0: Success, Message sent. +* ==0: Buffer full, Message *NOT* sent. +*/ +int SEGGER_SYSVIEW_SendPacket(U8* pPacket, U8* pPayloadEnd, unsigned int EventId) { +#if (SEGGER_SYSVIEW_USE_STATIC_BUFFER == 1) + SEGGER_SYSVIEW_LOCK(); +#endif + _SendPacket(pPacket + 4, pPayloadEnd, EventId); +#if (SEGGER_SYSVIEW_USE_STATIC_BUFFER == 1) + SEGGER_SYSVIEW_UNLOCK(); +#endif + return 0; +} + +/********************************************************************* +* +* SEGGER_SYSVIEW_EncodeU32() +* +* Function description +* Encode a U32 in variable-length format. +* +* Parameters +* pPayload - Pointer to where U32 will be encoded. +* Value - The 32-bit value to be encoded. +* +* Return value +* Pointer to the byte following the value, i.e. the first free +* byte in the payload and the next position to store payload +* content. +*/ +U8* SEGGER_SYSVIEW_EncodeU32(U8* pPayload, U32 Value) { + ENCODE_U32(pPayload, Value); + return pPayload; +} + +/********************************************************************* +* +* SEGGER_SYSVIEW_EncodeString() +* +* Function description +* Encode a string in variable-length format. +* +* Parameters +* pPayload - Pointer to where string will be encoded. +* s - String to encode. +* MaxLen - Maximum number of characters to encode from string. +* +* Return value +* Pointer to the byte following the value, i.e. the first free +* byte in the payload and the next position to store payload +* content. +* +* Additional information +* The string is encoded as a count byte followed by the contents +* of the string. +* No more than 1 + MaxLen bytes will be encoded to the payload. +*/ +U8* SEGGER_SYSVIEW_EncodeString(U8* pPayload, const char* s, unsigned int MaxLen) { + return _EncodeStr(pPayload, s, MaxLen); +} + +/********************************************************************* +* +* SEGGER_SYSVIEW_EncodeData() +* +* Function description +* Encode a byte buffer in variable-length format. +* +* Parameters +* pPayload - Pointer to where string will be encoded. +* pSrc - Pointer to data buffer to be encoded. +* NumBytes - Number of bytes in the buffer to be encoded. +* +* Return value +* Pointer to the byte following the value, i.e. the first free +* byte in the payload and the next position to store payload +* content. +* +* Additional information +* The data is encoded as a count byte followed by the contents +* of the data buffer. +* Make sure NumBytes + 1 bytes are free for the payload. +*/ +U8* SEGGER_SYSVIEW_EncodeData(U8 *pPayload, const char* pSrc, unsigned int NumBytes) { + return _EncodeData(pPayload, pSrc, NumBytes); +} + +/********************************************************************* +* +* SEGGER_SYSVIEW_EncodeId() +* +* Function description +* Encode a 32-bit Id in shrunken variable-length format. +* +* Parameters +* pPayload - Pointer to where the Id will be encoded. +* Id - The 32-bit value to be encoded. +* +* Return value +* Pointer to the byte following the value, i.e. the first free +* byte in the payload and the next position to store payload +* content. +* +* Additional information +* The parameters to shrink an Id can be configured in +* SEGGER_SYSVIEW_Conf.h and via SEGGER_SYSVIEW_SetRAMBase(). +* SEGGER_SYSVIEW_ID_BASE: Lowest Id reported by the application. +* (i.e. 0x20000000 when all Ids are an address in this RAM) +* SEGGER_SYSVIEW_ID_SHIFT: Number of bits to shift the Id to +* save bandwidth. (i.e. 2 when Ids are 4 byte aligned) +*/ +U8* SEGGER_SYSVIEW_EncodeId(U8* pPayload, U32 Id) { + Id = SHRINK_ID(Id); + ENCODE_U32(pPayload, Id); + return pPayload; +} + +/********************************************************************* +* +* SEGGER_SYSVIEW_ShrinkId() +* +* Function description +* Get the shrunken value of an Id for further processing like in +* SEGGER_SYSVIEW_NameResource(). +* +* Parameters +* Id - The 32-bit value to be shrunken. +* +* Return value +* Shrunken Id. +* +* Additional information +* The parameters to shrink an Id can be configured in +* SEGGER_SYSVIEW_Conf.h and via SEGGER_SYSVIEW_SetRAMBase(). +* SEGGER_SYSVIEW_ID_BASE: Lowest Id reported by the application. +* (i.e. 0x20000000 when all Ids are an address in this RAM) +* SEGGER_SYSVIEW_ID_SHIFT: Number of bits to shift the Id to +* save bandwidth. (i.e. 2 when Ids are 4 byte aligned) +*/ +U32 SEGGER_SYSVIEW_ShrinkId(U32 Id) { + return SHRINK_ID(Id); +} + +/********************************************************************* +* +* SEGGER_SYSVIEW_RegisterModule() +* +* Function description +* Register a middleware module for recording its events. +* +* Parameters +* pModule - The middleware module information. +* +* Additional information +* SEGGER_SYSVIEW_MODULE elements: +* sDescription - Pointer to a string containing the module name and optionally the module event description. +* NumEvents - Number of events the module wants to register. +* EventOffset - Offset to be added to the event Ids. Out parameter, set by this function. Do not modify after calling this function. +* pfSendModuleDesc - Callback function pointer to send more detailed module description to SystemViewer. +* pNext - Pointer to next registered module. Out parameter, set by this function. Do not modify after calling this function. +*/ +void SEGGER_SYSVIEW_RegisterModule(SEGGER_SYSVIEW_MODULE* pModule) { + SEGGER_SYSVIEW_LOCK(); + if (_pFirstModule == 0) { + // + // No module registered, yet. + // Start list with new module. + // EventOffset is the base offset for modules + // + pModule->EventOffset = MODULE_EVENT_OFFSET; + pModule->pNext = 0; + _pFirstModule = pModule; + _NumModules = 1; + } else { + // + // Registreded module(s) present. + // Prepend new module in list. + // EventOffset set from number of events and offset of previous module. + // + pModule->EventOffset = _pFirstModule->EventOffset + _pFirstModule->NumEvents; + pModule->pNext = _pFirstModule; + _pFirstModule = pModule; + _NumModules++; + } + SEGGER_SYSVIEW_SendModule(0); + if (pModule->pfSendModuleDesc) { + pModule->pfSendModuleDesc(); + } + SEGGER_SYSVIEW_UNLOCK(); +} + +/********************************************************************* +* +* SEGGER_SYSVIEW_RecordModuleDescription() +* +* Function description +* Sends detailed information of a registered module to the host. +* +* Parameters +* pModule - Pointer to the described module. +* sDescription - Pointer to a description string. +*/ +void SEGGER_SYSVIEW_RecordModuleDescription(const SEGGER_SYSVIEW_MODULE* pModule, const char* sDescription) { + U8 ModuleId; + SEGGER_SYSVIEW_MODULE* p; + + p = _pFirstModule; + ModuleId = 0; + do { + if (p == pModule) { + break; + } + ModuleId++; + p = p->pNext; + } while (p); + { + U8* pPayload; + U8* pPayloadStart; + RECORD_START(SEGGER_SYSVIEW_INFO_SIZE + 2 * SEGGER_SYSVIEW_QUANTA_U32 + 1 + SEGGER_SYSVIEW_MAX_STRING_LEN); + // + pPayload = pPayloadStart; + // + // Send module description + // Send event offset and number of events + // + ENCODE_U32(pPayload, ModuleId); + ENCODE_U32(pPayload, (pModule->EventOffset)); + pPayload = _EncodeStr(pPayload, sDescription, SEGGER_SYSVIEW_MAX_STRING_LEN); + _SendPacket(pPayloadStart, pPayload, SYSVIEW_EVTID_MODULEDESC); + RECORD_END(); + } +} + +/********************************************************************* +* +* SEGGER_SYSVIEW_SendModule() +* +* Function description +* Sends the information of a registered module to the host. +* +* Parameters +* ModuleId - Id of the requested module. +*/ +void SEGGER_SYSVIEW_SendModule(U8 ModuleId) { + SEGGER_SYSVIEW_MODULE* pModule; + U32 n; + + if (_pFirstModule != 0) { + pModule = _pFirstModule; + for (n = 0; n < ModuleId; n++) { + pModule = pModule->pNext; + if (pModule == 0) { + break; + } + } + if (pModule != 0) { + U8* pPayload; + U8* pPayloadStart; + RECORD_START(SEGGER_SYSVIEW_INFO_SIZE + 2 * SEGGER_SYSVIEW_QUANTA_U32 + 1 + SEGGER_SYSVIEW_MAX_STRING_LEN); + // + pPayload = pPayloadStart; + // + // Send module description + // Send event offset and number of events + // + ENCODE_U32(pPayload, ModuleId); + ENCODE_U32(pPayload, (pModule->EventOffset)); + pPayload = _EncodeStr(pPayload, pModule->sModule, SEGGER_SYSVIEW_MAX_STRING_LEN); + _SendPacket(pPayloadStart, pPayload, SYSVIEW_EVTID_MODULEDESC); + RECORD_END(); + } + } +} + +/********************************************************************* +* +* SEGGER_SYSVIEW_SendModuleDescription() +* +* Function description +* Triggers a send of the registered module descriptions. +* +*/ +void SEGGER_SYSVIEW_SendModuleDescription(void) { + SEGGER_SYSVIEW_MODULE* pModule; + + if (_pFirstModule != 0) { + pModule = _pFirstModule; + do { + if (pModule->pfSendModuleDesc) { + pModule->pfSendModuleDesc(); + } + pModule = pModule->pNext; + } while (pModule); + } +} + +/********************************************************************* +* +* SEGGER_SYSVIEW_SendNumModules() +* +* Function description +* Send the number of registered modules to the host. +*/ +void SEGGER_SYSVIEW_SendNumModules(void) { + U8* pPayload; + U8* pPayloadStart; + RECORD_START(SEGGER_SYSVIEW_INFO_SIZE + 2*SEGGER_SYSVIEW_QUANTA_U32); + pPayload = pPayloadStart; + ENCODE_U32(pPayload, _NumModules); + _SendPacket(pPayloadStart, pPayload, SYSVIEW_EVTID_NUMMODULES); + RECORD_END(); +} + +#ifndef SEGGER_SYSVIEW_EXCLUDE_PRINTF // Define in project to avoid warnings about variable parameter list + +/********************************************************************* +* +* SEGGER_SYSVIEW_PrintfHostEx() +* +* Function description +* Print a string which is formatted on the host by SystemViewer +* with Additional information. +* +* Parameters +* s - String to be formatted. +* Options - Options for the string. i.e. Log level. +* +* Additional information +* All format arguments are treated as 32-bit scalar values. +*/ +void SEGGER_SYSVIEW_PrintfHostEx(const char* s, U32 Options, ...) { + va_list ParamList; + + va_start(ParamList, Options); + _VPrintHost(s, Options, &ParamList); + va_end(ParamList); +} + +/********************************************************************* +* +* SEGGER_SYSVIEW_PrintfHost() +* +* Function description +* Print a string which is formatted on the host by SystemViewer. +* +* Parameters +* s - String to be formatted. +* +* Additional information +* All format arguments are treated as 32-bit scalar values. +*/ +void SEGGER_SYSVIEW_PrintfHost(const char* s, ...) { + va_list ParamList; + + va_start(ParamList, s); + _VPrintHost(s, SEGGER_SYSVIEW_LOG, &ParamList); + va_end(ParamList); +} + +/********************************************************************* +* +* SEGGER_SYSVIEW_WarnfHost() +* +* Function description +* Print a warnin string which is formatted on the host by +* SystemViewer. +* +* Parameters +* s - String to be formatted. +* +* Additional information +* All format arguments are treated as 32-bit scalar values. +*/ +void SEGGER_SYSVIEW_WarnfHost(const char* s, ...) { + va_list ParamList; + + va_start(ParamList, s); + _VPrintHost(s, SEGGER_SYSVIEW_WARNING, &ParamList); + va_end(ParamList); +} + +/********************************************************************* +* +* SEGGER_SYSVIEW_ErrorfHost() +* +* Function description +* Print an error string which is formatted on the host by +* SystemViewer. +* +* Parameters +* s - String to be formatted. +* +* Additional information +* All format arguments are treated as 32-bit scalar values. +*/ +void SEGGER_SYSVIEW_ErrorfHost(const char* s, ...) { + va_list ParamList; + + va_start(ParamList, s); + _VPrintHost(s, SEGGER_SYSVIEW_ERROR, &ParamList); + va_end(ParamList); +} + +/********************************************************************* +* +* SEGGER_SYSVIEW_PrintfTargetEx() +* +* Function description +* Print a string which is formatted on the target before sent to +* the host with Additional information. +* +* Parameters +* s - String to be formatted. +* Options - Options for the string. i.e. Log level. +*/ +void SEGGER_SYSVIEW_PrintfTargetEx(const char* s, U32 Options, ...) { + va_list ParamList; + + va_start(ParamList, Options); + _VPrintTarget(s, Options, &ParamList); + va_end(ParamList); +} + +/********************************************************************* +* +* SEGGER_SYSVIEW_PrintfTarget() +* +* Function description +* Print a string which is formatted on the target before sent to +* the host. +* +* Parameters +* s - String to be formatted. +*/ +void SEGGER_SYSVIEW_PrintfTarget(const char* s, ...) { + va_list ParamList; + + va_start(ParamList, s); + _VPrintTarget(s, SEGGER_SYSVIEW_LOG, &ParamList); + va_end(ParamList); +} + +/********************************************************************* +* +* SEGGER_SYSVIEW_WarnfTarget() +* +* Function description +* Print a warning string which is formatted on the target before +* sent to the host. +* +* Parameters +* s - String to be formatted. +*/ +void SEGGER_SYSVIEW_WarnfTarget(const char* s, ...) { + va_list ParamList; + + va_start(ParamList, s); + _VPrintTarget(s, SEGGER_SYSVIEW_WARNING, &ParamList); + va_end(ParamList); +} + +/********************************************************************* +* +* SEGGER_SYSVIEW_ErrorfTarget() +* +* Function description +* Print an error string which is formatted on the target before +* sent to the host. +* +* Parameters +* s - String to be formatted. +*/ +void SEGGER_SYSVIEW_ErrorfTarget(const char* s, ...) { + va_list ParamList; + + va_start(ParamList, s); + _VPrintTarget(s, SEGGER_SYSVIEW_ERROR, &ParamList); + va_end(ParamList); +} +#endif // SEGGER_SYSVIEW_EXCLUDE_PRINTF + +/********************************************************************* +* +* SEGGER_SYSVIEW_Print() +* +* Function description +* Print a string to the host. +* +* Parameters +* s - String to sent. +*/ +void SEGGER_SYSVIEW_Print(const char* s) { + U8* pPayload; + U8* pPayloadStart; + RECORD_START(SEGGER_SYSVIEW_INFO_SIZE + 2 * SEGGER_SYSVIEW_QUANTA_U32 + SEGGER_SYSVIEW_MAX_STRING_LEN); + // + pPayload = _EncodeStr(pPayloadStart, s, SEGGER_SYSVIEW_MAX_STRING_LEN); + ENCODE_U32(pPayload, SEGGER_SYSVIEW_LOG); + ENCODE_U32(pPayload, 0); + _SendPacket(pPayloadStart, pPayload, SYSVIEW_EVTID_PRINT_FORMATTED); + RECORD_END(); +} + +/********************************************************************* +* +* SEGGER_SYSVIEW_Warn() +* +* Function description +* Print a warning string to the host. +* +* Parameters +* s - String to sent. +*/ +void SEGGER_SYSVIEW_Warn(const char* s) { + U8* pPayload; + U8* pPayloadStart; + RECORD_START(SEGGER_SYSVIEW_INFO_SIZE + 2 * SEGGER_SYSVIEW_QUANTA_U32 + SEGGER_SYSVIEW_MAX_STRING_LEN); + // + pPayload = _EncodeStr(pPayloadStart, s, SEGGER_SYSVIEW_MAX_STRING_LEN); + ENCODE_U32(pPayload, SEGGER_SYSVIEW_WARNING); + ENCODE_U32(pPayload, 0); + _SendPacket(pPayloadStart, pPayload, SYSVIEW_EVTID_PRINT_FORMATTED); + RECORD_END(); +} + +/********************************************************************* +* +* SEGGER_SYSVIEW_Error() +* +* Function description +* Print an error string to the host. +* +* Parameters +* s - String to sent. +*/ +void SEGGER_SYSVIEW_Error(const char* s) { + U8* pPayload; + U8* pPayloadStart; + RECORD_START(SEGGER_SYSVIEW_INFO_SIZE + 2 * SEGGER_SYSVIEW_QUANTA_U32 + SEGGER_SYSVIEW_MAX_STRING_LEN); + // + pPayload = _EncodeStr(pPayloadStart, s, SEGGER_SYSVIEW_MAX_STRING_LEN); + ENCODE_U32(pPayload, SEGGER_SYSVIEW_ERROR); + ENCODE_U32(pPayload, 0); + _SendPacket(pPayloadStart, pPayload, SYSVIEW_EVTID_PRINT_FORMATTED); + RECORD_END(); +} + +/********************************************************************* +* +* SEGGER_SYSVIEW_EnableEvents() +* +* Function description +* Enable standard SystemView events to be generated. +* +* Parameters +* EnableMask - Events to be enabled. +*/ +void SEGGER_SYSVIEW_EnableEvents(U32 EnableMask) { + _SYSVIEW_Globals.DisabledEvents &= ~EnableMask; +} + +/********************************************************************* +* +* SEGGER_SYSVIEW_DisableEvents() +* +* Function description +* Disable standard SystemView events to not be generated. +* +* Parameters +* DisableMask - Events to be disabled. +*/ +void SEGGER_SYSVIEW_DisableEvents(U32 DisableMask) { + _SYSVIEW_Globals.DisabledEvents |= DisableMask; +} + + +/*************************** End of file ****************************/ diff --git a/components/app_trace/sys_view/SEGGER/SEGGER_SYSVIEW.h b/components/app_trace/sys_view/SEGGER/SEGGER_SYSVIEW.h new file mode 100644 index 0000000000..79b9aca057 --- /dev/null +++ b/components/app_trace/sys_view/SEGGER/SEGGER_SYSVIEW.h @@ -0,0 +1,334 @@ +/********************************************************************* +* SEGGER Microcontroller GmbH & Co. KG * +* The Embedded Experts * +********************************************************************** +* * +* (c) 2015 - 2017 SEGGER Microcontroller GmbH & Co. KG * +* * +* www.segger.com Support: support@segger.com * +* * +********************************************************************** +* * +* SEGGER SystemView * Real-time application analysis * +* * +********************************************************************** +* * +* All rights reserved. * +* * +* SEGGER strongly recommends to not make any changes * +* to or modify the source code of this software in order to stay * +* compatible with the RTT protocol and J-Link. * +* * +* Redistribution and use in source and binary forms, with or * +* without modification, are permitted provided that the following * +* conditions are met: * +* * +* o Redistributions of source code must retain the above copyright * +* notice, this list of conditions and the following disclaimer. * +* * +* o Redistributions in binary form must reproduce the above * +* copyright notice, this list of conditions and the following * +* disclaimer in the documentation and/or other materials provided * +* with the distribution. * +* * +* o Neither the name of SEGGER Microcontroller GmbH & Co. KG * +* nor the names of its contributors may be used to endorse or * +* promote products derived from this software without specific * +* prior written permission. * +* * +* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * +* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * +* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * +* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * +* DISCLAIMED. IN NO EVENT SHALL SEGGER Microcontroller BE LIABLE FOR * +* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * +* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * +* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * +* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * +* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * +* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * +* DAMAGE. * +* * +********************************************************************** +* * +* SystemView version: V2.42 * +* * +********************************************************************** +-------------------------- END-OF-HEADER ----------------------------- +File : SEGGER_SYSVIEW.h +Purpose : System visualization API. +Revision: $Rev: 5626 $ +*/ + +#ifndef SEGGER_SYSVIEW_H +#define SEGGER_SYSVIEW_H + +/********************************************************************* +* +* #include Section +* +********************************************************************** +*/ + +#include "SEGGER.h" + +#ifdef __cplusplus +extern "C" { +#endif + + +/********************************************************************* +* +* Defines, fixed +* +********************************************************************** +*/ + +#define SEGGER_SYSVIEW_VERSION 21000 + +#define SEGGER_SYSVIEW_INFO_SIZE 9 // Minimum size, which has to be reserved for a packet. 1-2 byte of message type, 0-2 byte of payload length, 1-5 bytes of timestamp. +#define SEGGER_SYSVIEW_QUANTA_U32 5 // Maximum number of bytes to encode a U32, should be reserved for each 32-bit value in a packet. + +#define SEGGER_SYSVIEW_LOG (0u) +#define SEGGER_SYSVIEW_WARNING (1u) +#define SEGGER_SYSVIEW_ERROR (2u) +#define SEGGER_SYSVIEW_FLAG_APPEND (1u << 6) + +#define SEGGER_SYSVIEW_PREPARE_PACKET(p) (p) + 4 +// +// SystemView events. First 32 IDs from 0 .. 31 are reserved for these +// +#define SYSVIEW_EVTID_NOP 0 // Dummy packet. +#define SYSVIEW_EVTID_OVERFLOW 1 +#define SYSVIEW_EVTID_ISR_ENTER 2 +#define SYSVIEW_EVTID_ISR_EXIT 3 +#define SYSVIEW_EVTID_TASK_START_EXEC 4 +#define SYSVIEW_EVTID_TASK_STOP_EXEC 5 +#define SYSVIEW_EVTID_TASK_START_READY 6 +#define SYSVIEW_EVTID_TASK_STOP_READY 7 +#define SYSVIEW_EVTID_TASK_CREATE 8 +#define SYSVIEW_EVTID_TASK_INFO 9 +#define SYSVIEW_EVTID_TRACE_START 10 +#define SYSVIEW_EVTID_TRACE_STOP 11 +#define SYSVIEW_EVTID_SYSTIME_CYCLES 12 +#define SYSVIEW_EVTID_SYSTIME_US 13 +#define SYSVIEW_EVTID_SYSDESC 14 +#define SYSVIEW_EVTID_USER_START 15 +#define SYSVIEW_EVTID_USER_STOP 16 +#define SYSVIEW_EVTID_IDLE 17 +#define SYSVIEW_EVTID_ISR_TO_SCHEDULER 18 +#define SYSVIEW_EVTID_TIMER_ENTER 19 +#define SYSVIEW_EVTID_TIMER_EXIT 20 +#define SYSVIEW_EVTID_STACK_INFO 21 +#define SYSVIEW_EVTID_MODULEDESC 22 + +#define SYSVIEW_EVTID_INIT 24 +#define SYSVIEW_EVTID_NAME_RESOURCE 25 +#define SYSVIEW_EVTID_PRINT_FORMATTED 26 +#define SYSVIEW_EVTID_NUMMODULES 27 +#define SYSVIEW_EVTID_END_CALL 28 +#define SYSVIEW_EVTID_TASK_TERMINATE 29 + +#define SYSVIEW_EVTID_EX 31 +// +// Event masks to disable/enable events +// +#define SYSVIEW_EVTMASK_NOP (1 << SYSVIEW_EVTID_NOP) +#define SYSVIEW_EVTMASK_OVERFLOW (1 << SYSVIEW_EVTID_OVERFLOW) +#define SYSVIEW_EVTMASK_ISR_ENTER (1 << SYSVIEW_EVTID_ISR_ENTER) +#define SYSVIEW_EVTMASK_ISR_EXIT (1 << SYSVIEW_EVTID_ISR_EXIT) +#define SYSVIEW_EVTMASK_TASK_START_EXEC (1 << SYSVIEW_EVTID_TASK_START_EXEC) +#define SYSVIEW_EVTMASK_TASK_STOP_EXEC (1 << SYSVIEW_EVTID_TASK_STOP_EXEC) +#define SYSVIEW_EVTMASK_TASK_START_READY (1 << SYSVIEW_EVTID_TASK_START_READY) +#define SYSVIEW_EVTMASK_TASK_STOP_READY (1 << SYSVIEW_EVTID_TASK_STOP_READY) +#define SYSVIEW_EVTMASK_TASK_CREATE (1 << SYSVIEW_EVTID_TASK_CREATE) +#define SYSVIEW_EVTMASK_TASK_INFO (1 << SYSVIEW_EVTID_TASK_INFO) +#define SYSVIEW_EVTMASK_TRACE_START (1 << SYSVIEW_EVTID_TRACE_START) +#define SYSVIEW_EVTMASK_TRACE_STOP (1 << SYSVIEW_EVTID_TRACE_STOP) +#define SYSVIEW_EVTMASK_SYSTIME_CYCLES (1 << SYSVIEW_EVTID_SYSTIME_CYCLES) +#define SYSVIEW_EVTMASK_SYSTIME_US (1 << SYSVIEW_EVTID_SYSTIME_US) +#define SYSVIEW_EVTMASK_SYSDESC (1 << SYSVIEW_EVTID_SYSDESC) +#define SYSVIEW_EVTMASK_USER_START (1 << SYSVIEW_EVTID_USER_START) +#define SYSVIEW_EVTMASK_USER_STOP (1 << SYSVIEW_EVTID_USER_STOP) +#define SYSVIEW_EVTMASK_IDLE (1 << SYSVIEW_EVTID_IDLE) +#define SYSVIEW_EVTMASK_ISR_TO_SCHEDULER (1 << SYSVIEW_EVTID_ISR_TO_SCHEDULER) +#define SYSVIEW_EVTMASK_TIMER_ENTER (1 << SYSVIEW_EVTID_TIMER_ENTER) +#define SYSVIEW_EVTMASK_TIMER_EXIT (1 << SYSVIEW_EVTID_TIMER_EXIT) +#define SYSVIEW_EVTMASK_STACK_INFO (1 << SYSVIEW_EVTID_STACK_INFO) +#define SYSVIEW_EVTMASK_MODULEDESC (1 << SYSVIEW_EVTID_MODULEDESC) + +#define SYSVIEW_EVTMASK_INIT (1 << SYSVIEW_EVTID_INIT) +#define SYSVIEW_EVTMASK_NAME_RESOURCE (1 << SYSVIEW_EVTID_NAME_RESOURCE) +#define SYSVIEW_EVTMASK_PRINT_FORMATTED (1 << SYSVIEW_EVTID_PRINT_FORMATTED) +#define SYSVIEW_EVTMASK_NUMMODULES (1 << SYSVIEW_EVTID_NUMMODULES) +#define SYSVIEW_EVTMASK_END_CALL (1 << SYSVIEW_EVTID_END_CALL) +#define SYSVIEW_EVTMASK_TASK_TERMINATE (1 << SYSVIEW_EVTID_TASK_TERMINATE) + +#define SYSVIEW_EVTMASK_EX (1 << SYSVIEW_EVTID_EX) + +#define SYSVIEW_EVTMASK_ALL_INTERRUPTS ( SYSVIEW_EVTMASK_ISR_ENTER \ + | SYSVIEW_EVTMASK_ISR_EXIT \ + | SYSVIEW_EVTMASK_ISR_TO_SCHEDULER) +#define SYSVIEW_EVTMASK_ALL_TASKS ( SYSVIEW_EVTMASK_TASK_START_EXEC \ + | SYSVIEW_EVTMASK_TASK_STOP_EXEC \ + | SYSVIEW_EVTMASK_TASK_START_READY \ + | SYSVIEW_EVTMASK_TASK_STOP_READY \ + | SYSVIEW_EVTMASK_TASK_CREATE \ + | SYSVIEW_EVTMASK_TASK_INFO \ + | SYSVIEW_EVTMASK_STACK_INFO \ + | SYSVIEW_EVTMASK_TASK_TERMINATE) + +/********************************************************************* +* +* Structures +* +********************************************************************** +*/ + +typedef struct { + U32 TaskID; + const char* sName; + U32 Prio; + U32 StackBase; + U32 StackSize; +} SEGGER_SYSVIEW_TASKINFO; + +typedef struct SEGGER_SYSVIEW_MODULE_STRUCT SEGGER_SYSVIEW_MODULE; + +struct SEGGER_SYSVIEW_MODULE_STRUCT { + const char* sModule; + U32 NumEvents; + U32 EventOffset; + void (*pfSendModuleDesc)(void); + SEGGER_SYSVIEW_MODULE* pNext; +}; + +typedef void (SEGGER_SYSVIEW_SEND_SYS_DESC_FUNC)(void); + +/********************************************************************* +* +* API functions +* +********************************************************************** +*/ + +typedef struct { + U64 (*pfGetTime) (void); + void (*pfSendTaskList) (void); +} SEGGER_SYSVIEW_OS_API; + +/********************************************************************* +* +* Control and initialization functions +*/ +void SEGGER_SYSVIEW_Init (U32 SysFreq, U32 CPUFreq, const SEGGER_SYSVIEW_OS_API *pOSAPI, SEGGER_SYSVIEW_SEND_SYS_DESC_FUNC pfSendSysDesc); +void SEGGER_SYSVIEW_SetRAMBase (U32 RAMBaseAddress); +void SEGGER_SYSVIEW_Start (void); +void SEGGER_SYSVIEW_Stop (void); +void SEGGER_SYSVIEW_GetSysDesc (void); +void SEGGER_SYSVIEW_SendTaskList (void); +void SEGGER_SYSVIEW_SendTaskInfo (const SEGGER_SYSVIEW_TASKINFO* pInfo); +void SEGGER_SYSVIEW_SendSysDesc (const char* sSysDesc); + +/********************************************************************* +* +* Event recording functions +*/ +void SEGGER_SYSVIEW_RecordVoid (unsigned int EventId); +void SEGGER_SYSVIEW_RecordU32 (unsigned int EventId, U32 Para0); +void SEGGER_SYSVIEW_RecordU32x2 (unsigned int EventId, U32 Para0, U32 Para1); +void SEGGER_SYSVIEW_RecordU32x3 (unsigned int EventId, U32 Para0, U32 Para1, U32 Para2); +void SEGGER_SYSVIEW_RecordU32x4 (unsigned int EventId, U32 Para0, U32 Para1, U32 Para2, U32 Para3); +void SEGGER_SYSVIEW_RecordU32x5 (unsigned int EventId, U32 Para0, U32 Para1, U32 Para2, U32 Para3, U32 Para4); +void SEGGER_SYSVIEW_RecordU32x6 (unsigned int EventId, U32 Para0, U32 Para1, U32 Para2, U32 Para3, U32 Para4, U32 Para5); +void SEGGER_SYSVIEW_RecordU32x7 (unsigned int EventId, U32 Para0, U32 Para1, U32 Para2, U32 Para3, U32 Para4, U32 Para5, U32 Para6); +void SEGGER_SYSVIEW_RecordU32x8 (unsigned int EventId, U32 Para0, U32 Para1, U32 Para2, U32 Para3, U32 Para4, U32 Para5, U32 Para6, U32 Para7); +void SEGGER_SYSVIEW_RecordU32x9 (unsigned int EventId, U32 Para0, U32 Para1, U32 Para2, U32 Para3, U32 Para4, U32 Para5, U32 Para6, U32 Para7, U32 Para8); +void SEGGER_SYSVIEW_RecordU32x10 (unsigned int EventId, U32 Para0, U32 Para1, U32 Para2, U32 Para3, U32 Para4, U32 Para5, U32 Para6, U32 Para7, U32 Para8, U32 Para9); +void SEGGER_SYSVIEW_RecordString (unsigned int EventId, const char* pString); +void SEGGER_SYSVIEW_RecordSystime (void); +void SEGGER_SYSVIEW_RecordEnterISR (U32 IrqId); +void SEGGER_SYSVIEW_RecordExitISR (void); +void SEGGER_SYSVIEW_RecordExitISRToScheduler (void); +void SEGGER_SYSVIEW_RecordEnterTimer (U32 TimerId); +void SEGGER_SYSVIEW_RecordExitTimer (void); +void SEGGER_SYSVIEW_RecordEndCall (unsigned int EventID); +void SEGGER_SYSVIEW_RecordEndCallU32 (unsigned int EventID, U32 Para0); + +void SEGGER_SYSVIEW_OnIdle (void); +void SEGGER_SYSVIEW_OnTaskCreate (U32 TaskId); +void SEGGER_SYSVIEW_OnTaskTerminate (U32 TaskId); +void SEGGER_SYSVIEW_OnTaskStartExec (U32 TaskId); +void SEGGER_SYSVIEW_OnTaskStopExec (void); +void SEGGER_SYSVIEW_OnTaskStartReady (U32 TaskId); +void SEGGER_SYSVIEW_OnTaskStopReady (U32 TaskId, unsigned int Cause); +void SEGGER_SYSVIEW_OnUserStart (unsigned int UserId); // Start of user defined event (such as a subroutine to profile) +void SEGGER_SYSVIEW_OnUserStop (unsigned int UserId); // Start of user defined event + +void SEGGER_SYSVIEW_NameResource (U32 ResourceId, const char* sName); + +int SEGGER_SYSVIEW_SendPacket (U8* pPacket, U8* pPayloadEnd, unsigned int EventId); + +/********************************************************************* +* +* Event parameter encoding functions +*/ +U8* SEGGER_SYSVIEW_EncodeU32 (U8* pPayload, U32 Value); +U8* SEGGER_SYSVIEW_EncodeData (U8* pPayload, const char* pSrc, unsigned int Len); +U8* SEGGER_SYSVIEW_EncodeString (U8* pPayload, const char* s, unsigned int MaxLen); +U8* SEGGER_SYSVIEW_EncodeId (U8* pPayload, U32 Id); +U32 SEGGER_SYSVIEW_ShrinkId (U32 Id); + + +/********************************************************************* +* +* Middleware module registration +*/ +void SEGGER_SYSVIEW_RegisterModule (SEGGER_SYSVIEW_MODULE* pModule); +void SEGGER_SYSVIEW_RecordModuleDescription (const SEGGER_SYSVIEW_MODULE* pModule, const char* sDescription); +void SEGGER_SYSVIEW_SendModule (U8 ModuleId); +void SEGGER_SYSVIEW_SendModuleDescription (void); +void SEGGER_SYSVIEW_SendNumModules (void); + +/********************************************************************* +* +* printf-Style functions +*/ +#ifndef SEGGER_SYSVIEW_EXCLUDE_PRINTF // Define in project to avoid warnings about variable parameter list +void SEGGER_SYSVIEW_PrintfHostEx (const char* s, U32 Options, ...); +void SEGGER_SYSVIEW_PrintfTargetEx (const char* s, U32 Options, ...); +void SEGGER_SYSVIEW_PrintfHost (const char* s, ...); +void SEGGER_SYSVIEW_PrintfTarget (const char* s, ...); +void SEGGER_SYSVIEW_WarnfHost (const char* s, ...); +void SEGGER_SYSVIEW_WarnfTarget (const char* s, ...); +void SEGGER_SYSVIEW_ErrorfHost (const char* s, ...); +void SEGGER_SYSVIEW_ErrorfTarget (const char* s, ...); +#endif + +void SEGGER_SYSVIEW_Print (const char* s); +void SEGGER_SYSVIEW_Warn (const char* s); +void SEGGER_SYSVIEW_Error (const char* s); + +/********************************************************************* +* +* Run-time configuration functions +*/ +void SEGGER_SYSVIEW_EnableEvents (U32 EnableMask); +void SEGGER_SYSVIEW_DisableEvents (U32 DisableMask); + +/********************************************************************* +* +* Application-provided functions +*/ +void SEGGER_SYSVIEW_Conf (void); +U32 SEGGER_SYSVIEW_X_GetTimestamp (void); +U32 SEGGER_SYSVIEW_X_GetInterruptId (void); + +#ifdef __cplusplus +} +#endif + +#endif + +/*************************** End of file ****************************/ diff --git a/components/app_trace/sys_view/SEGGER/SEGGER_SYSVIEW_ConfDefaults.h b/components/app_trace/sys_view/SEGGER/SEGGER_SYSVIEW_ConfDefaults.h new file mode 100644 index 0000000000..162e6db705 --- /dev/null +++ b/components/app_trace/sys_view/SEGGER/SEGGER_SYSVIEW_ConfDefaults.h @@ -0,0 +1,178 @@ +/********************************************************************* +* SEGGER Microcontroller GmbH & Co. KG * +* The Embedded Experts * +********************************************************************** +* * +* (c) 2015 - 2017 SEGGER Microcontroller GmbH & Co. KG * +* * +* www.segger.com Support: support@segger.com * +* * +********************************************************************** +* * +* SEGGER SystemView * Real-time application analysis * +* * +********************************************************************** +* * +* All rights reserved. * +* * +* SEGGER strongly recommends to not make any changes * +* to or modify the source code of this software in order to stay * +* compatible with the RTT protocol and J-Link. * +* * +* Redistribution and use in source and binary forms, with or * +* without modification, are permitted provided that the following * +* conditions are met: * +* * +* o Redistributions of source code must retain the above copyright * +* notice, this list of conditions and the following disclaimer. * +* * +* o Redistributions in binary form must reproduce the above * +* copyright notice, this list of conditions and the following * +* disclaimer in the documentation and/or other materials provided * +* with the distribution. * +* * +* o Neither the name of SEGGER Microcontroller GmbH & Co. KG * +* nor the names of its contributors may be used to endorse or * +* promote products derived from this software without specific * +* prior written permission. * +* * +* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * +* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * +* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * +* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * +* DISCLAIMED. IN NO EVENT SHALL SEGGER Microcontroller BE LIABLE FOR * +* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * +* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * +* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * +* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * +* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * +* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * +* DAMAGE. * +* * +********************************************************************** +* * +* SystemView version: V2.42 * +* * +********************************************************************** +-------------------------- END-OF-HEADER ----------------------------- +File : SEGGER_SYSVIEW_ConfDefaults.h +Purpose : Defines defaults for configurable defines used in + SEGGER SystemView. +Revision: $Rev: 3734 $ +*/ + +#ifndef SEGGER_SYSVIEW_CONFDEFAULTS_H +#define SEGGER_SYSVIEW_CONFDEFAULTS_H + +/********************************************************************* +* +* #include Section +* +********************************************************************** +*/ + +#include "SEGGER_SYSVIEW_Conf.h" +#include "SEGGER_RTT_Conf.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/********************************************************************* +* +* Configuration defaults +* +********************************************************************** +*/ + +// Number of bytes that SystemView uses for a buffer. +#ifndef SEGGER_SYSVIEW_RTT_BUFFER_SIZE + #define SEGGER_SYSVIEW_RTT_BUFFER_SIZE 1024 +#endif + +// The RTT channel that SystemView will use. +#ifndef SEGGER_SYSVIEW_RTT_CHANNEL + #define SEGGER_SYSVIEW_RTT_CHANNEL 0 +#endif +// Sanity check of RTT channel +#if (SEGGER_SYSVIEW_RTT_CHANNEL == 0) && (SEGGER_RTT_MAX_NUM_UP_BUFFERS < 2) + #error "SEGGER_RTT_MAX_NUM_UP_BUFFERS in SEGGER_RTT_Conf.h has to be > 1!" +#elif (SEGGER_SYSVIEW_RTT_CHANNEL >= SEGGER_RTT_MAX_NUM_UP_BUFFERS) + #error "SEGGER_RTT_MAX_NUM_UP_BUFFERS in SEGGER_RTT_Conf.h has to be > SEGGER_SYSVIEW_RTT_CHANNEL!" +#endif + +// Place the SystemView buffer into its own/the RTT section +#if !(defined SEGGER_SYSVIEW_BUFFER_SECTION) && (defined SEGGER_RTT_SECTION) + #define SEGGER_SYSVIEW_BUFFER_SECTION SEGGER_RTT_SECTION +#endif + +// Retrieve a system timestamp. This gets the Cortex-M cycle counter. +#ifndef SEGGER_SYSVIEW_GET_TIMESTAMP + #error "SEGGER_SYSVIEW_GET_TIMESTAMP has to be defined in SEGGER_SYSVIEW_Conf.h!" +#endif + +// Define number of valid bits low-order delivered by clock source. +#ifndef SEGGER_SYSVIEW_TIMESTAMP_BITS + #define SEGGER_SYSVIEW_TIMESTAMP_BITS 32 +#endif + +// Lowest Id reported by the Application. +#ifndef SEGGER_SYSVIEW_ID_BASE + #define SEGGER_SYSVIEW_ID_BASE 0 +#endif + +// Number of bits to shift Ids to save bandwidth +#ifndef SEGGER_SYSVIEW_ID_SHIFT + #define SEGGER_SYSVIEW_ID_SHIFT 0 +#endif + +#ifndef SEGGER_SYSVIEW_GET_INTERRUPT_ID + #error "SEGGER_SYSVIEW_GET_INTERRUPT_ID has to be defined in SEGGER_SYSVIEW_Conf.h!" +#endif + +#ifndef SEGGER_SYSVIEW_MAX_ARGUMENTS + #define SEGGER_SYSVIEW_MAX_ARGUMENTS 16 +#endif + +#ifndef SEGGER_SYSVIEW_MAX_STRING_LEN + #define SEGGER_SYSVIEW_MAX_STRING_LEN 128 +#endif + +// Use a static buffer instead of a buffer on the stack for packets +#ifndef SEGGER_SYSVIEW_USE_STATIC_BUFFER + #define SEGGER_SYSVIEW_USE_STATIC_BUFFER 1 +#endif + +// Maximum packet size used by SystemView for the static buffer +#ifndef SEGGER_SYSVIEW_MAX_PACKET_SIZE + #define SEGGER_SYSVIEW_MAX_PACKET_SIZE SEGGER_SYSVIEW_INFO_SIZE + SEGGER_SYSVIEW_MAX_STRING_LEN + 2 * SEGGER_SYSVIEW_QUANTA_U32 + SEGGER_SYSVIEW_MAX_ARGUMENTS * SEGGER_SYSVIEW_QUANTA_U32 +#endif + +// Use post-mortem analysis instead of real-time analysis +#ifndef SEGGER_SYSVIEW_POST_MORTEM_MODE + #define SEGGER_SYSVIEW_POST_MORTEM_MODE 0 +#endif + +// Configure how frequently syncronization is sent +#ifndef SEGGER_SYSVIEW_SYNC_PERIOD_SHIFT + #define SEGGER_SYSVIEW_SYNC_PERIOD_SHIFT 8 +#endif + +// Lock SystemView (nestable) +#ifndef SEGGER_SYSVIEW_LOCK + #define SEGGER_SYSVIEW_LOCK() SEGGER_RTT_LOCK() +#endif + +// Unlock SystemView (nestable) +#ifndef SEGGER_SYSVIEW_UNLOCK + #define SEGGER_SYSVIEW_UNLOCK() SEGGER_RTT_UNLOCK() +#endif + +#ifdef __cplusplus +} +#endif + +#endif + +/*************************** End of file ****************************/ diff --git a/components/app_trace/sys_view/SEGGER/SEGGER_SYSVIEW_Int.h b/components/app_trace/sys_view/SEGGER/SEGGER_SYSVIEW_Int.h new file mode 100644 index 0000000000..84d8ad5e2d --- /dev/null +++ b/components/app_trace/sys_view/SEGGER/SEGGER_SYSVIEW_Int.h @@ -0,0 +1,110 @@ +/********************************************************************* +* SEGGER Microcontroller GmbH & Co. KG * +* The Embedded Experts * +********************************************************************** +* * +* (c) 2015 - 2017 SEGGER Microcontroller GmbH & Co. KG * +* * +* www.segger.com Support: support@segger.com * +* * +********************************************************************** +* * +* SEGGER SystemView * Real-time application analysis * +* * +********************************************************************** +* * +* All rights reserved. * +* * +* SEGGER strongly recommends to not make any changes * +* to or modify the source code of this software in order to stay * +* compatible with the RTT protocol and J-Link. * +* * +* Redistribution and use in source and binary forms, with or * +* without modification, are permitted provided that the following * +* conditions are met: * +* * +* o Redistributions of source code must retain the above copyright * +* notice, this list of conditions and the following disclaimer. * +* * +* o Redistributions in binary form must reproduce the above * +* copyright notice, this list of conditions and the following * +* disclaimer in the documentation and/or other materials provided * +* with the distribution. * +* * +* o Neither the name of SEGGER Microcontroller GmbH & Co. KG * +* nor the names of its contributors may be used to endorse or * +* promote products derived from this software without specific * +* prior written permission. * +* * +* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * +* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * +* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * +* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * +* DISCLAIMED. IN NO EVENT SHALL SEGGER Microcontroller BE LIABLE FOR * +* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * +* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * +* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * +* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * +* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * +* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * +* DAMAGE. * +* * +********************************************************************** +* * +* SystemView version: V2.42 * +* * +********************************************************************** +-------------------------- END-OF-HEADER ----------------------------- +File : SEGGER_SYSVIEW_Int.h +Purpose : SEGGER SystemView internal header. +Revision: $Rev: 5626 $ +*/ + +#ifndef SEGGER_SYSVIEW_INT_H +#define SEGGER_SYSVIEW_INT_H + +/********************************************************************* +* +* #include Section +* +********************************************************************** +*/ + +#include "SEGGER_SYSVIEW.h" +#include "SEGGER_SYSVIEW_Conf.h" +#include "SEGGER_SYSVIEW_ConfDefaults.h" + +#ifdef __cplusplus +extern "C" { +#endif + + +/********************************************************************* +* +* Private data types +* +********************************************************************** +*/ +// +// Commands that Host can send to target +// +typedef enum { + SEGGER_SYSVIEW_COMMAND_ID_START = 1, + SEGGER_SYSVIEW_COMMAND_ID_STOP, + SEGGER_SYSVIEW_COMMAND_ID_GET_SYSTIME, + SEGGER_SYSVIEW_COMMAND_ID_GET_TASKLIST, + SEGGER_SYSVIEW_COMMAND_ID_GET_SYSDESC, + SEGGER_SYSVIEW_COMMAND_ID_GET_NUMMODULES, + SEGGER_SYSVIEW_COMMAND_ID_GET_MODULEDESC, + // Extended commands: Commands >= 128 have a second parameter + SEGGER_SYSVIEW_COMMAND_ID_GET_MODULE = 128 +} SEGGER_SYSVIEW_COMMAND_ID; + +#ifdef __cplusplus +} +#endif + +#endif + +/*************************** End of file ****************************/ diff --git a/components/app_trace/sys_view/Sample/Config/SEGGER_SYSVIEW_Config_FreeRTOS.c b/components/app_trace/sys_view/Sample/Config/SEGGER_SYSVIEW_Config_FreeRTOS.c new file mode 100644 index 0000000000..aa018f507c --- /dev/null +++ b/components/app_trace/sys_view/Sample/Config/SEGGER_SYSVIEW_Config_FreeRTOS.c @@ -0,0 +1,333 @@ +/********************************************************************* +* SEGGER Microcontroller GmbH & Co. KG * +* The Embedded Experts * +********************************************************************** +* * +* (c) 2015 - 2017 SEGGER Microcontroller GmbH & Co. KG * +* * +* www.segger.com Support: support@segger.com * +* * +********************************************************************** +* * +* SEGGER SystemView * Real-time application analysis * +* * +********************************************************************** +* * +* All rights reserved. * +* * +* SEGGER strongly recommends to not make any changes * +* to or modify the source code of this software in order to stay * +* compatible with the RTT protocol and J-Link. * +* * +* Redistribution and use in source and binary forms, with or * +* without modification, are permitted provided that the following * +* conditions are met: * +* * +* o Redistributions of source code must retain the above copyright * +* notice, this list of conditions and the following disclaimer. * +* * +* o Redistributions in binary form must reproduce the above * +* copyright notice, this list of conditions and the following * +* disclaimer in the documentation and/or other materials provided * +* with the distribution. * +* * +* o Neither the name of SEGGER Microcontroller GmbH & Co. KG * +* nor the names of its contributors may be used to endorse or * +* promote products derived from this software without specific * +* prior written permission. * +* * +* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * +* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * +* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * +* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * +* DISCLAIMED. IN NO EVENT SHALL SEGGER Microcontroller BE LIABLE FOR * +* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * +* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * +* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * +* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * +* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * +* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * +* DAMAGE. * +* * +********************************************************************** +* * +* SystemView version: V2.42 * +* * +********************************************************************** +-------------------------- END-OF-HEADER ----------------------------- + +File : SEGGER_SYSVIEW_Config_FreeRTOS.c +Purpose : Sample setup configuration of SystemView with FreeRTOS. +Revision: $Rev: 3734 $ +*/ +#include "freertos/FreeRTOS.h" +#include "SEGGER_SYSVIEW.h" +#include "rom/ets_sys.h" +#if CONFIG_FREERTOS_UNICORE == 0 +#include "driver/timer.h" +#endif +#include "esp_app_trace.h" +#include "esp_app_trace_util.h" +#include "esp_intr_alloc.h" + +extern const SEGGER_SYSVIEW_OS_API SYSVIEW_X_OS_TraceAPI; + +/********************************************************************* +* +* Defines, configurable +* +********************************************************************** +*/ +// The application name to be displayed in SystemViewer +#define SYSVIEW_APP_NAME "FreeRTOS Application" + +// The target device name +#define SYSVIEW_DEVICE_NAME "ESP32" + +// Frequency of the timestamp. +#if CONFIG_FREERTOS_UNICORE == 0 +#define SYSVIEW_TIMESTAMP_FREQ (TIMER_BASE_CLK/2) +#else +#define SYSVIEW_TIMESTAMP_FREQ (XT_CLOCK_FREQ) +#endif +// System Frequency. +#define SYSVIEW_CPU_FREQ (XT_CLOCK_FREQ) + +// The lowest RAM address used for IDs (pointers) +#define SYSVIEW_RAM_BASE (0x3F400000) + +#if CONFIG_FREERTOS_CORETIMER_0 + #define SYSTICK_INTR_ID (ETS_INTERNAL_TIMER0_INTR_SOURCE+ETS_INTERNAL_INTR_SOURCE_OFF) +#endif +#if CONFIG_FREERTOS_CORETIMER_1 + #define SYSTICK_INTR_ID (ETS_INTERNAL_TIMER1_INTR_SOURCE+ETS_INTERNAL_INTR_SOURCE_OFF) +#endif + +#if CONFIG_FREERTOS_UNICORE == 0 +static timer_idx_t s_ts_timer_idx; +static timer_group_t s_ts_timer_group; +#endif + +// SystemView is single core specific: it implies that SEGGER_SYSVIEW_LOCK() +// disables IRQs (disables rescheduling globaly). So we can not use finite timeouts for locks and return error +// in case of expiration, because error will not be handled and SEGGER's code will go further implying that +// everything is fine, so for multi-core env we have to wait on underlying lock forever +#define SEGGER_LOCK_WAIT_TMO ESP_APPTRACE_TMO_INFINITE + +static esp_apptrace_lock_t s_sys_view_lock = {.irq_stat = 0, .portmux = portMUX_INITIALIZER_UNLOCKED}; + +static const char * const s_isr_names[] = { + [0] = "WIFI_MAC", + [1] = "WIFI_NMI", + [2] = "WIFI_BB", + [3] = "BT_MAC", + [4] = "BT_BB", + [5] = "BT_BB_NMI", + [6] = "RWBT", + [7] = "RWBLE", + [8] = "RWBT_NMI", + [9] = "RWBLE_NMI", + [10] = "SLC0", + [11] = "SLC1", + [12] = "UHCI0", + [13] = "UHCI1", + [14] = "TG0_T0_LEVEL", + [15] = "TG0_T1_LEVEL", + [16] = "TG0_WDT_LEVEL", + [17] = "TG0_LACT_LEVEL", + [18] = "TG1_T0_LEVEL", + [19] = "TG1_T1_LEVEL", + [20] = "TG1_WDT_LEVEL", + [21] = "TG1_LACT_LEVEL", + [22] = "GPIO", + [23] = "GPIO_NMI", + [24] = "FROM_CPU0", + [25] = "FROM_CPU1", + [26] = "FROM_CPU2", + [27] = "FROM_CPU3", + [28] = "SPI0", + [29] = "SPI1", + [30] = "SPI2", + [31] = "SPI3", + [32] = "I2S0", + [33] = "I2S1", + [34] = "UART0", + [35] = "UART1", + [36] = "UART2", + [37] = "SDIO_HOST", + [38] = "ETH_MAC", + [39] = "PWM0", + [40] = "PWM1", + [41] = "PWM2", + [42] = "PWM3", + [43] = "LEDC", + [44] = "EFUSE", + [45] = "CAN", + [46] = "RTC_CORE", + [47] = "RMT", + [48] = "PCNT", + [49] = "I2C_EXT0", + [50] = "I2C_EXT1", + [51] = "RSA", + [52] = "SPI1_DMA", + [53] = "SPI2_DMA", + [54] = "SPI3_DMA", + [55] = "WDT", + [56] = "TIMER1", + [57] = "TIMER2", + [58] = "TG0_T0_EDGE", + [59] = "TG0_T1_EDGE", + [60] = "TG0_WDT_EDGE", + [61] = "TG0_LACT_EDGE", + [62] = "TG1_T0_EDGE", + [63] = "TG1_T1_EDGE", + [64] = "TG1_WDT_EDGE", + [65] = "TG1_LACT_EDGE", + [66] = "MMU_IA", + [67] = "MPU_IA", + [68] = "CACHE_IA", +}; + +/********************************************************************* +* +* _cbSendSystemDesc() +* +* Function description +* Sends SystemView description strings. +*/ +static void _cbSendSystemDesc(void) { + char irq_str[32]; + SEGGER_SYSVIEW_SendSysDesc("N="SYSVIEW_APP_NAME",D="SYSVIEW_DEVICE_NAME",C=Xtensa,O=FreeRTOS"); + snprintf(irq_str, sizeof(irq_str), "I#%d=SysTick", SYSTICK_INTR_ID); + SEGGER_SYSVIEW_SendSysDesc(irq_str); + size_t isr_count = sizeof(s_isr_names)/sizeof(s_isr_names[0]); + for (size_t i = 0; i < isr_count; ++i) { + snprintf(irq_str, sizeof(irq_str), "I#%d=%s", ETS_INTERNAL_INTR_SOURCE_OFF + i, s_isr_names[i]); + SEGGER_SYSVIEW_SendSysDesc(irq_str); + } +} + +/********************************************************************* +* +* Global functions +* +********************************************************************** +*/ +#if CONFIG_FREERTOS_UNICORE == 0 +static void SEGGER_SYSVIEW_TS_Init() +{ + timer_config_t config; + +#if CONFIG_SYSVIEW_TS_SOURCE_TIMER_00 + s_ts_timer_group = TIMER_GROUP_0; + s_ts_timer_idx = TIMER_0; +#endif +#if CONFIG_SYSVIEW_TS_SOURCE_TIMER_01 + s_ts_timer_group = TIMER_GROUP_0; + s_ts_timer_idx = TIMER_1; +#endif +#if CONFIG_SYSVIEW_TS_SOURCE_TIMER_10 + s_ts_timer_group = TIMER_GROUP_1; + s_ts_timer_idx = TIMER_0; +#endif +#if CONFIG_SYSVIEW_TS_SOURCE_TIMER_11 + s_ts_timer_group = TIMER_GROUP_1; + s_ts_timer_idx = TIMER_1; +#endif + config.alarm_en = 0; + config.auto_reload = 0; + config.counter_dir = TIMER_COUNT_UP; + config.divider = 2; + config.counter_en = 0; + /*Configure timer*/ + timer_init(s_ts_timer_group, s_ts_timer_idx, &config); + /*Load counter value */ + timer_set_counter_value(s_ts_timer_group, s_ts_timer_idx, 0x00000000ULL); + /*Enable timer interrupt*/ + timer_start(s_ts_timer_group, s_ts_timer_idx); +} +#endif + +void SEGGER_SYSVIEW_Conf(void) { + U32 disable_evts = 0; + +#if CONFIG_FREERTOS_UNICORE == 0 + SEGGER_SYSVIEW_TS_Init(); +#endif + SEGGER_SYSVIEW_Init(SYSVIEW_TIMESTAMP_FREQ, SYSVIEW_CPU_FREQ, + &SYSVIEW_X_OS_TraceAPI, _cbSendSystemDesc); + SEGGER_SYSVIEW_SetRAMBase(SYSVIEW_RAM_BASE); + +#if !CONFIG_SYSVIEW_EVT_OVERFLOW_ENABLE + disable_evts |= SYSVIEW_EVTMASK_OVERFLOW; +#endif +#if !CONFIG_SYSVIEW_EVT_ISR_ENTER_ENABLE + disable_evts |= SYSVIEW_EVTMASK_ISR_ENTER; +#endif +#if !CONFIG_SYSVIEW_EVT_ISR_EXIT_ENABLE + disable_evts |= SYSVIEW_EVTMASK_ISR_EXIT; +#endif +#if !CONFIG_SYSVIEW_EVT_TASK_START_EXEC_ENABLE + disable_evts |= SYSVIEW_EVTMASK_TASK_START_EXEC; +#endif +#if !CONFIG_SYSVIEW_EVT_TASK_STOP_EXEC_ENABLE + disable_evts |= SYSVIEW_EVTMASK_TASK_STOP_EXEC; +#endif +#if !CONFIG_SYSVIEW_EVT_TASK_START_READY_ENABLE + disable_evts |= SYSVIEW_EVTMASK_TASK_START_READY; +#endif +#if !CONFIG_SYSVIEW_EVT_TASK_STOP_READY_ENABLE + disable_evts |= SYSVIEW_EVTMASK_TASK_STOP_READY; +#endif +#if !CONFIG_SYSVIEW_EVT_TASK_CREATE_ENABLE + disable_evts |= SYSVIEW_EVTMASK_TASK_CREATE; +#endif +#if !CONFIG_SYSVIEW_EVT_TASK_TERMINATE_ENABLE + disable_evts |= SYSVIEW_EVTMASK_TASK_TERMINATE; +#endif +#if !CONFIG_SYSVIEW_EVT_IDLE_ENABLE + disable_evts |= SYSVIEW_EVTMASK_IDLE; +#endif +#if !CONFIG_SYSVIEW_EVT_ISR_TO_SCHEDULER_ENABLE + disable_evts |= SYSVIEW_EVTMASK_ISR_TO_SCHEDULER; +#endif +#if !CONFIG_SYSVIEW_EVT_TIMER_ENTER_ENABLE + disable_evts |= SYSVIEW_EVTMASK_TIMER_ENTER; +#endif +#if !CONFIG_SYSVIEW_EVT_TIMER_EXIT_ENABLE + disable_evts |= SYSVIEW_EVTMASK_TIMER_EXIT; +#endif + SEGGER_SYSVIEW_DisableEvents(disable_evts); +} + +U32 SEGGER_SYSVIEW_X_GetTimestamp() +{ +#if CONFIG_FREERTOS_UNICORE == 0 + uint64_t ts = 0; + timer_get_counter_value(s_ts_timer_group, s_ts_timer_idx, &ts); + return (U32)ts; // return lower part of counter value +#else + return portGET_RUN_TIME_COUNTER_VALUE(); +#endif +} + +void SEGGER_SYSVIEW_X_RTT_Lock() +{ +} + +void SEGGER_SYSVIEW_X_RTT_Unlock() +{ +} + +void SEGGER_SYSVIEW_X_SysView_Lock() +{ + esp_apptrace_lock_take(&s_sys_view_lock, SEGGER_LOCK_WAIT_TMO); +} + +void SEGGER_SYSVIEW_X_SysView_Unlock() +{ + esp_apptrace_lock_give(&s_sys_view_lock); +} + +/*************************** End of file ****************************/ diff --git a/components/app_trace/sys_view/Sample/OS/SEGGER_SYSVIEW_FreeRTOS.c b/components/app_trace/sys_view/Sample/OS/SEGGER_SYSVIEW_FreeRTOS.c new file mode 100644 index 0000000000..803fdc7880 --- /dev/null +++ b/components/app_trace/sys_view/Sample/OS/SEGGER_SYSVIEW_FreeRTOS.c @@ -0,0 +1,290 @@ +/********************************************************************* +* SEGGER Microcontroller GmbH & Co. KG * +* The Embedded Experts * +********************************************************************** +* * +* (c) 2015 - 2017 SEGGER Microcontroller GmbH & Co. KG * +* * +* www.segger.com Support: support@segger.com * +* * +********************************************************************** +* * +* SEGGER SystemView * Real-time application analysis * +* * +********************************************************************** +* * +* All rights reserved. * +* * +* SEGGER strongly recommends to not make any changes * +* to or modify the source code of this software in order to stay * +* compatible with the RTT protocol and J-Link. * +* * +* Redistribution and use in source and binary forms, with or * +* without modification, are permitted provided that the following * +* conditions are met: * +* * +* o Redistributions of source code must retain the above copyright * +* notice, this list of conditions and the following disclaimer. * +* * +* o Redistributions in binary form must reproduce the above * +* copyright notice, this list of conditions and the following * +* disclaimer in the documentation and/or other materials provided * +* with the distribution. * +* * +* o Neither the name of SEGGER Microcontroller GmbH & Co. KG * +* nor the names of its contributors may be used to endorse or * +* promote products derived from this software without specific * +* prior written permission. * +* * +* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * +* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * +* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * +* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * +* DISCLAIMED. IN NO EVENT SHALL SEGGER Microcontroller BE LIABLE FOR * +* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * +* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * +* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * +* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * +* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * +* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * +* DAMAGE. * +* * +********************************************************************** +* * +* SystemView version: V2.42 * +* * +********************************************************************** +-------------------------- END-OF-HEADER ----------------------------- + +File : SEGGER_SYSVIEW_FreeRTOS.c +Purpose : Interface between FreeRTOS and SystemView. +Revision: $Rev: 3734 $ +*/ +#include "freertos/FreeRTOS.h" +#include "freertos/task.h" +#include "SEGGER_SYSVIEW.h" +#include "SEGGER_SYSVIEW_FreeRTOS.h" +#include "string.h" // Required for memset + + + +typedef struct SYSVIEW_FREERTOS_TASK_STATUS SYSVIEW_FREERTOS_TASK_STATUS; + +struct SYSVIEW_FREERTOS_TASK_STATUS { + U32 xHandle; + const char* pcTaskName; + unsigned uxCurrentPriority; + U32 pxStack; + unsigned uStackHighWaterMark; +}; + +static SYSVIEW_FREERTOS_TASK_STATUS _aTasks[SYSVIEW_FREERTOS_MAX_NOF_TASKS]; + +/********************************************************************* +* +* _cbSendTaskList() +* +* Function description +* This function is part of the link between FreeRTOS and SYSVIEW. +* Called from SystemView when asked by the host, it uses SYSVIEW +* functions to send the entire task list to the host. +*/ +static void _cbSendTaskList(void) { + unsigned n; + + for (n = 0; n < SYSVIEW_FREERTOS_MAX_NOF_TASKS; n++) { + if (_aTasks[n].xHandle) { +#if INCLUDE_uxTaskGetStackHighWaterMark // Report Task Stack High Watermark + _aTasks[n].uStackHighWaterMark = uxTaskGetStackHighWaterMark((TaskHandle_t)_aTasks[n].xHandle); +#endif + SYSVIEW_SendTaskInfo((U32)_aTasks[n].xHandle, _aTasks[n].pcTaskName, (unsigned)_aTasks[n].uxCurrentPriority, (U32)_aTasks[n].pxStack, (unsigned)_aTasks[n].uStackHighWaterMark); + } + } +} + +/********************************************************************* +* +* _cbGetTime() +* +* Function description +* This function is part of the link between FreeRTOS and SYSVIEW. +* Called from SystemView when asked by the host, returns the +* current system time in micro seconds. +*/ +static U64 _cbGetTime(void) { + U64 Time; + + Time = xTaskGetTickCountFromISR(); + Time *= portTICK_PERIOD_MS; + Time *= 1000; + return Time; +} + +/********************************************************************* +* +* Global functions +* +********************************************************************** +*/ +/********************************************************************* +* +* SYSVIEW_AddTask() +* +* Function description +* Add a task to the internal list and record its information. +*/ +void SYSVIEW_AddTask(U32 xHandle, const char* pcTaskName, unsigned uxCurrentPriority, U32 pxStack, unsigned uStackHighWaterMark) { + unsigned n; + + if (memcmp(pcTaskName, "IDLE", 5) == 0) { + return; + } + + for (n = 0; n < SYSVIEW_FREERTOS_MAX_NOF_TASKS; n++) { + if (_aTasks[n].xHandle == 0) { + break; + } + } + if (n == SYSVIEW_FREERTOS_MAX_NOF_TASKS) { + SEGGER_SYSVIEW_Warn("SYSTEMVIEW: Could not record task information. Maximum number of tasks reached."); + return; + } + + _aTasks[n].xHandle = xHandle; + _aTasks[n].pcTaskName = pcTaskName; + _aTasks[n].uxCurrentPriority = uxCurrentPriority; + _aTasks[n].pxStack = pxStack; + _aTasks[n].uStackHighWaterMark = uStackHighWaterMark; + + SYSVIEW_SendTaskInfo(xHandle, pcTaskName,uxCurrentPriority, pxStack, uStackHighWaterMark); + +} + +/********************************************************************* +* +* SYSVIEW_UpdateTask() +* +* Function description +* Update a task in the internal list and record its information. +*/ +void SYSVIEW_UpdateTask(U32 xHandle, const char* pcTaskName, unsigned uxCurrentPriority, U32 pxStack, unsigned uStackHighWaterMark) { + unsigned n; + + if (memcmp(pcTaskName, "IDLE", 5) == 0) { + return; + } + + for (n = 0; n < SYSVIEW_FREERTOS_MAX_NOF_TASKS; n++) { + if (_aTasks[n].xHandle == xHandle) { + break; + } + } + if (n < SYSVIEW_FREERTOS_MAX_NOF_TASKS) { + _aTasks[n].pcTaskName = pcTaskName; + _aTasks[n].uxCurrentPriority = uxCurrentPriority; + _aTasks[n].pxStack = pxStack; + _aTasks[n].uStackHighWaterMark = uStackHighWaterMark; + + SYSVIEW_SendTaskInfo(xHandle, pcTaskName, uxCurrentPriority, pxStack, uStackHighWaterMark); + } else { + SYSVIEW_AddTask(xHandle, pcTaskName, uxCurrentPriority, pxStack, uStackHighWaterMark); + } +} + +/********************************************************************* +* +* SYSVIEW_DeleteTask() +* +* Function description +* Delete a task from the internal list. +*/ +void SYSVIEW_DeleteTask(U32 xHandle) { + unsigned n; + + for (n = 0; n < SYSVIEW_FREERTOS_MAX_NOF_TASKS; n++) { + if (_aTasks[n].xHandle == xHandle) { + break; + } + } + if (n == SYSVIEW_FREERTOS_MAX_NOF_TASKS) { + SEGGER_SYSVIEW_Warn("SYSTEMVIEW: Could not find task information. Cannot delete task."); + return; + } + + _aTasks[n].xHandle = 0; +} + +/********************************************************************* +* +* SYSVIEW_SendTaskInfo() +* +* Function description +* Record task information. +*/ +void SYSVIEW_SendTaskInfo(U32 TaskID, const char* sName, unsigned Prio, U32 StackBase, unsigned StackSize) { + SEGGER_SYSVIEW_TASKINFO TaskInfo; + + memset(&TaskInfo, 0, sizeof(TaskInfo)); // Fill all elements with 0 to allow extending the structure in future version without breaking the code + TaskInfo.TaskID = TaskID; + TaskInfo.sName = sName; + TaskInfo.Prio = Prio; + TaskInfo.StackBase = StackBase; + TaskInfo.StackSize = StackSize; + SEGGER_SYSVIEW_SendTaskInfo(&TaskInfo); +} + +/********************************************************************* +* +* SYSVIEW_RecordU32x4() +* +* Function description +* Record an event with 4 parameters +*/ +void SYSVIEW_RecordU32x4(unsigned Id, U32 Para0, U32 Para1, U32 Para2, U32 Para3) { + U8 aPacket[SEGGER_SYSVIEW_INFO_SIZE + 4 * SEGGER_SYSVIEW_QUANTA_U32]; + U8* pPayload; + // + pPayload = SEGGER_SYSVIEW_PREPARE_PACKET(aPacket); // Prepare the packet for SystemView + pPayload = SEGGER_SYSVIEW_EncodeU32(pPayload, Para0); // Add the first parameter to the packet + pPayload = SEGGER_SYSVIEW_EncodeU32(pPayload, Para1); // Add the second parameter to the packet + pPayload = SEGGER_SYSVIEW_EncodeU32(pPayload, Para2); // Add the third parameter to the packet + pPayload = SEGGER_SYSVIEW_EncodeU32(pPayload, Para3); // Add the fourth parameter to the packet + // + SEGGER_SYSVIEW_SendPacket(&aPacket[0], pPayload, Id); // Send the packet +} + +/********************************************************************* +* +* SYSVIEW_RecordU32x5() +* +* Function description +* Record an event with 5 parameters +*/ +void SYSVIEW_RecordU32x5(unsigned Id, U32 Para0, U32 Para1, U32 Para2, U32 Para3, U32 Para4) { + U8 aPacket[SEGGER_SYSVIEW_INFO_SIZE + 5 * SEGGER_SYSVIEW_QUANTA_U32]; + U8* pPayload; + // + pPayload = SEGGER_SYSVIEW_PREPARE_PACKET(aPacket); // Prepare the packet for SystemView + pPayload = SEGGER_SYSVIEW_EncodeU32(pPayload, Para0); // Add the first parameter to the packet + pPayload = SEGGER_SYSVIEW_EncodeU32(pPayload, Para1); // Add the second parameter to the packet + pPayload = SEGGER_SYSVIEW_EncodeU32(pPayload, Para2); // Add the third parameter to the packet + pPayload = SEGGER_SYSVIEW_EncodeU32(pPayload, Para3); // Add the fourth parameter to the packet + pPayload = SEGGER_SYSVIEW_EncodeU32(pPayload, Para4); // Add the fifth parameter to the packet + // + SEGGER_SYSVIEW_SendPacket(&aPacket[0], pPayload, Id); // Send the packet +} + +/********************************************************************* +* +* Public API structures +* +********************************************************************** +*/ +// Callbacks provided to SYSTEMVIEW by FreeRTOS +const SEGGER_SYSVIEW_OS_API SYSVIEW_X_OS_TraceAPI = { + _cbGetTime, + _cbSendTaskList, +}; + +/*************************** End of file ****************************/ diff --git a/components/app_trace/sys_view/Sample/OS/SEGGER_SYSVIEW_FreeRTOS.h b/components/app_trace/sys_view/Sample/OS/SEGGER_SYSVIEW_FreeRTOS.h new file mode 100644 index 0000000000..6d4f876238 --- /dev/null +++ b/components/app_trace/sys_view/Sample/OS/SEGGER_SYSVIEW_FreeRTOS.h @@ -0,0 +1,335 @@ +/********************************************************************* +* SEGGER Microcontroller GmbH & Co. KG * +* The Embedded Experts * +********************************************************************** +* * +* (c) 2015 - 2017 SEGGER Microcontroller GmbH & Co. KG * +* * +* www.segger.com Support: support@segger.com * +* * +********************************************************************** +* * +* SEGGER SystemView * Real-time application analysis * +* * +********************************************************************** +* * +* All rights reserved. * +* * +* SEGGER strongly recommends to not make any changes * +* to or modify the source code of this software in order to stay * +* compatible with the RTT protocol and J-Link. * +* * +* Redistribution and use in source and binary forms, with or * +* without modification, are permitted provided that the following * +* conditions are met: * +* * +* o Redistributions of source code must retain the above copyright * +* notice, this list of conditions and the following disclaimer. * +* * +* o Redistributions in binary form must reproduce the above * +* copyright notice, this list of conditions and the following * +* disclaimer in the documentation and/or other materials provided * +* with the distribution. * +* * +* o Neither the name of SEGGER Microcontroller GmbH & Co. KG * +* nor the names of its contributors may be used to endorse or * +* promote products derived from this software without specific * +* prior written permission. * +* * +* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * +* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * +* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * +* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * +* DISCLAIMED. IN NO EVENT SHALL SEGGER Microcontroller BE LIABLE FOR * +* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * +* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * +* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * +* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * +* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * +* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * +* DAMAGE. * +* * +********************************************************************** +* * +* SystemView version: V2.42 * +* * +********************************************************************** +-------------------------- END-OF-HEADER ----------------------------- + +File : SEGGER_SYSVIEW_FreeRTOS.h +Purpose : Interface between FreeRTOS and SystemView. +Revision: $Rev: 3734 $ + +Notes: + (1) Include this file at the end of FreeRTOSConfig.h +*/ + +#ifndef SYSVIEW_FREERTOS_H +#define SYSVIEW_FREERTOS_H + +#include "SEGGER_SYSVIEW.h" + +/********************************************************************* +* +* Defines, configurable +* +********************************************************************** +*/ +#ifndef portSTACK_GROWTH + #define portSTACK_GROWTH ( -1 ) +#endif + +#define SYSVIEW_FREERTOS_MAX_NOF_TASKS 16 + +/********************************************************************* +* +* Defines, fixed +* +********************************************************************** +*/ + +// for dual-core targets we use event ID to keep core ID bit (0 or 1) +// 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 +// this reduces supported ID range to [0..63] (for 1 byte IDs) plus [128..16383] (for 2 bytes IDs) +// so original continuous event IDs range is split into two sub-ranges for 1-bytes IDs and 2-bytes ones + +// events which use apiFastID_OFFSET will have 1 byte ID, +// so for the sake of bandwidth economy events which are generated more frequently should use this ID offset +// currently all used events fall into this range +#define apiFastID_OFFSET (32u) + +#define apiID_VTASKDELETE (1u) +#define apiID_VTASKDELAY (2u) +#define apiID_VTASKDELAYUNTIL (3u) +#define apiID_VTASKSUSPEND (4u) +#define apiID_ULTASKNOTIFYTAKE (5u) +#define apiID_VTASKNOTIFYGIVEFROMISR (6u) +#define apiID_VTASKPRIORITYINHERIT (7u) +#define apiID_VTASKRESUME (8u) +#define apiID_VTASKSTEPTICK (9u) +#define apiID_XTASKPRIORITYDISINHERIT (10u) +#define apiID_XTASKRESUMEFROMISR (11u) +#define apiID_XTASKGENERICNOTIFY (12u) +#define apiID_XTASKGENERICNOTIFYFROMISR (13u) +#define apiID_XTASKNOTIFYWAIT (14u) +#define apiID_XQUEUEGENERICCREATE (15u) +#define apiID_VQUEUEDELETE (16u) +#define apiID_XQUEUEGENERICRECEIVE (17u) +#define apiID_XQUEUEPEEKFROMISR (18u) +#define apiID_XQUEUERECEIVEFROMISR (19u) +#define apiID_VQUEUEADDTOREGISTRY (20u) +#define apiID_XQUEUEGENERICSEND (21u) +#define apiID_XQUEUEGENERICSENDFROMISR (22u) +#define apiID_VTASKPRIORITYSET (23u) +#define apiID_UXTASKPRIORITYGETFROMISR (24u) +#define apiID_XTASKGETTICKCOUNTFROMISR (25u) +#define apiID_XEVENTGROUPCLEARBITSFROMISR (26u) +#define apiID_XEVENTGROUPSETBITSFROMISR (27u) +#define apiID_XEVENTGROUPGETBITSFROMISR (28u) +#define apiID_XQUEUEGIVEFROMISR (29u) +#define apiID_XQUEUEISQUEUEEMPTYFROMISR (30u) +#define apiID_XQUEUEISQUEUEFULLFROMISR (31u) // the maximum allowed apiID for the first ID range + +// events which use apiSlowID_OFFSET will have 2-bytes ID +#define apiSlowID_OFFSET (127u) + +#define apiID_VTASKALLOCATEMPUREGIONS (1u) +#define apiID_UXTASKPRIORITYGET (2u) +#define apiID_ETASKGETSTATE (3u) +#define apiID_VTASKSTARTSCHEDULER (4u) +#define apiID_VTASKENDSCHEDULER (5u) +#define apiID_VTASKSUSPENDALL (6u) +#define apiID_XTASKRESUMEALL (7u) +#define apiID_XTASKGETTICKCOUNT (8u) +#define apiID_UXTASKGETNUMBEROFTASKS (9u) +#define apiID_PCTASKGETTASKNAME (10u) +#define apiID_UXTASKGETSTACKHIGHWATERMARK (11u) +#define apiID_VTASKSETAPPLICATIONTASKTAG (12u) +#define apiID_XTASKGETAPPLICATIONTASKTAG (13u) +#define apiID_VTASKSETTHREADLOCALSTORAGEPOINTER (14u) +#define apiID_PVTASKGETTHREADLOCALSTORAGEPOINTER (15u) +#define apiID_XTASKCALLAPPLICATIONTASKHOOK (16u) +#define apiID_XTASKGETIDLETASKHANDLE (17u) +#define apiID_UXTASKGETSYSTEMSTATE (18u) +#define apiID_VTASKLIST (19u) +#define apiID_VTASKGETRUNTIMESTATS (20u) +#define apiID_XTASKNOTIFYSTATECLEAR (21u) +#define apiID_XTASKGETCURRENTTASKHANDLE (22u) +#define apiID_VTASKSETTIMEOUTSTATE (23u) +#define apiID_XTASKCHECKFORTIMEOUT (24u) +#define apiID_VTASKMISSEDYIELD (25u) +#define apiID_XTASKGETSCHEDULERSTATE (26u) +#define apiID_XTASKGENERICCREATE (27u) +#define apiID_UXTASKGETTASKNUMBER (28u) +#define apiID_VTASKSETTASKNUMBER (29u) +#define apiID_ETASKCONFIRMSLEEPMODESTATUS (30u) +#define apiID_XTIMERCREATE (31u) +#define apiID_PVTIMERGETTIMERID (32u) +#define apiID_VTIMERSETTIMERID (33u) +#define apiID_XTIMERISTIMERACTIVE (34u) +#define apiID_XTIMERGETTIMERDAEMONTASKHANDLE (35u) +#define apiID_XTIMERPENDFUNCTIONCALLFROMISR (36u) +#define apiID_XTIMERPENDFUNCTIONCALL (37u) +#define apiID_PCTIMERGETTIMERNAME (38u) +#define apiID_XTIMERCREATETIMERTASK (39u) +#define apiID_XTIMERGENERICCOMMAND (40u) +#define apiID_UXQUEUEMESSAGESWAITING (41u) +#define apiID_UXQUEUESPACESAVAILABLE (42u) +#define apiID_UXQUEUEMESSAGESWAITINGFROMISR (43u) +#define apiID_XQUEUEALTGENERICSEND (44u) +#define apiID_XQUEUEALTGENERICRECEIVE (45u) +#define apiID_XQUEUECRSENDFROMISR (46u) +#define apiID_XQUEUECRRECEIVEFROMISR (47u) +#define apiID_XQUEUECRSEND (48u) +#define apiID_XQUEUECRRECEIVE (49u) +#define apiID_XQUEUECREATEMUTEX (50u) +#define apiID_XQUEUECREATECOUNTINGSEMAPHORE (51u) +#define apiID_XQUEUEGETMUTEXHOLDER (52u) +#define apiID_XQUEUETAKEMUTEXRECURSIVE (53u) +#define apiID_XQUEUEGIVEMUTEXRECURSIVE (54u) +#define apiID_VQUEUEUNREGISTERQUEUE (55u) +#define apiID_XQUEUECREATESET (56u) +#define apiID_XQUEUEADDTOSET (57u) +#define apiID_XQUEUEREMOVEFROMSET (58u) +#define apiID_XQUEUESELECTFROMSET (59u) +#define apiID_XQUEUESELECTFROMSETFROMISR (60u) +#define apiID_XQUEUEGENERICRESET (61u) +#define apiID_VLISTINITIALISE (62u) +#define apiID_VLISTINITIALISEITEM (63u) +#define apiID_VLISTINSERT (64u) +#define apiID_VLISTINSERTEND (65u) +#define apiID_UXLISTREMOVE (66u) +#define apiID_XEVENTGROUPCREATE (67u) +#define apiID_XEVENTGROUPWAITBITS (68u) +#define apiID_XEVENTGROUPCLEARBITS (69u) +#define apiID_XEVENTGROUPSETBITS (70u) +#define apiID_XEVENTGROUPSYNC (71u) +#define apiID_VEVENTGROUPDELETE (72u) +#define apiID_UXEVENTGROUPGETNUMBER (73u) + +#define traceTASK_NOTIFY_TAKE() SEGGER_SYSVIEW_RecordU32x2(apiFastID_OFFSET + apiID_ULTASKNOTIFYTAKE, xClearCountOnExit, xTicksToWait) +#define traceTASK_DELAY() SEGGER_SYSVIEW_RecordU32(apiFastID_OFFSET + apiID_VTASKDELAY, xTicksToDelay) +#define traceTASK_DELAY_UNTIL() SEGGER_SYSVIEW_RecordVoid(apiFastID_OFFSET + apiID_VTASKDELAYUNTIL) +#define traceTASK_DELETE( pxTCB ) if (pxTCB != NULL) { \ + SEGGER_SYSVIEW_RecordU32(apiFastID_OFFSET + apiID_VTASKDELETE, \ + SEGGER_SYSVIEW_ShrinkId((U32)pxTCB)); \ + SYSVIEW_DeleteTask((U32)pxTCB); \ + } +#define traceTASK_NOTIFY_GIVE_FROM_ISR() SEGGER_SYSVIEW_RecordU32x2(apiFastID_OFFSET + apiID_VTASKNOTIFYGIVEFROMISR, SEGGER_SYSVIEW_ShrinkId((U32)pxTCB), (U32)pxHigherPriorityTaskWoken) +#define traceTASK_PRIORITY_INHERIT( pxTCB, uxPriority ) SEGGER_SYSVIEW_RecordU32(apiFastID_OFFSET + apiID_VTASKPRIORITYINHERIT, (U32)pxMutexHolder) +#define traceTASK_RESUME( pxTCB ) SEGGER_SYSVIEW_RecordU32(apiFastID_OFFSET + apiID_VTASKRESUME, SEGGER_SYSVIEW_ShrinkId((U32)pxTCB)) +#define traceINCREASE_TICK_COUNT( xTicksToJump ) SEGGER_SYSVIEW_RecordU32(apiFastID_OFFSET + apiID_VTASKSTEPTICK, xTicksToJump) +#define traceTASK_SUSPEND( pxTCB ) SEGGER_SYSVIEW_RecordU32(apiFastID_OFFSET + apiID_VTASKSUSPEND, SEGGER_SYSVIEW_ShrinkId((U32)pxTCB)) +#define traceTASK_PRIORITY_DISINHERIT( pxTCB, uxBasePriority ) SEGGER_SYSVIEW_RecordU32(apiFastID_OFFSET + apiID_XTASKPRIORITYDISINHERIT, (U32)pxMutexHolder) +#define traceTASK_RESUME_FROM_ISR( pxTCB ) SEGGER_SYSVIEW_RecordU32(apiFastID_OFFSET + apiID_XTASKRESUMEFROMISR, SEGGER_SYSVIEW_ShrinkId((U32)pxTCB)) +#define traceTASK_NOTIFY() SYSVIEW_RecordU32x4(apiFastID_OFFSET + apiID_XTASKGENERICNOTIFY, SEGGER_SYSVIEW_ShrinkId((U32)pxTCB), ulValue, eAction, (U32)pulPreviousNotificationValue) +#define traceTASK_NOTIFY_FROM_ISR() SYSVIEW_RecordU32x5(apiFastID_OFFSET + apiID_XTASKGENERICNOTIFYFROMISR, SEGGER_SYSVIEW_ShrinkId((U32)pxTCB), ulValue, eAction, (U32)pulPreviousNotificationValue, (U32)pxHigherPriorityTaskWoken) +#define traceTASK_NOTIFY_WAIT() SYSVIEW_RecordU32x4(apiFastID_OFFSET + apiID_XTASKNOTIFYWAIT, ulBitsToClearOnEntry, ulBitsToClearOnExit, (U32)pulNotificationValue, xTicksToWait) + +#define traceQUEUE_CREATE( pxNewQueue ) SEGGER_SYSVIEW_RecordU32x3(apiFastID_OFFSET + apiID_XQUEUEGENERICCREATE, uxQueueLength, uxItemSize, ucQueueType) +#define traceQUEUE_DELETE( pxQueue ) SEGGER_SYSVIEW_RecordU32(apiFastID_OFFSET + apiID_VQUEUEDELETE, SEGGER_SYSVIEW_ShrinkId((U32)pxQueue)) +#define traceQUEUE_PEEK( pxQueue ) SYSVIEW_RecordU32x4(apiFastID_OFFSET + apiID_XQUEUEGENERICRECEIVE, SEGGER_SYSVIEW_ShrinkId((U32)pxQueue), SEGGER_SYSVIEW_ShrinkId((U32)pvBuffer), xTicksToWait, xJustPeeking) +#define traceQUEUE_PEEK_FROM_ISR( pxQueue ) SEGGER_SYSVIEW_RecordU32x2(apiFastID_OFFSET + apiID_XQUEUEPEEKFROMISR, SEGGER_SYSVIEW_ShrinkId((U32)pxQueue), SEGGER_SYSVIEW_ShrinkId((U32)pvBuffer)) +#define traceQUEUE_PEEK_FROM_ISR_FAILED( pxQueue ) SEGGER_SYSVIEW_RecordU32x2(apiFastID_OFFSET + apiID_XQUEUEPEEKFROMISR, SEGGER_SYSVIEW_ShrinkId((U32)pxQueue), SEGGER_SYSVIEW_ShrinkId((U32)pvBuffer)) +#define traceQUEUE_RECEIVE( pxQueue ) SYSVIEW_RecordU32x4(apiFastID_OFFSET + apiID_XQUEUEGENERICRECEIVE, SEGGER_SYSVIEW_ShrinkId((U32)pxQueue), SEGGER_SYSVIEW_ShrinkId((U32)pvBuffer), xTicksToWait, xJustPeeking) +#define traceQUEUE_RECEIVE_FAILED( pxQueue ) SYSVIEW_RecordU32x4(apiFastID_OFFSET + apiID_XQUEUEGENERICRECEIVE, SEGGER_SYSVIEW_ShrinkId((U32)pxQueue), SEGGER_SYSVIEW_ShrinkId((U32)pvBuffer), xTicksToWait, xJustPeeking) +#define traceQUEUE_RECEIVE_FROM_ISR( pxQueue ) SEGGER_SYSVIEW_RecordU32x3(apiFastID_OFFSET + apiID_XQUEUERECEIVEFROMISR, SEGGER_SYSVIEW_ShrinkId((U32)pxQueue), SEGGER_SYSVIEW_ShrinkId((U32)pvBuffer), (U32)pxHigherPriorityTaskWoken) +#define traceQUEUE_RECEIVE_FROM_ISR_FAILED( pxQueue ) SEGGER_SYSVIEW_RecordU32x3(apiFastID_OFFSET + apiID_XQUEUERECEIVEFROMISR, SEGGER_SYSVIEW_ShrinkId((U32)pxQueue), SEGGER_SYSVIEW_ShrinkId((U32)pvBuffer), (U32)pxHigherPriorityTaskWoken) +#define traceQUEUE_REGISTRY_ADD( xQueue, pcQueueName ) SEGGER_SYSVIEW_RecordU32x2(apiFastID_OFFSET + apiID_VQUEUEADDTOREGISTRY, SEGGER_SYSVIEW_ShrinkId((U32)xQueue), (U32)pcQueueName) +#if ( configUSE_QUEUE_SETS != 1 ) + #define traceQUEUE_SEND( pxQueue ) SYSVIEW_RecordU32x4(apiFastID_OFFSET + apiID_XQUEUEGENERICSEND, SEGGER_SYSVIEW_ShrinkId((U32)pxQueue), (U32)pvItemToQueue, xTicksToWait, xCopyPosition) +#else + #define traceQUEUE_SEND( pxQueue ) SYSVIEW_RecordU32x4(apiFastID_OFFSET + apiID_XQUEUEGENERICSEND, SEGGER_SYSVIEW_ShrinkId((U32)pxQueue), 0, 0, xCopyPosition) +#endif +#define traceQUEUE_SEND_FAILED( pxQueue ) SYSVIEW_RecordU32x4(apiFastID_OFFSET + apiID_XQUEUEGENERICSEND, SEGGER_SYSVIEW_ShrinkId((U32)pxQueue), (U32)pvItemToQueue, xTicksToWait, xCopyPosition) +#define traceQUEUE_SEND_FROM_ISR( pxQueue ) SEGGER_SYSVIEW_RecordU32x2(apiFastID_OFFSET + apiID_XQUEUEGENERICSENDFROMISR, SEGGER_SYSVIEW_ShrinkId((U32)pxQueue), (U32)pxHigherPriorityTaskWoken) +#define traceQUEUE_SEND_FROM_ISR_FAILED( pxQueue ) SEGGER_SYSVIEW_RecordU32x2(apiFastID_OFFSET + apiID_XQUEUEGENERICSENDFROMISR, SEGGER_SYSVIEW_ShrinkId((U32)pxQueue), (U32)pxHigherPriorityTaskWoken) + +#if( portSTACK_GROWTH < 0 ) +#define traceTASK_CREATE(pxNewTCB) if (pxNewTCB != NULL) { \ + SEGGER_SYSVIEW_OnTaskCreate((U32)pxNewTCB); \ + SYSVIEW_AddTask((U32)pxNewTCB, \ + &(pxNewTCB->pcTaskName[0]), \ + pxNewTCB->uxPriority, \ + (U32)pxNewTCB->pxStack, \ + ((U32)pxNewTCB->pxTopOfStack - (U32)pxNewTCB->pxStack) \ + ); \ + } +#else +#define traceTASK_CREATE(pxNewTCB) if (pxNewTCB != NULL) { \ + SEGGER_SYSVIEW_OnTaskCreate((U32)pxNewTCB); \ + SYSVIEW_AddTask((U32)pxNewTCB, \ + &(pxNewTCB->pcTaskName[0]), \ + pxNewTCB->uxPriority, \ + (U32)pxNewTCB->pxStack, \ + (U32)(pxNewTCB->pxStack-pxNewTCB->pxTopOfStack) \ + ); \ + } +#endif +#define traceTASK_PRIORITY_SET(pxTask, uxNewPriority) { \ + SEGGER_SYSVIEW_RecordU32x2(apiFastID_OFFSET+apiID_VTASKPRIORITYSET, \ + SEGGER_SYSVIEW_ShrinkId((U32)pxTCB), \ + uxNewPriority \ + ); \ + SYSVIEW_UpdateTask((U32)pxTask, \ + &(pxTask->pcTaskName[0]), \ + uxNewPriority, \ + (U32)pxTask->pxStack, \ + 0 \ + ); \ + } +// +// Define INCLUDE_xTaskGetIdleTaskHandle as 1 in FreeRTOSConfig.h to allow identification of Idle state. +// +#if ( INCLUDE_xTaskGetIdleTaskHandle == 1 ) + #define traceTASK_SWITCHED_IN() if(prvGetTCBFromHandle(NULL) == xTaskGetIdleTaskHandle()) { \ + SEGGER_SYSVIEW_OnIdle(); \ + } else { \ + SEGGER_SYSVIEW_OnTaskStartExec((U32)pxCurrentTCB[xPortGetCoreID()]); \ + } +#else + #define traceTASK_SWITCHED_IN() { \ + if (memcmp(pxCurrentTCB[xPortGetCoreID()]->pcTaskName, "IDLE", 5) != 0) { \ + SEGGER_SYSVIEW_OnTaskStartExec((U32)pxCurrentTCB[xPortGetCoreID()]); \ + } else { \ + SEGGER_SYSVIEW_OnIdle(); \ + } \ + } +#endif + +#define traceMOVED_TASK_TO_READY_STATE(pxTCB) SEGGER_SYSVIEW_OnTaskStartReady((U32)pxTCB) +#define traceREADDED_TASK_TO_READY_STATE(pxTCB) + +#define traceMOVED_TASK_TO_DELAYED_LIST() SEGGER_SYSVIEW_OnTaskStopReady((U32)pxCurrentTCB[xPortGetCoreID()], (1u << 2)) +#define traceMOVED_TASK_TO_OVERFLOW_DELAYED_LIST() SEGGER_SYSVIEW_OnTaskStopReady((U32)pxCurrentTCB[xPortGetCoreID()], (1u << 2)) +#define traceMOVED_TASK_TO_SUSPENDED_LIST(pxTCB) SEGGER_SYSVIEW_OnTaskStopReady((U32)pxTCB, ((3u << 3) | 3)) + +#define traceISR_EXIT_TO_SCHEDULER() SEGGER_SYSVIEW_RecordExitISRToScheduler() +#define traceISR_EXIT() SEGGER_SYSVIEW_RecordExitISR() +#define traceISR_ENTER(_n_) SEGGER_SYSVIEW_RecordEnterISR(_n_) + +/********************************************************************* +* +* API functions +* +********************************************************************** +*/ +#ifdef __cplusplus +extern "C" { +#endif +void SYSVIEW_AddTask (U32 xHandle, const char* pcTaskName, unsigned uxCurrentPriority, U32 pxStack, unsigned uStackHighWaterMark); +void SYSVIEW_UpdateTask (U32 xHandle, const char* pcTaskName, unsigned uxCurrentPriority, U32 pxStack, unsigned uStackHighWaterMark); +void SYSVIEW_DeleteTask (U32 xHandle); +void SYSVIEW_SendTaskInfo (U32 TaskID, const char* sName, unsigned Prio, U32 StackBase, unsigned StackSize); +void SYSVIEW_RecordU32x4 (unsigned Id, U32 Para0, U32 Para1, U32 Para2, U32 Para3); +void SYSVIEW_RecordU32x5 (unsigned Id, U32 Para0, U32 Para1, U32 Para2, U32 Para3, U32 Para4); + +#ifdef __cplusplus +} +#endif + +#endif + +/*************************** End of file ****************************/ diff --git a/components/app_trace/sys_view/esp32/SEGGER_RTT_esp32.c b/components/app_trace/sys_view/esp32/SEGGER_RTT_esp32.c new file mode 100644 index 0000000000..795af78da1 --- /dev/null +++ b/components/app_trace/sys_view/esp32/SEGGER_RTT_esp32.c @@ -0,0 +1,222 @@ +// Copyright 2017 Espressif Systems (Shanghai) PTE LTD +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at + +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "string.h" +#include "freertos/FreeRTOS.h" +#include "SEGGER_RTT.h" +#include "SEGGER_SYSVIEW.h" + +#include "rom/ets_sys.h" +#include "esp_app_trace.h" + +#define LOG_LOCAL_LEVEL ESP_LOG_ERROR +#include "esp_log.h" +const static char *TAG = "segger_rtt"; + +#define SYSVIEW_EVENTS_BUF_SZ 255U + +#if SYSVIEW_RTT_MAX_DATA_RATE > 0 +#include "SEGGER_SYSVIEW_Conf.h" +#if CONFIG_FREERTOS_UNICORE == 0 +#include "driver/timer.h" +#define SYSVIEW_TIMESTAMP_FREQ (TIMER_BASE_CLK/2) +#else +#define SYSVIEW_TIMESTAMP_FREQ (XT_CLOCK_FREQ) +#endif +#endif + +#define SEGGER_HOST_WAIT_TMO 500 //us +#define SEGGER_STOP_WAIT_TMO 1000000 //us + +static uint8_t s_events_buf[SYSVIEW_EVENTS_BUF_SZ]; +static uint16_t s_events_buf_filled; + +/********************************************************************* +* +* Public code +* +********************************************************************** +*/ + +/********************************************************************* +* +* SEGGER_RTT_ESP32_FlushNoLock() +* +* Function description +* Flushes buffered events. +* +* Parameters +* min_sz Threshold for flushing data. If current filling level is above this value, data will be flushed. TRAX destinations only. +* tmo Timeout for operation (in us). Use ESP_APPTRACE_TMO_INFINITE to wait indefinetly. +* +* Return value +* None. +*/ +void SEGGER_RTT_ESP32_FlushNoLock(unsigned long min_sz, unsigned long tmo) +{ + esp_err_t res = esp_apptrace_write(ESP_APPTRACE_DEST_TRAX, 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); + if (res != ESP_OK) { + ESP_LOGE(TAG, "Failed to flush apptrace data (%d)!\n", res); + } + s_events_buf_filled = 0; +} + +/********************************************************************* +* +* SEGGER_RTT_ReadNoLock() +* +* Function description +* Reads characters from SEGGER real-time-terminal control block +* which have been previously stored by the host. +* Do not lock against interrupts and multiple access. +* +* Parameters +* BufferIndex Index of Down-buffer to be used (e.g. 0 for "Terminal"). +* pBuffer Pointer to buffer provided by target application, to copy characters from RTT-down-buffer to. +* BufferSize Size of the target application buffer. +* +* Return value +* Number of bytes that have been read. +*/ +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); + if (res != ESP_OK) { + return 0; + } + return size; +} + +/********************************************************************* +* +* SEGGER_RTT_WriteSkipNoLock +* +* Function description +* Stores a specified number of characters in SEGGER RTT +* control block which is then read by the host. +* SEGGER_RTT_WriteSkipNoLock does not lock the application and +* skips all data, if the data does not fit into the buffer. +* +* Parameters +* BufferIndex Index of "Up"-buffer to be used (e.g. 0 for "Terminal"). +* pBuffer Pointer to character array. Does not need to point to a \0 terminated string. +* NumBytes Number of bytes to be stored in the SEGGER RTT control block. +* +* Return value +* Number of bytes which have been stored in the "Up"-buffer. +* +* Notes +* (1) If there is not enough space in the "Up"-buffer, all data is dropped. +* (2) For performance reasons this function does not call Init() +* and may only be called after RTT has been initialized. +* Either by calling SEGGER_RTT_Init() or calling another RTT API function first. +*/ +unsigned SEGGER_RTT_WriteSkipNoLock(unsigned BufferIndex, const void* pBuffer, unsigned NumBytes) { + uint8_t *pbuf = (uint8_t *)pBuffer; + uint8_t event_id = *pbuf; + + if (NumBytes > SYSVIEW_EVENTS_BUF_SZ) { + ESP_LOGE(TAG, "Too large event %d bytes!", NumBytes); + return 0; + } + if (xPortGetCoreID()) { // 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 + // this reduces supported ID range to [0..63] (for 1 byte IDs) plus [128..16383] (for 2 bytes IDs) + if (*pbuf & 0x80) { // 2 bytes ID + *(pbuf + 1) |= (1 << 6); + } else if (NumBytes != 10 || *pbuf != 0) { // ignore sync sequence + *pbuf |= (1 << 6); + } + } + 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); + if (res != ESP_OK) { + return 0; // skip current data buffer only, accumulated events are kept + } + s_events_buf_filled = 0; + } + memcpy(&s_events_buf[s_events_buf_filled], pBuffer, NumBytes); + s_events_buf_filled += NumBytes; + if (event_id == SYSVIEW_EVTID_TRACE_STOP) { + SEGGER_RTT_ESP32_FlushNoLock(0, SEGGER_STOP_WAIT_TMO); + } + return NumBytes; +} + +/********************************************************************* +* +* SEGGER_RTT_ConfigUpBuffer +* +* Function description +* Run-time configuration of a specific up-buffer (T->H). +* Buffer to be configured is specified by index. +* This includes: Buffer address, size, name, flags, ... +* +* Parameters +* BufferIndex Index of the buffer to configure. +* sName Pointer to a constant name string. +* pBuffer Pointer to a buffer to be used. +* BufferSize Size of the buffer. +* Flags Operating modes. Define behavior if buffer is full (not enough space for entire message). +* +* Return value +* >= 0 - O.K. +* < 0 - Error +* +* Additional information +* Buffer 0 is configured on compile-time. +* May only be called once per buffer. +* Buffer name and flags can be reconfigured using the appropriate functions. +*/ +int SEGGER_RTT_ConfigUpBuffer(unsigned BufferIndex, const char* sName, void* pBuffer, unsigned BufferSize, unsigned Flags) { + s_events_buf_filled = 0; + return 0; +} + +/********************************************************************* +* +* SEGGER_RTT_ConfigDownBuffer +* +* Function description +* Run-time configuration of a specific down-buffer (H->T). +* Buffer to be configured is specified by index. +* This includes: Buffer address, size, name, flags, ... +* +* Parameters +* BufferIndex Index of the buffer to configure. +* sName Pointer to a constant name string. +* pBuffer Pointer to a buffer to be used. +* BufferSize Size of the buffer. +* Flags Operating modes. Define behavior if buffer is full (not enough space for entire message). +* +* Return value +* >= 0 O.K. +* < 0 Error +* +* Additional information +* Buffer 0 is configured on compile-time. +* May only be called once per buffer. +* Buffer name and flags can be reconfigured using the appropriate functions. +*/ +int SEGGER_RTT_ConfigDownBuffer(unsigned BufferIndex, const char* sName, void* pBuffer, unsigned BufferSize, unsigned Flags) { + return 0; +} + +/*************************** End of file ****************************/ diff --git a/components/app_trace/test/component.mk b/components/app_trace/test/component.mk new file mode 100644 index 0000000000..5dd172bdb7 --- /dev/null +++ b/components/app_trace/test/component.mk @@ -0,0 +1,5 @@ +# +#Component Makefile +# + +COMPONENT_ADD_LDFLAGS = -Wl,--whole-archive -l$(COMPONENT_NAME) -Wl,--no-whole-archive diff --git a/components/esp32/test/test_trace.c b/components/app_trace/test/test_trace.c similarity index 78% rename from components/esp32/test/test_trace.c rename to components/app_trace/test/test_trace.c index 48e53adba8..e92b6ffc6a 100644 --- a/components/esp32/test/test_trace.c +++ b/components/app_trace/test/test_trace.c @@ -5,11 +5,13 @@ #include #include "unity.h" #include "driver/timer.h" +#include "soc/cpu.h" #include "freertos/FreeRTOS.h" #include "freertos/semphr.h" #include "freertos/task.h" #if CONFIG_ESP32_APPTRACE_ENABLE == 1 #include "esp_app_trace.h" +#include "esp_app_trace_util.h" #define ESP_APPTRACE_TEST_USE_PRINT_LOCK 0 #define ESP_APPTRACE_TEST_PRN_WRERR_MAX 5 @@ -57,8 +59,32 @@ const static char *TAG = "esp_apptrace_test"; #define ESP_APPTRACE_TEST_LOGV( format, ... ) ESP_APPTRACE_TEST_LOG_LEVEL(V, ESP_LOG_VERBOSE, format, ##__VA_ARGS__) #define ESP_APPTRACE_TEST_LOGO( format, ... ) ESP_APPTRACE_TEST_LOG_LEVEL(E, ESP_LOG_NONE, format, ##__VA_ARGS__) +static void esp_apptrace_test_timer_init(int timer_group, int timer_idx, uint32_t period) +{ + timer_config_t config; + uint64_t alarm_val = (period * (TIMER_BASE_CLK / 1000000UL)) / 2; + + config.alarm_en = 1; + config.auto_reload = 1; + config.counter_dir = TIMER_COUNT_UP; + config.divider = 1; + config.intr_type = TIMER_INTR_LEVEL; + config.counter_en = TIMER_PAUSE; + /*Configure timer*/ + timer_init(timer_group, timer_idx, &config); + /*Stop timer counter*/ + timer_pause(timer_group, timer_idx); + /*Load counter value */ + timer_set_counter_value(timer_group, timer_idx, 0x00000000ULL); + /*Set alarm value*/ + timer_set_alarm_value(timer_group, timer_idx, alarm_val); + /*Enable timer interrupt*/ + timer_enable_intr(timer_group, timer_idx); +} + +#if CONFIG_SYSVIEW_ENABLE == 0 #define ESP_APPTRACE_TEST_WRITE(_b_, _s_) esp_apptrace_write(ESP_APPTRACE_DEST_TRAX, _b_, _s_, ESP_APPTRACE_TMO_INFINITE) -#define ESP_APPTRACE_TEST_WRITE_FROM_ISR(_b_, _s_) esp_apptrace_write(ESP_APPTRACE_DEST_TRAX, _b_, _s_, 100UL) +#define ESP_APPTRACE_TEST_WRITE_FROM_ISR(_b_, _s_) esp_apptrace_write(ESP_APPTRACE_DEST_TRAX, _b_, _s_, 0UL) #define ESP_APPTRACE_TEST_WRITE_NOWAIT(_b_, _s_) esp_apptrace_write(ESP_APPTRACE_DEST_TRAX, _b_, _s_, 0) #define ESP_APPTRACE_TEST_CPUTICKS2US(_t_) ((_t_)/(XT_CLOCK_FREQ/1000000)) @@ -103,29 +129,6 @@ static SemaphoreHandle_t s_print_lock; static uint64_t esp_apptrace_test_ts_get(); -static void esp_apptrace_test_timer_init(int timer_group, int timer_idx, uint32_t period) -{ - timer_config_t config; - uint64_t alarm_val = (period * (TIMER_BASE_CLK / 1000000UL)) / 2; - - config.alarm_en = 1; - config.auto_reload = 1; - config.counter_dir = TIMER_COUNT_UP; - config.divider = 1; - config.intr_type = TIMER_INTR_LEVEL; - config.counter_en = TIMER_PAUSE; - /*Configure timer*/ - timer_init(timer_group, timer_idx, &config); - /*Stop timer counter*/ - timer_pause(timer_group, timer_idx); - /*Load counter value */ - timer_set_counter_value(timer_group, timer_idx, 0x00000000ULL); - /*Set alarm value*/ - timer_set_alarm_value(timer_group, timer_idx, alarm_val); - /*Enable timer interrupt*/ - timer_enable_intr(timer_group, timer_idx); -} - static void esp_apptrace_test_timer_isr(void *arg) { esp_apptrace_test_timer_arg_t *tim_arg = (esp_apptrace_test_timer_arg_t *)arg; @@ -309,13 +312,14 @@ static void esp_apptrace_test_task(void *p) uint32_t *ts = (uint32_t *)(arg->data.buf + sizeof(uint32_t)); *ts = (uint32_t)esp_apptrace_test_ts_get(); memset(arg->data.buf + 2 * sizeof(uint32_t), arg->data.wr_cnt & arg->data.mask, arg->data.buf_sz - 2 * sizeof(uint32_t)); + // ESP_APPTRACE_TEST_LOGD("%x:%x: Write chunk%d %d bytes, %x", xTaskGetCurrentTaskHandle(), *ts, arg->data.wr_cnt, arg->data.buf_sz, arg->data.wr_cnt & arg->data.mask); if (arg->nowait) { res = ESP_APPTRACE_TEST_WRITE_NOWAIT(arg->data.buf, arg->data.buf_sz); } else { res = ESP_APPTRACE_TEST_WRITE(arg->data.buf, arg->data.buf_sz); } if (res) { - if (arg->data.wr_err++ < ESP_APPTRACE_TEST_PRN_WRERR_MAX) { + if (1){//arg->data.wr_err++ < ESP_APPTRACE_TEST_PRN_WRERR_MAX) { ESP_APPTRACE_TEST_LOGE("%x: Failed to write trace %d %x!", xTaskGetCurrentTaskHandle(), res, arg->data.wr_cnt & arg->data.mask); if (arg->data.wr_err == ESP_APPTRACE_TEST_PRN_WRERR_MAX) { ESP_APPTRACE_TEST_LOGE("\n"); @@ -490,8 +494,9 @@ static void esp_apptrace_test(esp_apptrace_test_cfg_t *test_cfg) ESP_APPTRACE_TEST_LOGI("Created task %x", thnd); } xTaskCreatePinnedToCore(esp_apptrace_dummy_task, "dummy0", 2048, &dummy_task_arg[0], dummy_task_arg[0].prio, NULL, 0); +#if CONFIG_FREERTOS_UNICORE == 0 xTaskCreatePinnedToCore(esp_apptrace_dummy_task, "dummy1", 2048, &dummy_task_arg[0], dummy_task_arg[0].prio, NULL, 1); - +#endif for (int i = 0; i < test_cfg->tasks_num; i++) { //arg1.stop = 1; xSemaphoreTake(test_cfg->tasks[i].done, portMAX_DELAY); @@ -567,6 +572,7 @@ TEST_CASE("App trace test (1 crashed task)", "[trace][ignore]") esp_apptrace_test(&test_cfg); } +#if CONFIG_FREERTOS_UNICORE == 0 TEST_CASE("App trace test (2 tasks + 1 timer @ each core", "[trace][ignore]") { int ntask = 0; @@ -628,9 +634,9 @@ TEST_CASE("App trace test (2 tasks + 1 timer @ each core", "[trace][ignore]") s_test_tasks[ntask].timers_num = 0; s_test_tasks[ntask].timers = NULL; ntask++; - esp_apptrace_test(&test_cfg); } +#endif TEST_CASE("App trace test (1 task + 1 timer @ 1 core)", "[trace][ignore]") { @@ -661,6 +667,7 @@ TEST_CASE("App trace test (1 task + 1 timer @ 1 core)", "[trace][ignore]") esp_apptrace_test(&test_cfg); } +#if CONFIG_FREERTOS_UNICORE == 0 TEST_CASE("App trace test (2 tasks (nowait): 1 @ each core)", "[trace][ignore]") { esp_apptrace_test_cfg_t test_cfg = { @@ -722,6 +729,7 @@ TEST_CASE("App trace test (2 tasks: 1 @ each core)", "[trace][ignore]") esp_apptrace_test(&test_cfg); } +#endif TEST_CASE("App trace test (1 task)", "[trace][ignore]") { @@ -732,7 +740,7 @@ TEST_CASE("App trace test (1 task)", "[trace][ignore]") memset(s_test_tasks, 0, sizeof(s_test_tasks)); - s_test_tasks[0].core = 1; + s_test_tasks[0].core = 0; s_test_tasks[0].prio = 3; s_test_tasks[0].task_func = esp_apptrace_test_task; s_test_tasks[0].data.buf = s_bufs[0]; @@ -759,6 +767,7 @@ static int esp_logtrace_printf(const char *fmt, ...) typedef struct { SemaphoreHandle_t done; + uint32_t work_count; } esp_logtrace_task_t; static void esp_logtrace_task(void *p) @@ -793,7 +802,7 @@ static void esp_logtrace_task(void *p) vTaskDelete(NULL); } -TEST_CASE("Log trace test (1 task)", "[trace][ignore]") +TEST_CASE("Log trace test (2 tasks)", "[trace][ignore]") { TaskHandle_t thnd; @@ -806,7 +815,11 @@ TEST_CASE("Log trace test (1 task)", "[trace][ignore]") xTaskCreatePinnedToCore(esp_logtrace_task, "logtrace0", 2048, &arg1, 3, &thnd, 0); ESP_APPTRACE_TEST_LOGI("Created task %x", thnd); +#if CONFIG_FREERTOS_UNICORE == 0 xTaskCreatePinnedToCore(esp_logtrace_task, "logtrace1", 2048, &arg2, 3, &thnd, 1); +#else + xTaskCreatePinnedToCore(esp_logtrace_task, "logtrace1", 2048, &arg2, 3, &thnd, 0); +#endif ESP_APPTRACE_TEST_LOGI("Created task %x", thnd); xSemaphoreTake(arg1.done, portMAX_DELAY); @@ -814,4 +827,234 @@ TEST_CASE("Log trace test (1 task)", "[trace][ignore]") xSemaphoreTake(arg2.done, portMAX_DELAY); vSemaphoreDelete(arg2.done); } + +#else + +typedef struct { + int group; + int timer; + int flags; + uint32_t id; +} esp_sysviewtrace_timer_arg_t; + +typedef struct { + SemaphoreHandle_t done; + SemaphoreHandle_t *sync; + esp_sysviewtrace_timer_arg_t *timer; + uint32_t work_count; + uint32_t sleep_tmo; + uint32_t id; +} esp_sysviewtrace_task_arg_t; + +static void esp_sysview_test_timer_isr(void *arg) +{ + esp_sysviewtrace_timer_arg_t *tim_arg = (esp_sysviewtrace_timer_arg_t *)arg; + + //ESP_APPTRACE_TEST_LOGI("tim-%d: IRQ %d/%d\n", tim_arg->id, tim_arg->group, tim_arg->timer); + + if (tim_arg->group == 0) { + if (tim_arg->timer == 0) { + TIMERG0.int_clr_timers.t0 = 1; + TIMERG0.hw_timer[0].update = 1; + TIMERG0.hw_timer[0].config.alarm_en = 1; + } else { + TIMERG0.int_clr_timers.t1 = 1; + TIMERG0.hw_timer[1].update = 1; + TIMERG0.hw_timer[1].config.alarm_en = 1; + } + } + if (tim_arg->group == 1) { + if (tim_arg->timer == 0) { + TIMERG1.int_clr_timers.t0 = 1; + TIMERG1.hw_timer[0].update = 1; + TIMERG1.hw_timer[0].config.alarm_en = 1; + } else { + TIMERG1.int_clr_timers.t1 = 1; + TIMERG1.hw_timer[1].update = 1; + TIMERG1.hw_timer[1].config.alarm_en = 1; + } + } +} + +static void esp_sysviewtrace_test_task(void *p) +{ + esp_sysviewtrace_task_arg_t *arg = (esp_sysviewtrace_task_arg_t *) p; + volatile uint32_t tmp = 0; + timer_isr_handle_t inth; + + printf("%x: run sysview task\n", (uint32_t)xTaskGetCurrentTaskHandle()); + + if (arg->timer) { + esp_err_t res = timer_isr_register(arg->timer->group, arg->timer->timer, esp_sysview_test_timer_isr, arg->timer, arg->timer->flags, &inth); + if (res != ESP_OK) { + printf("%x: failed to register timer ISR\n", (uint32_t)xTaskGetCurrentTaskHandle()); + } + else { + res = timer_start(arg->timer->group, arg->timer->timer); + if (res != ESP_OK) { + printf("%x: failed to start timer\n", (uint32_t)xTaskGetCurrentTaskHandle()); + } + } + } + + int i = 0; + while (1) { + static uint32_t count; + printf("%d", arg->id); + if((++count % 80) == 0) + printf("\n"); + if (arg->sync) { + xSemaphoreTake(*arg->sync, portMAX_DELAY); + } + for (uint32_t k = 0; k < arg->work_count; k++) { + tmp++; + } + vTaskDelay(arg->sleep_tmo/portTICK_PERIOD_MS); + i++; + if (arg->sync) { + xSemaphoreGive(*arg->sync); + } + } + ESP_APPTRACE_TEST_LOGI("%x: finished", xTaskGetCurrentTaskHandle()); + + xSemaphoreGive(arg->done); + vTaskDelay(1); + vTaskDelete(NULL); +} + +TEST_CASE("SysView trace test 1", "[trace][ignore]") +{ + TaskHandle_t thnd; + + esp_sysviewtrace_timer_arg_t tim_arg1 = { + .group = TIMER_GROUP_1, + .timer = TIMER_1, + .flags = ESP_INTR_FLAG_SHARED, + .id = 0, + }; + esp_sysviewtrace_task_arg_t arg1 = { + .done = xSemaphoreCreateBinary(), + .sync = NULL, + .work_count = 10000, + .sleep_tmo = 1, + .timer = &tim_arg1, + .id = 0, + }; + esp_sysviewtrace_timer_arg_t tim_arg2 = { + .group = TIMER_GROUP_1, + .timer = TIMER_0, + .flags = 0, + .id = 1, + }; + esp_sysviewtrace_task_arg_t arg2 = { + .done = xSemaphoreCreateBinary(), + .sync = NULL, + .work_count = 10000, + .sleep_tmo = 1, + .timer = &tim_arg2, + .id = 1, + }; + + esp_apptrace_test_timer_init(TIMER_GROUP_1, TIMER_1, 500); + esp_apptrace_test_timer_init(TIMER_GROUP_1, TIMER_0, 100); + + xTaskCreatePinnedToCore(esp_sysviewtrace_test_task, "svtrace0", 2048, &arg1, 3, &thnd, 0); + ESP_APPTRACE_TEST_LOGI("Created task %x", thnd); +#if CONFIG_FREERTOS_UNICORE == 0 + xTaskCreatePinnedToCore(esp_sysviewtrace_test_task, "svtrace1", 2048, &arg2, 5, &thnd, 1); +#else + xTaskCreatePinnedToCore(esp_sysviewtrace_test_task, "svtrace1", 2048, &arg2, 5, &thnd, 0); +#endif + ESP_APPTRACE_TEST_LOGI("Created task %x", thnd); + + xSemaphoreTake(arg1.done, portMAX_DELAY); + vSemaphoreDelete(arg1.done); + xSemaphoreTake(arg2.done, portMAX_DELAY); + vSemaphoreDelete(arg2.done); +} + +TEST_CASE("SysView trace test 2", "[trace][ignore]") +{ + TaskHandle_t thnd; + + esp_sysviewtrace_timer_arg_t tim_arg1 = { + .group = TIMER_GROUP_1, + .timer = TIMER_1, + .flags = ESP_INTR_FLAG_SHARED, + .id = 0, + }; + esp_sysviewtrace_task_arg_t arg1 = { + .done = xSemaphoreCreateBinary(), + .sync = NULL, + .work_count = 10000, + .sleep_tmo = 1, + .timer = &tim_arg1, + .id = 0, + }; + esp_sysviewtrace_timer_arg_t tim_arg2 = { + .group = TIMER_GROUP_1, + .timer = TIMER_0, + .flags = 0, + .id = 1, + }; + esp_sysviewtrace_task_arg_t arg2 = { + .done = xSemaphoreCreateBinary(), + .sync = NULL, + .work_count = 10000, + .sleep_tmo = 1, + .timer = &tim_arg2, + .id = 1, + }; + + SemaphoreHandle_t test_sync = xSemaphoreCreateBinary(); + xSemaphoreGive(test_sync); + esp_sysviewtrace_task_arg_t arg3 = { + .done = xSemaphoreCreateBinary(), + .sync = &test_sync, + .work_count = 1000, + .sleep_tmo = 1, + .timer = NULL, + .id = 2, + }; + esp_sysviewtrace_task_arg_t arg4 = { + .done = xSemaphoreCreateBinary(), + .sync = &test_sync, + .work_count = 10000, + .sleep_tmo = 1, + .timer = NULL, + .id = 3, + }; + + esp_apptrace_test_timer_init(TIMER_GROUP_1, TIMER_1, 500); + esp_apptrace_test_timer_init(TIMER_GROUP_1, TIMER_0, 100); + + xTaskCreatePinnedToCore(esp_sysviewtrace_test_task, "svtrace0", 2048, &arg1, 3, &thnd, 0); + printf("Created task %x\n", (uint32_t)thnd); +#if CONFIG_FREERTOS_UNICORE == 0 + xTaskCreatePinnedToCore(esp_sysviewtrace_test_task, "svtrace1", 2048, &arg2, 4, &thnd, 1); +#else + xTaskCreatePinnedToCore(esp_sysviewtrace_test_task, "svtrace1", 2048, &arg2, 4, &thnd, 0); +#endif + printf("Created task %x\n", (uint32_t)thnd); + + xTaskCreatePinnedToCore(esp_sysviewtrace_test_task, "svsync0", 2048, &arg3, 3, &thnd, 0); + printf("Created task %x\n", (uint32_t)thnd); +#if CONFIG_FREERTOS_UNICORE == 0 + xTaskCreatePinnedToCore(esp_sysviewtrace_test_task, "svsync1", 2048, &arg4, 5, &thnd, 1); +#else + xTaskCreatePinnedToCore(esp_sysviewtrace_test_task, "svsync1", 2048, &arg4, 5, &thnd, 0); +#endif + printf("Created task %x\n", (uint32_t)thnd); + + xSemaphoreTake(arg1.done, portMAX_DELAY); + vSemaphoreDelete(arg1.done); + xSemaphoreTake(arg2.done, portMAX_DELAY); + vSemaphoreDelete(arg2.done); + xSemaphoreTake(arg3.done, portMAX_DELAY); + vSemaphoreDelete(arg3.done); + xSemaphoreTake(arg4.done, portMAX_DELAY); + vSemaphoreDelete(arg4.done); + vSemaphoreDelete(test_sync); +} +#endif #endif diff --git a/components/esp32/Kconfig b/components/esp32/Kconfig index 3625ce59e0..0839226df3 100644 --- a/components/esp32/Kconfig +++ b/components/esp32/Kconfig @@ -104,45 +104,6 @@ config ESP32_CORE_DUMP_LOG_LEVEL help Config core dump module logging level (0-5). -choice ESP32_APPTRACE_DESTINATION - prompt "AppTrace: destination" - default ESP32_APPTRACE_DEST_NONE - help - Select destination for application trace: trace memory, uart or none (to disable). - -config ESP32_APPTRACE_DEST_TRAX - bool "Trace memory" - select ESP32_APPTRACE_ENABLE -config ESP32_APPTRACE_DEST_UART - bool "UART" - select ESP32_APPTRACE_ENABLE -config ESP32_APPTRACE_DEST_NONE - bool "None" -endchoice - -config ESP32_APPTRACE_ENABLE - bool - depends on !ESP32_TRAX - select MEMMAP_TRACEMEM - select MEMMAP_TRACEMEM_TWOBANKS - default F - help - Enables/disable application tracing module. - -config ESP32_APPTRACE_ONPANIC_HOST_FLUSH_TMO - int "AppTrace: Timeout for flushing last trace data to host on panic" - depends on ESP32_APPTRACE_ENABLE - default 4294967295 - help - Timeout for flushing last trace data to host in case of panic. In us. - -config ESP32_APPTRACE_ONPANIC_HOST_FLUSH_TRAX_THRESH - int "AppTrace: Threshold for flushing last trace data to host on panic" - depends on ESP32_APPTRACE_DEST_TRAX - default 50 - help - Threshold for flushing last trace data to host on panic. In percents of TRAX memory block length. - # Not implemented and/or needs new silicon rev to work config MEMMAP_SPISRAM bool "Use external SPI SRAM chip as main memory" diff --git a/components/esp32/cpu_start.c b/components/esp32/cpu_start.c index e70613619e..858036c677 100644 --- a/components/esp32/cpu_start.c +++ b/components/esp32/cpu_start.c @@ -188,7 +188,7 @@ void IRAM_ATTR call_start_cpu1() "wsr %0, vecbase\n" \ ::"r"(&_init_start)); - ets_set_appcpu_boot_addr(0); + ets_set_appcpu_boot_addr(0); cpu_configure_region_protection(); #if CONFIG_CONSOLE_UART_NONE @@ -257,6 +257,9 @@ void start_cpu0_default(void) if (err != ESP_OK) { ESP_EARLY_LOGE(TAG, "Failed to init apptrace module on CPU0 (%d)!", err); } +#endif +#if CONFIG_SYSVIEW_ENABLE + SEGGER_SYSVIEW_Conf(); #endif do_global_ctors(); #if CONFIG_INT_WDT diff --git a/components/esp32/dport_access.c b/components/esp32/dport_access.c index dbb956e820..2e7be5544c 100644 --- a/components/esp32/dport_access.c +++ b/components/esp32/dport_access.c @@ -188,9 +188,9 @@ static void dport_access_init_core1(void *arg) void esp_dport_access_int_init(void) { if (xPortGetCoreID() == 0) { - xTaskCreatePinnedToCore(&dport_access_init_core0, "dport0", 512, NULL, 5, NULL, 0); + xTaskCreatePinnedToCore(&dport_access_init_core0, "dport0", 2048, NULL, 5, NULL, 0); } else { - xTaskCreatePinnedToCore(&dport_access_init_core1, "dport1", 512, NULL, 5, NULL, 1); + xTaskCreatePinnedToCore(&dport_access_init_core1, "dport1", 2048, NULL, 5, NULL, 1); } } diff --git a/components/esp32/include/esp_intr_alloc.h b/components/esp32/include/esp_intr_alloc.h index 7195d07d87..63555c208f 100644 --- a/components/esp32/include/esp_intr_alloc.h +++ b/components/esp32/include/esp_intr_alloc.h @@ -77,6 +77,9 @@ extern "C" { /**@}*/ +// This is used to provide SystemView with positive IRQ IDs, otherwise sheduler events are not shown properly +#define ETS_INTERNAL_INTR_SOURCE_OFF (-ETS_INTERNAL_PROFILING_INTR_SOURCE) + typedef void (*intr_handler_t)(void *arg); @@ -221,7 +224,6 @@ int esp_intr_get_cpu(intr_handle_t handle); */ int esp_intr_get_intno(intr_handle_t handle); - /** * @brief Disable the interrupt associated with the handle * diff --git a/components/esp32/intr_alloc.c b/components/esp32/intr_alloc.c index 9686cc7eef..534354cdc5 100644 --- a/components/esp32/intr_alloc.c +++ b/components/esp32/intr_alloc.c @@ -24,6 +24,7 @@ #include "freertos/task.h" #include #include "esp_err.h" +//#define LOG_LOCAL_LEVEL ESP_LOG_VERBOSE #include "esp_log.h" #include "esp_intr.h" #include "esp_attr.h" @@ -33,7 +34,6 @@ static const char* TAG = "intr_alloc"; - #define ETS_INTERNAL_TIMER0_INTR_NO 6 #define ETS_INTERNAL_TIMER1_INTR_NO 15 #define ETS_INTERNAL_TIMER2_INTR_NO 16 @@ -74,7 +74,7 @@ typedef struct { } int_desc_t; -//We should mark the interrupt for the timer used by FreeRTOS as reserved. The specific timer +//We should mark the interrupt for the timer used by FreeRTOS as reserved. The specific timer //is selectable using menuconfig; we use these cpp bits to convert that into something we can use in //the table below. #if CONFIG_FREERTOS_CORETIMER_0 @@ -159,6 +159,13 @@ struct intr_handle_data_t { shared_vector_desc_t *shared_vector_desc; }; +typedef struct non_shared_isr_arg_t non_shared_isr_arg_t; + +struct non_shared_isr_arg_t { + intr_handler_t isr; + void *isr_arg; + int source; +}; //Linked list of vector descriptions, sorted by cpu.intno value static vector_desc_t *vector_desc_head; @@ -169,12 +176,15 @@ static uint32_t non_iram_int_mask[portNUM_PROCESSORS]; static uint32_t non_iram_int_disabled[portNUM_PROCESSORS]; static bool non_iram_int_disabled_flag[portNUM_PROCESSORS]; +#if CONFIG_SYSVIEW_ENABLE +extern uint32_t port_switch_flag[]; +#endif static portMUX_TYPE spinlock = portMUX_INITIALIZER_UNLOCKED; //Inserts an item into vector_desc list so that the list is sorted //with an incrementing cpu.intno value. -static void insert_vector_desc(vector_desc_t *to_insert) +static void insert_vector_desc(vector_desc_t *to_insert) { vector_desc_t *vd=vector_desc_head; vector_desc_t *prev=NULL; @@ -195,7 +205,7 @@ static void insert_vector_desc(vector_desc_t *to_insert) } //Returns a vector_desc entry for an intno/cpu, or NULL if none exists. -static vector_desc_t *find_desc_for_int(int intno, int cpu) +static vector_desc_t *find_desc_for_int(int intno, int cpu) { vector_desc_t *vd=vector_desc_head; while(vd!=NULL) { @@ -208,7 +218,7 @@ static vector_desc_t *find_desc_for_int(int intno, int cpu) //Returns a vector_desc entry for an intno/cpu. //Either returns a preexisting one or allocates a new one and inserts //it into the list. Returns NULL on malloc fail. -static vector_desc_t *get_desc_for_int(int intno, int cpu) +static vector_desc_t *get_desc_for_int(int intno, int cpu) { vector_desc_t *vd=find_desc_for_int(intno, cpu); if (vd==NULL) { @@ -234,7 +244,7 @@ esp_err_t esp_intr_mark_shared(int intno, int cpu, bool is_int_ram) if (vd==NULL) { portEXIT_CRITICAL(&spinlock); return ESP_ERR_NO_MEM; - } + } vd->flags=VECDESC_FL_SHARED; if (is_int_ram) vd->flags|=VECDESC_FL_INIRAM; portEXIT_CRITICAL(&spinlock); @@ -252,16 +262,16 @@ esp_err_t esp_intr_reserve(int intno, int cpu) if (vd==NULL) { portEXIT_CRITICAL(&spinlock); return ESP_ERR_NO_MEM; - } + } vd->flags=VECDESC_FL_RESERVED; portEXIT_CRITICAL(&spinlock); return ESP_OK; } -//Interrupt handler table and unhandled uinterrupt routine. Duplicated -//from xtensa_intr.c... it's supposed to be private, but we need to look -//into it in order to see if someone allocated an int using +//Interrupt handler table and unhandled uinterrupt routine. Duplicated +//from xtensa_intr.c... it's supposed to be private, but we need to look +//into it in order to see if someone allocated an int using //xt_set_interrupt_handler. typedef struct xt_handler_table_entry { void * handler; @@ -271,7 +281,7 @@ extern xt_handler_table_entry _xt_interrupt_table[XCHAL_NUM_INTERRUPTS*portNUM_P extern void xt_unhandled_interrupt(void * arg); //Returns true if handler for interrupt is not the default unhandled interrupt handler -static bool int_has_handler(int intr, int cpu) +static bool int_has_handler(int intr, int cpu) { return (_xt_interrupt_table[intr*portNUM_PROCESSORS+cpu].handler != xt_unhandled_interrupt); } @@ -303,8 +313,8 @@ static int get_free_int(int flags, int cpu, int force) ALCHLOG(TAG, "Ignoring int %d: forced to %d", x, force); continue; } - ALCHLOG(TAG, "Int %d reserved %d level %d %s hasIsr %d", - x, int_desc[x].cpuflags[cpu]==INTDESC_RESVD, int_desc[x].level, + ALCHLOG(TAG, "Int %d reserved %d level %d %s hasIsr %d", + x, int_desc[x].cpuflags[cpu]==INTDESC_RESVD, int_desc[x].level, int_desc[x].type==INTTP_LEVEL?"LEVEL":"EDGE", int_has_handler(x, cpu)); //Check if interrupt is not reserved by design if (int_desc[x].cpuflags[cpu]==INTDESC_RESVD) { @@ -321,7 +331,7 @@ static int get_free_int(int flags, int cpu, int force) continue; } //check if edge/level type matches what we want - if (((flags&ESP_INTR_FLAG_EDGE) && (int_desc[x].type==INTTP_LEVEL)) || + if (((flags&ESP_INTR_FLAG_EDGE) && (int_desc[x].type==INTTP_LEVEL)) || (((!(flags&ESP_INTR_FLAG_EDGE)) && (int_desc[x].type==INTTP_EDGE)))) { ALCHLOG(TAG, "....Unusable: incompatible trigger type"); continue; @@ -373,7 +383,7 @@ static int get_free_int(int flags, int cpu, int force) } } else { if (best==-1) { - //We haven't found a feasible shared interrupt yet. This one is still free and usable, even if + //We haven't found a feasible shared interrupt yet. This one is still free and usable, even if //not marked as shared. //Remember it in case we don't find any other shared interrupt that qualifies. if (bestLevel>int_desc[x].level) { @@ -406,9 +416,8 @@ static int get_free_int(int flags, int cpu, int force) return best; } - //Common shared isr handler. Chain-call all ISRs. -static void IRAM_ATTR shared_intr_isr(void *arg) +static void IRAM_ATTR shared_intr_isr(void *arg) { vector_desc_t *vd=(vector_desc_t*)arg; shared_vector_desc_t *sh_vec=vd->shared_vec_info; @@ -416,7 +425,16 @@ static void IRAM_ATTR shared_intr_isr(void *arg) while(sh_vec) { if (!sh_vec->disabled) { if ((sh_vec->statusreg == NULL) || (*sh_vec->statusreg & sh_vec->statusmask)) { +#if CONFIG_SYSVIEW_ENABLE + traceISR_ENTER(sh_vec->source+ETS_INTERNAL_INTR_SOURCE_OFF); +#endif sh_vec->isr(sh_vec->arg); +#if CONFIG_SYSVIEW_ENABLE + // check if we will return to scheduler or to interrupted task after ISR + if (!port_switch_flag[xPortGetCoreID()]) { + traceISR_EXIT(); + } +#endif } } sh_vec=sh_vec->next; @@ -424,10 +442,27 @@ static void IRAM_ATTR shared_intr_isr(void *arg) portEXIT_CRITICAL(&spinlock); } +#if CONFIG_SYSVIEW_ENABLE +//Common non-shared isr handler wrapper. +static void IRAM_ATTR non_shared_intr_isr(void *arg) +{ + non_shared_isr_arg_t *ns_isr_arg=(non_shared_isr_arg_t*)arg; + portENTER_CRITICAL(&spinlock); + traceISR_ENTER(ns_isr_arg->source+ETS_INTERNAL_INTR_SOURCE_OFF); + // FIXME: can we call ISR and check port_switch_flag after releasing spinlock? + // when CONFIG_SYSVIEW_ENABLE = 0 ISRs for non-shared IRQs are called without spinlock + ns_isr_arg->isr(ns_isr_arg->isr_arg); + // check if we will return to scheduler or to interrupted task after ISR + if (!port_switch_flag[xPortGetCoreID()]) { + traceISR_EXIT(); + } + portEXIT_CRITICAL(&spinlock); +} +#endif //We use ESP_EARLY_LOG* here because this can be called before the scheduler is running. -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) +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) { intr_handle_data_t *ret=NULL; int force=-1; @@ -456,7 +491,7 @@ esp_err_t esp_intr_alloc_intrstatus(int source, int flags, uint32_t intrstatusre } } ESP_EARLY_LOGV(TAG, "esp_intr_alloc_intrstatus (cpu %d): Args okay. Resulting flags 0x%X", xPortGetCoreID(), flags); - + //Check 'special' interrupt sources. These are tied to one specific interrupt, so we //have to force get_free_int to only look at that. if (source==ETS_INTERNAL_TIMER0_INTR_SOURCE) force=ETS_INTERNAL_TIMER0_INTR_NO; @@ -513,7 +548,20 @@ esp_err_t esp_intr_alloc_intrstatus(int source, int flags, uint32_t intrstatusre //Mark as unusable for other interrupt sources. This is ours now! vd->flags=VECDESC_FL_NONSHARED; if (handler) { +#if CONFIG_SYSVIEW_ENABLE + non_shared_isr_arg_t *ns_isr_arg=malloc(sizeof(non_shared_isr_arg_t)); + if (!ns_isr_arg) { + portEXIT_CRITICAL(&spinlock); + free(ret); + return ESP_ERR_NO_MEM; + } + ns_isr_arg->isr=handler; + ns_isr_arg->isr_arg=arg; + ns_isr_arg->source=source; + xt_set_interrupt_handler(intr, non_shared_intr_isr, ns_isr_arg); +#else xt_set_interrupt_handler(intr, handler, arg); +#endif } if (flags&ESP_INTR_FLAG_EDGE) xthal_set_intclear(1 << intr); vd->source=source; @@ -555,18 +603,18 @@ esp_err_t esp_intr_alloc_intrstatus(int source, int flags, uint32_t intrstatusre return ESP_OK; } -esp_err_t esp_intr_alloc(int source, int flags, intr_handler_t handler, void *arg, intr_handle_t *ret_handle) +esp_err_t esp_intr_alloc(int source, int flags, intr_handler_t handler, void *arg, intr_handle_t *ret_handle) { /* As an optimization, we can create a table with the possible interrupt status registers and masks for every single - source there is. We can then add code here to look up an applicable value and pass that to the + source there is. We can then add code here to look up an applicable value and pass that to the esp_intr_alloc_intrstatus function. */ return esp_intr_alloc_intrstatus(source, flags, 0, 0, handler, arg, ret_handle); } -esp_err_t esp_intr_free(intr_handle_t handle) +esp_err_t esp_intr_free(intr_handle_t handle) { bool free_shared_vector=false; if (!handle) return ESP_ERR_INVALID_ARG; @@ -576,7 +624,7 @@ esp_err_t esp_intr_free(intr_handle_t handle) portENTER_CRITICAL(&spinlock); esp_intr_disable(handle); if (handle->vector_desc->flags&VECDESC_FL_SHARED) { - //Find and kill the shared int + //Find and kill the shared int shared_vector_desc_t *svd=handle->vector_desc->shared_vec_info; shared_vector_desc_t *prevsvd=NULL; assert(svd); //should be something in there for a shared int @@ -601,11 +649,19 @@ esp_err_t esp_intr_free(intr_handle_t handle) if ((handle->vector_desc->flags&VECDESC_FL_NONSHARED) || free_shared_vector) { ESP_LOGV(TAG, "esp_intr_free: Disabling int, killing handler"); +#if CONFIG_SYSVIEW_ENABLE + if (!free_shared_vector) { + void *isr_arg = xt_get_interrupt_handler_arg(handle->vector_desc->intno); + if (isr_arg) { + free(isr_arg); + } + } +#endif //Reset to normal handler xt_set_interrupt_handler(handle->vector_desc->intno, xt_unhandled_interrupt, (void*)((int)handle->vector_desc->intno)); //Theoretically, we could free the vector_desc... not sure if that's worth the few bytes of memory - //we save.(We can also not use the same exit path for empty shared ints anymore if we delete - //the desc.) For now, just mark it as free. + //we save.(We can also not use the same exit path for empty shared ints anymore if we delete + //the desc.) For now, just mark it as free. handle->vector_desc->flags&=!(VECDESC_FL_NONSHARED|VECDESC_FL_RESERVED); //Also kill non_iram mask bit. non_iram_int_mask[handle->vector_desc->cpu]&=~(1<<(handle->vector_desc->intno)); diff --git a/components/esp32/ld/esp32.common.ld b/components/esp32/ld/esp32.common.ld index 48e31d1ea0..475b2b2bfd 100644 --- a/components/esp32/ld/esp32.common.ld +++ b/components/esp32/ld/esp32.common.ld @@ -86,7 +86,8 @@ SECTIONS *libesp32.a:panic.o(.literal .text .literal.* .text.*) *libesp32.a:core_dump.o(.literal .text .literal.* .text.*) *libesp32.a:heap_alloc_caps.o(.literal .text .literal.* .text.*) - *libesp32.a:app_trace.o(.literal .text .literal.* .text.*) + *libapp_trace.a:(.literal .text .literal.* .text.*) + *libxtensa-debug-module.a:eri.o(.literal .text .literal.* .text.*) *libphy.a:(.literal .text .literal.* .text.*) *librtc.a:(.literal .text .literal.* .text.*) *libsoc.a:(.literal .text .literal.* .text.*) @@ -111,8 +112,8 @@ SECTIONS KEEP(*(.jcr)) *(.dram1 .dram1.*) *libesp32.a:panic.o(.rodata .rodata.*) - *libesp32.a:app_trace.o(.rodata .rodata.*) *libphy.a:(.rodata .rodata.*) + *libapp_trace.a:(.rodata .rodata.*) _data_end = ABSOLUTE(.); . = ALIGN(4); } >dram0_0_seg diff --git a/components/esp32/panic.c b/components/esp32/panic.c index 4d83864467..fe50622f53 100644 --- a/components/esp32/panic.c +++ b/components/esp32/panic.c @@ -39,7 +39,15 @@ #include "esp_spi_flash.h" #include "esp_cache_err_int.h" #include "esp_app_trace.h" +#if CONFIG_SYSVIEW_ENABLE +#include "SEGGER_RTT.h" +#endif +#if CONFIG_ESP32_APPTRACE_ONPANIC_HOST_FLUSH_TMO == -1 +#define APPTRACE_ONPANIC_HOST_FLUSH_TMO ESP_APPTRACE_TMO_INFINITE +#else +#define APPTRACE_ONPANIC_HOST_FLUSH_TMO (1000*CONFIG_ESP32_APPTRACE_ONPANIC_HOST_FLUSH_TMO) +#endif /* Panic handlers; these get called when an unhandled exception occurs or the assembly-level task switching / interrupt code runs into an unrecoverable error. The default task stack @@ -116,7 +124,12 @@ static __attribute__((noreturn)) inline void invoke_abort() { abort_called = true; #if CONFIG_ESP32_APPTRACE_ENABLE - esp_apptrace_flush_nolock(ESP_APPTRACE_DEST_TRAX, ESP_APPTRACE_TRAX_BLOCK_SIZE*CONFIG_ESP32_APPTRACE_ONPANIC_HOST_FLUSH_TRAX_THRESH/100, CONFIG_ESP32_APPTRACE_ONPANIC_HOST_FLUSH_TMO); +#if CONFIG_SYSVIEW_ENABLE + SEGGER_RTT_ESP32_FlushNoLock(CONFIG_ESP32_APPTRACE_POSTMORTEM_FLUSH_TRAX_THRESH, APPTRACE_ONPANIC_HOST_FLUSH_TMO); +#else + esp_apptrace_flush_nolock(ESP_APPTRACE_DEST_TRAX, CONFIG_ESP32_APPTRACE_POSTMORTEM_FLUSH_TRAX_THRESH, + APPTRACE_ONPANIC_HOST_FLUSH_TMO); +#endif #endif while(1) { if (esp_cpu_in_ocd_debug_mode()) { @@ -233,7 +246,12 @@ void panicHandler(XtExcFrame *frame) if (esp_cpu_in_ocd_debug_mode()) { #if CONFIG_ESP32_APPTRACE_ENABLE - esp_apptrace_flush_nolock(ESP_APPTRACE_DEST_TRAX, ESP_APPTRACE_TRAX_BLOCK_SIZE*CONFIG_ESP32_APPTRACE_ONPANIC_HOST_FLUSH_TRAX_THRESH/100, CONFIG_ESP32_APPTRACE_ONPANIC_HOST_FLUSH_TMO); +#if CONFIG_SYSVIEW_ENABLE + SEGGER_RTT_ESP32_FlushNoLock(CONFIG_ESP32_APPTRACE_POSTMORTEM_FLUSH_TRAX_THRESH, APPTRACE_ONPANIC_HOST_FLUSH_TMO); +#else + esp_apptrace_flush_nolock(ESP_APPTRACE_DEST_TRAX, CONFIG_ESP32_APPTRACE_POSTMORTEM_FLUSH_TRAX_THRESH, + APPTRACE_ONPANIC_HOST_FLUSH_TMO); +#endif #endif setFirstBreakpoint(frame->pc); return; @@ -259,7 +277,12 @@ void xt_unhandled_exception(XtExcFrame *frame) panicPutHex(frame->pc); panicPutStr(". Setting bp and returning..\r\n"); #if CONFIG_ESP32_APPTRACE_ENABLE - esp_apptrace_flush_nolock(ESP_APPTRACE_DEST_TRAX, ESP_APPTRACE_TRAX_BLOCK_SIZE*CONFIG_ESP32_APPTRACE_ONPANIC_HOST_FLUSH_TRAX_THRESH/100, CONFIG_ESP32_APPTRACE_ONPANIC_HOST_FLUSH_TMO); +#if CONFIG_SYSVIEW_ENABLE + SEGGER_RTT_ESP32_FlushNoLock(CONFIG_ESP32_APPTRACE_POSTMORTEM_FLUSH_TRAX_THRESH, APPTRACE_ONPANIC_HOST_FLUSH_TMO); +#else + esp_apptrace_flush_nolock(ESP_APPTRACE_DEST_TRAX, CONFIG_ESP32_APPTRACE_POSTMORTEM_FLUSH_TRAX_THRESH, + APPTRACE_ONPANIC_HOST_FLUSH_TMO); +#endif #endif //Stick a hardware breakpoint on the address the handler returns to. This way, the OCD debugger //will kick in exactly at the context the error happened. @@ -430,7 +453,12 @@ static __attribute__((noreturn)) void commonErrorHandler(XtExcFrame *frame) #if CONFIG_ESP32_APPTRACE_ENABLE disableAllWdts(); - esp_apptrace_flush_nolock(ESP_APPTRACE_DEST_TRAX, ESP_APPTRACE_TRAX_BLOCK_SIZE*CONFIG_ESP32_APPTRACE_ONPANIC_HOST_FLUSH_TRAX_THRESH/100, CONFIG_ESP32_APPTRACE_ONPANIC_HOST_FLUSH_TMO); +#if CONFIG_SYSVIEW_ENABLE + SEGGER_RTT_ESP32_FlushNoLock(CONFIG_ESP32_APPTRACE_POSTMORTEM_FLUSH_TRAX_THRESH, APPTRACE_ONPANIC_HOST_FLUSH_TMO); +#else + esp_apptrace_flush_nolock(ESP_APPTRACE_DEST_TRAX, CONFIG_ESP32_APPTRACE_POSTMORTEM_FLUSH_TRAX_THRESH, + APPTRACE_ONPANIC_HOST_FLUSH_TMO); +#endif reconfigureAllWdts(); #endif diff --git a/components/ethernet/emac_main.c b/components/ethernet/emac_main.c index 7e299be944..8c24eb4f97 100644 --- a/components/ethernet/emac_main.c +++ b/components/ethernet/emac_main.c @@ -236,7 +236,7 @@ static void emac_set_user_config_data(eth_config_t *config ) emac_config.emac_phy_get_duplex_mode = config->phy_get_duplex_mode; #if DMA_RX_BUF_NUM > 9 emac_config.emac_flow_ctrl_enable = config->flow_ctrl_enable; -#else +#else if(config->flow_ctrl_enable == true) { ESP_LOGE(TAG, "eth flow ctrl init err!!! Please run make menuconfig and make sure DMA_RX_BUF_NUM > 9 ."); } diff --git a/components/freertos/component.mk b/components/freertos/component.mk index 0240ea235f..83a4443f69 100644 --- a/components/freertos/component.mk +++ b/components/freertos/component.mk @@ -6,3 +6,6 @@ COMPONENT_ADD_LDFLAGS = -l$(COMPONENT_NAME) -Wl,--undefined=uxTopUsedPriority COMPONENT_ADD_INCLUDEDIRS := include COMPONENT_PRIV_INCLUDEDIRS := include/freertos +#ifdef CONFIG_SYSVIEW_ENABLE +#COMPONENT_ADD_INCLUDEDIRS += app_trace +#endif diff --git a/components/freertos/include/freertos/FreeRTOS.h b/components/freertos/include/freertos/FreeRTOS.h index 0e93acf271..31b66fb850 100644 --- a/components/freertos/include/freertos/FreeRTOS.h +++ b/components/freertos/include/freertos/FreeRTOS.h @@ -204,6 +204,10 @@ extern "C" { #define INCLUDE_uxTaskGetStackHighWaterMark 0 #endif +#ifndef INCLUDE_pxTaskGetStackStart + #define INCLUDE_pxTaskGetStackStart 0 +#endif + #ifndef INCLUDE_eTaskGetState #define INCLUDE_eTaskGetState 0 #endif @@ -406,6 +410,22 @@ extern "C" { #define traceMOVED_TASK_TO_READY_STATE( pxTCB ) #endif +#ifndef traceREADDED_TASK_TO_READY_STATE + #define traceREADDED_TASK_TO_READY_STATE( pxTCB ) traceMOVED_TASK_TO_READY_STATE( pxTCB ) +#endif + +#ifndef traceMOVED_TASK_TO_DELAYED_LIST + #define traceMOVED_TASK_TO_DELAYED_LIST() +#endif + +#ifndef traceMOVED_TASK_TO_OVERFLOW_DELAYED_LIST + #define traceMOVED_TASK_TO_OVERFLOW_DELAYED_LIST() +#endif + +#ifndef traceMOVED_TASK_TO_SUSPENDED_LIST + #define traceMOVED_TASK_TO_SUSPENDED_LIST( pxTCB ) +#endif + #ifndef traceQUEUE_CREATE #define traceQUEUE_CREATE( pxNewQueue ) #endif @@ -618,6 +638,22 @@ extern "C" { #define traceQUEUE_REGISTRY_ADD(xQueue, pcQueueName) #endif +#ifndef traceTASK_NOTIFY_GIVE_FROM_ISR + #define traceTASK_NOTIFY_GIVE_FROM_ISR() + #endif + +#ifndef traceISR_EXIT_TO_SCHEDULER + #define traceISR_EXIT_TO_SCHEDULER() +#endif + +#ifndef traceISR_EXIT + #define traceISR_EXIT() +#endif + +#ifndef traceISR_ENTER + #define traceISR_ENTER(_n_) +#endif + #ifndef configGENERATE_RUN_TIME_STATS #define configGENERATE_RUN_TIME_STATS 0 #endif diff --git a/components/freertos/include/freertos/FreeRTOSConfig.h b/components/freertos/include/freertos/FreeRTOSConfig.h index 250879f306..a69381e074 100644 --- a/components/freertos/include/freertos/FreeRTOSConfig.h +++ b/components/freertos/include/freertos/FreeRTOSConfig.h @@ -227,6 +227,7 @@ #define INCLUDE_vTaskDelay 1 #define INCLUDE_uxTaskGetStackHighWaterMark 1 #define INCLUDE_pcTaskGetTaskName 1 +#define INCLUDE_xTaskGetIdleTaskHandle 1 #if CONFIG_ENABLE_MEMORY_DEBUG #define configENABLE_MEMORY_DEBUG 1 @@ -276,6 +277,12 @@ extern void vPortCleanUpTCB ( void *pxTCB ); #define configENABLE_TASK_SNAPSHOT 1 #endif +#if CONFIG_SYSVIEW_ENABLE +#ifndef __ASSEMBLER__ +#include "SEGGER_SYSVIEW_FreeRTOS.h" +#undef INLINE // to avoid redefinition +#endif /* def __ASSEMBLER__ */ +#endif #endif /* FREERTOS_CONFIG_H */ diff --git a/components/freertos/include/freertos/portmacro.h b/components/freertos/include/freertos/portmacro.h index 00db60c913..a909b329af 100644 --- a/components/freertos/include/freertos/portmacro.h +++ b/components/freertos/include/freertos/portmacro.h @@ -268,7 +268,7 @@ static inline void uxPortCompareSet(volatile uint32_t *addr, uint32_t compare, u void vPortYield( void ); void _frxt_setup_switch( void ); #define portYIELD() vPortYield() -#define portYIELD_FROM_ISR() _frxt_setup_switch() +#define portYIELD_FROM_ISR() {traceISR_EXIT_TO_SCHEDULER(); _frxt_setup_switch();} static inline uint32_t xPortGetCoreID(); diff --git a/components/freertos/include/freertos/task.h b/components/freertos/include/freertos/task.h index bd91d34991..2438d96000 100644 --- a/components/freertos/include/freertos/task.h +++ b/components/freertos/include/freertos/task.h @@ -1297,6 +1297,25 @@ char *pcTaskGetTaskName( TaskHandle_t xTaskToQuery ) PRIVILEGED_FUNCTION; /*lint */ UBaseType_t uxTaskGetStackHighWaterMark( TaskHandle_t xTask ) PRIVILEGED_FUNCTION; +/** + * task.h + *
uint8_t* pxTaskGetStackStart( TaskHandle_t xTask);
+ * + * INCLUDE_pxTaskGetStackStart must be set to 1 in FreeRTOSConfig.h for + * this function to be available. + * + * Returns the start of the stack associated with xTask. That is, + * the highest stack memory address on architectures where the stack grows down + * from high memory, and the lowest memory address on architectures where the + * stack grows up from low memory. + * + * @param xTask Handle of the task associated with the stack returned. + * Set xTask to NULL to return the stack of the calling task. + * + * @return A pointer to the start of the stack. + */ +uint8_t* pxTaskGetStackStart( TaskHandle_t xTask) PRIVILEGED_FUNCTION; + /* When using trace macros it is sometimes necessary to include task.h before FreeRTOS.h. When this is done TaskHookFunction_t will not yet have been defined, so the following two prototypes will cause a compilation error. This can be diff --git a/components/freertos/include/freertos/xtensa_api.h b/components/freertos/include/freertos/xtensa_api.h index 87922691dd..19630ce581 100644 --- a/components/freertos/include/freertos/xtensa_api.h +++ b/components/freertos/include/freertos/xtensa_api.h @@ -117,6 +117,14 @@ static inline void xt_set_intclear(unsigned int arg) xthal_set_intclear(arg); } +/* +------------------------------------------------------------------------------- + Call this function to get handler's argument for the specified interrupt. + + n - Interrupt number. +------------------------------------------------------------------------------- +*/ +extern void * xt_get_interrupt_handler_arg(int n); #endif /* __XTENSA_API_H__ */ diff --git a/components/freertos/port.c b/components/freertos/port.c index bd6864049c..a578df9a17 100644 --- a/components/freertos/port.c +++ b/components/freertos/port.c @@ -105,6 +105,8 @@ #include "esp_crosscore_int.h" +#include "esp_intr_alloc.h" + /* Defined in portasm.h */ extern void _frxt_tick_timer_init(void); @@ -112,6 +114,13 @@ extern void _frxt_tick_timer_init(void); extern void _xt_coproc_init(void); +#if CONFIG_FREERTOS_CORETIMER_0 + #define SYSTICK_INTR_ID (ETS_INTERNAL_TIMER0_INTR_SOURCE+ETS_INTERNAL_INTR_SOURCE_OFF) +#endif +#if CONFIG_FREERTOS_CORETIMER_1 + #define SYSTICK_INTR_ID (ETS_INTERNAL_TIMER1_INTR_SOURCE+ETS_INTERNAL_INTR_SOURCE_OFF) +#endif + /*-----------------------------------------------------------*/ unsigned port_xSchedulerRunning[portNUM_PROCESSORS] = {0}; // Duplicate of inaccessible xSchedulerRunning; needed at startup to avoid counting nesting @@ -122,7 +131,7 @@ unsigned port_interruptNesting[portNUM_PROCESSORS] = {0}; // Interrupt nesting // User exception dispatcher when exiting void _xt_user_exit(void); -/* +/* * Stack initialization */ #if portUSING_MPU_WRAPPERS @@ -222,12 +231,14 @@ BaseType_t xPortSysTickHandler( void ) BaseType_t ret; portbenchmarkIntLatency(); + traceISR_ENTER(SYSTICK_INTR_ID); ret = xTaskIncrementTick(); if( ret != pdFALSE ) { portYIELD_FROM_ISR(); + } else { + traceISR_EXIT(); } - return ret; } diff --git a/components/freertos/portasm.S b/components/freertos/portasm.S index 7f23e6283b..de4b0d5581 100644 --- a/components/freertos/portasm.S +++ b/components/freertos/portasm.S @@ -30,7 +30,6 @@ .extern pxCurrentTCB - /* ******************************************************************************* * Interrupt stack. The size of the interrupt stack is determined by the config @@ -42,6 +41,7 @@ .align 16 .global port_IntStack .global port_IntStackTop + .global port_switch_flag port_IntStack: .space configISR_STACK_SIZE*portNUM_PROCESSORS /* This allocates stacks for each individual CPU. */ port_IntStackTop: diff --git a/components/freertos/queue.c b/components/freertos/queue.c index 66a7ed0497..b66b8065a4 100644 --- a/components/freertos/queue.c +++ b/components/freertos/queue.c @@ -70,7 +70,7 @@ /* - ToDo: The multicore implementation of this uses taskENTER_CRITICAL etc to make sure the + ToDo: The multicore implementation of this uses taskENTER_CRITICAL etc to make sure the queue structures aren't accessed by another processor or core. It would be useful to have IRQs be able to schedule stuff while doing task-related stuff, meaning we have to convert the taskENTER_CRITICAL stuff to a lock + a scheduler suspend instead. @@ -262,7 +262,7 @@ Queue_t * const pxQueue = ( Queue_t * ) xQueue; configASSERT( pxQueue ); - if ( xNewQueue == pdTRUE ) + if ( xNewQueue == pdTRUE ) { vPortCPUInitializeMutex(&pxQueue->mux); } @@ -1181,7 +1181,7 @@ Queue_t * const pxQueue = ( Queue_t * ) xQueue; if( ( pxQueue->uxMessagesWaiting < pxQueue->uxLength ) || ( xCopyPosition == queueOVERWRITE ) ) { traceQUEUE_SEND_FROM_ISR( pxQueue ); - + /* A task can only have an inherited priority if it is a mutex holder - and if there is a mutex holder then the mutex cannot be given from an ISR. Therefore, unlike the xQueueGenericGive() @@ -2315,7 +2315,7 @@ Queue_t * const pxQueue = ( Queue_t * ) xQueue; void vQueueAddToRegistry( QueueHandle_t xQueue, const char *pcQueueName ) /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ { UBaseType_t ux; - + UNTESTED_FUNCTION(); /* See if there is an empty space in the registry. A NULL name denotes a free slot. */ diff --git a/components/freertos/tasks.c b/components/freertos/tasks.c index a28e1031a9..2090f0d3c7 100644 --- a/components/freertos/tasks.c +++ b/components/freertos/tasks.c @@ -277,7 +277,7 @@ PRIVILEGED_DATA static List_t xPendingReadyList[ portNUM_PROCESSORS ]; /*< #if ( INCLUDE_xTaskGetIdleTaskHandle == 1 ) - PRIVILEGED_DATA static TaskHandle_t xIdleTaskHandle = NULL; /*< Holds the handle of the idle task. The idle task is created automatically when the scheduler is started. */ + PRIVILEGED_DATA static TaskHandle_t xIdleTaskHandle[portNUM_PROCESSORS] = {NULL}; /*< Holds the handle of the idle task. The idle task is created automatically when the scheduler is started. */ #endif @@ -314,6 +314,12 @@ PRIVILEGED_DATA static portMUX_TYPE xTickCountMutex = portMUX_INITIALIZER_UNLOCK #endif + +// per-CPU flags indicating that we are doing context switch, it is used by apptrace and sysview modules +// in order to avoid calls of vPortYield from traceTASK_SWITCHED_IN/OUT when waiting +// for locks to be free or for host to read full trace buffer +PRIVILEGED_DATA static volatile BaseType_t xSwitchingContext[ portNUM_PROCESSORS ] = { pdFALSE }; + /*lint +e956 */ /* Debugging and trace facilities private variables and macros. ------------*/ @@ -436,12 +442,20 @@ count overflows. */ * the task. It is inserted at the end of the list. */ #define prvAddTaskToReadyList( pxTCB ) \ - traceMOVED_TASK_TO_READY_STATE( pxTCB ) \ + traceMOVED_TASK_TO_READY_STATE( pxTCB ); \ taskRECORD_READY_PRIORITY( ( pxTCB )->uxPriority ); \ vListInsertEnd( &( pxReadyTasksLists[ ( pxTCB )->uxPriority ] ), &( ( pxTCB )->xGenericListItem ) ) +/* + * Place the task represented by pxTCB which has been in a ready list before + * into the appropriate ready list for the task. + * It is inserted at the end of the list. + */ +#define prvReaddTaskToReadyList( pxTCB ) \ + traceREADDED_TASK_TO_READY_STATE( pxTCB ); \ + taskRECORD_READY_PRIORITY( ( pxTCB )->uxPriority ); \ + vListInsertEnd( &( pxReadyTasksLists[ ( pxTCB )->uxPriority ] ), &( ( pxTCB )->xGenericListItem ) ) /*-----------------------------------------------------------*/ - #define tskCAN_RUN_HERE( cpuid ) ( cpuid==xPortGetCoreID() || cpuid==tskNO_AFFINITY ) /* @@ -621,7 +635,7 @@ static void prvAddNewTaskToReadyList( TCB_t *pxNewTCB, TaskFunction_t pxTaskCode /* * This routine tries to send an interrupt to another core if needed to make it execute a task - * of higher priority. We try to figure out if needed first by inspecting the pxTCB of the + * of higher priority. We try to figure out if needed first by inspecting the pxTCB of the * other CPU first. Specifically for Xtensa, we can do this because pxTCB is an atomic pointer. It * is possible that it is inaccurate because the other CPU just did a task switch, but in that case * at most a superfluous interrupt is generated. @@ -1046,8 +1060,8 @@ static void prvAddNewTaskToReadyList( TCB_t *pxNewTCB, TaskFunction_t pxTaskCode { TCB_t *curTCB, *tcb0, *tcb1; - /* Assure that xCoreID is valid or we'll have an out-of-bounds on pxCurrentTCB - You will assert here if e.g. you only have one CPU enabled in menuconfig and + /* Assure that xCoreID is valid or we'll have an out-of-bounds on pxCurrentTCB + You will assert here if e.g. you only have one CPU enabled in menuconfig and are trying to start a task on core 1. */ configASSERT( xCoreID == tskNO_AFFINITY || xCoreID < portNUM_PROCESSORS); @@ -1609,7 +1623,7 @@ static void prvAddNewTaskToReadyList( TCB_t *pxNewTCB, TaskFunction_t pxTaskCode { xYieldRequired = pdTRUE; } - else if ( pxTCB->xCoreID != xPortGetCoreID() ) + else if ( pxTCB->xCoreID != xPortGetCoreID() ) { taskYIELD_OTHER_CORE( pxTCB->xCoreID, uxNewPriority ); } @@ -1697,7 +1711,7 @@ static void prvAddNewTaskToReadyList( TCB_t *pxNewTCB, TaskFunction_t pxTaskCode { mtCOVERAGE_TEST_MARKER(); } - prvAddTaskToReadyList( pxTCB ); + prvReaddTaskToReadyList( pxTCB ); } else { @@ -1758,7 +1772,7 @@ static void prvAddNewTaskToReadyList( TCB_t *pxNewTCB, TaskFunction_t pxTaskCode { mtCOVERAGE_TEST_MARKER(); } - + traceMOVED_TASK_TO_SUSPENDED_LIST(pxTCB); vListInsertEnd( &xSuspendedTaskList, &( pxTCB->xGenericListItem ) ); curTCB = pxCurrentTCB[ xPortGetCoreID() ]; } @@ -2064,7 +2078,7 @@ void vTaskEndScheduler( void ) #if ( configUSE_NEWLIB_REENTRANT == 1 ) -//Return global reent struct if FreeRTOS isn't running, +//Return global reent struct if FreeRTOS isn't running, struct _reent* __getreent() { //No lock needed because if this changes, we won't be running anymore. TCB_t *currTask=xTaskGetCurrentTaskHandle(); @@ -2353,8 +2367,8 @@ UBaseType_t uxTaskGetNumberOfTasks( void ) { /* If xTaskGetIdleTaskHandle() is called before the scheduler has been started, then xIdleTaskHandle will be NULL. */ - configASSERT( ( xIdleTaskHandle != NULL ) ); - return xIdleTaskHandle; + configASSERT( ( xIdleTaskHandle[ xPortGetCoreID() ] != NULL ) ); + return xIdleTaskHandle[ xPortGetCoreID() ]; } #endif /* INCLUDE_xTaskGetIdleTaskHandle */ @@ -2393,7 +2407,7 @@ BaseType_t xSwitchRequired = pdFALSE; /* Only let core 0 increase the tick count, to keep accurate track of time. */ /* ToDo: This doesn't really play nice with the logic below: it means when core 1 is - running a low-priority task, it will keep running it until there is a context + running a low-priority task, it will keep running it until there is a context switch, even when this routine (running on core 0) unblocks a bunch of high-priority tasks... this is less than optimal -- JD. */ if ( xPortGetCoreID()!=0 ) { @@ -2688,6 +2702,7 @@ void vTaskSwitchContext( void ) else { xYieldPending[ xPortGetCoreID() ] = pdFALSE; + xSwitchingContext[ xPortGetCoreID() ] = pdTRUE; traceTASK_SWITCHED_OUT(); #if ( configGENERATE_RUN_TIME_STATS == 1 ) @@ -2724,7 +2739,7 @@ void vTaskSwitchContext( void ) taskSECOND_CHECK_FOR_STACK_OVERFLOW(); /* Select a new task to run */ - + /* We cannot do taskENTER_CRITICAL_ISR(&xTaskQueueMutex); here because it saves the interrupt context to the task tcb, and we're swapping that out here. Instead, we're going to do the work here ourselves. Because interrupts are already disabled, we only @@ -2735,11 +2750,11 @@ void vTaskSwitchContext( void ) #else vPortCPUAcquireMutex( &xTaskQueueMutex ); #endif - + unsigned portBASE_TYPE foundNonExecutingWaiter = pdFALSE, ableToSchedule = pdFALSE, resetListHead; portBASE_TYPE uxDynamicTopReady = uxTopReadyPriority; unsigned portBASE_TYPE holdTop=pdFALSE; - + /* * ToDo: This scheduler doesn't correctly implement the round-robin scheduling as done in the single-core * FreeRTOS stack when multiple tasks have the same priority and are all ready; it just keeps grabbing the @@ -2747,21 +2762,21 @@ void vTaskSwitchContext( void ) * (Is this still true? if any, there's the issue with one core skipping over the processes for the other * core, potentially not giving the skipped-over processes any time.) */ - + while ( ableToSchedule == pdFALSE && uxDynamicTopReady >= 0 ) { resetListHead = pdFALSE; // Nothing to do for empty lists if (!listLIST_IS_EMPTY( &( pxReadyTasksLists[ uxDynamicTopReady ] ) )) { - + ableToSchedule = pdFALSE; tskTCB * pxRefTCB; - + /* Remember the current list item so that we can detect if all items have been inspected. Once this happens, we move on to a lower priority list (assuming nothing is suitable - for scheduling). Note: This can return NULL if + for scheduling). Note: This can return NULL if the list index is at the listItem */ pxRefTCB = pxReadyTasksLists[ uxDynamicTopReady ].pxIndex->pvOwner; @@ -2769,7 +2784,7 @@ void vTaskSwitchContext( void ) //pxIndex points to the list end marker. Skip that and just get the next item. listGET_OWNER_OF_NEXT_ENTRY( pxRefTCB, &( pxReadyTasksLists[ uxDynamicTopReady ] ) ); } - + do { listGET_OWNER_OF_NEXT_ENTRY( pxTCB, &( pxReadyTasksLists[ uxDynamicTopReady ] ) ); /* Find out if the next task in the list is @@ -2785,7 +2800,7 @@ void vTaskSwitchContext( void ) break; } } - + if (foundNonExecutingWaiter == pdTRUE) { /* If the task is not being executed by another core and its affinity is @@ -2804,7 +2819,7 @@ void vTaskSwitchContext( void ) } else { ableToSchedule = pdFALSE; } - + if (ableToSchedule == pdFALSE) { resetListHead = pdTRUE; } else if ((ableToSchedule == pdTRUE) && (resetListHead == pdTRUE)) { @@ -2821,6 +2836,7 @@ void vTaskSwitchContext( void ) } traceTASK_SWITCHED_IN(); + xSwitchingContext[ xPortGetCoreID() ] = pdFALSE; //Exit critical region manually as well: release the mux now, interrupts will be re-enabled when we //exit the function. @@ -2834,7 +2850,6 @@ void vTaskSwitchContext( void ) vPortSetStackWatchpoint(pxCurrentTCB[xPortGetCoreID()]->pxStack); #endif - } portEXIT_CRITICAL_NESTED(irqstate); } @@ -2875,6 +2890,7 @@ TickType_t xTimeToWake; /* Add the task to the suspended task list instead of a delayed task list to ensure the task is not woken by a timing event. It will block indefinitely. */ + traceMOVED_TASK_TO_SUSPENDED_LIST(pxCurrentTCB); vListInsertEnd( &xSuspendedTaskList, &( pxCurrentTCB[ xPortGetCoreID() ]->xGenericListItem ) ); } else @@ -3567,7 +3583,7 @@ static void prvCheckTasksWaitingTermination( void ) break; } } - + #if ( configNUM_THREAD_LOCAL_STORAGE_POINTERS > 0 ) && ( configTHREAD_LOCAL_STORAGE_DELETE_CALLBACKS ) { int x; @@ -3586,7 +3602,7 @@ static void prvCheckTasksWaitingTermination( void ) { mtCOVERAGE_TEST_MARKER(); } - } + } taskEXIT_CRITICAL(&xTaskQueueMutex); } #endif /* vTaskDelete */ @@ -3601,11 +3617,13 @@ static void prvAddCurrentTaskToDelayedList( const BaseType_t xCoreID, const Tick if( xTimeToWake < xTickCount ) { + traceMOVED_TASK_TO_OVERFLOW_DELAYED_LIST(); /* Wake time has overflowed. Place this item in the overflow list. */ vListInsert( pxOverflowDelayedTaskList, &( pxCurrentTCB[ xCoreID ]->xGenericListItem ) ); } else { + traceMOVED_TASK_TO_DELAYED_LIST(); /* The wake time has not overflowed, so the current block list is used. */ vListInsert( pxDelayedTaskList, &( pxCurrentTCB[ xCoreID ]->xGenericListItem ) ); @@ -3749,7 +3767,6 @@ BaseType_t xTaskGetAffinity( TaskHandle_t xTask ) uint8_t *pucEndOfStack; UBaseType_t uxReturn; - UNTESTED_FUNCTION(); pxTCB = prvGetTCBFromHandle( xTask ); #if portSTACK_GROWTH < 0 @@ -3770,6 +3787,19 @@ BaseType_t xTaskGetAffinity( TaskHandle_t xTask ) #endif /* INCLUDE_uxTaskGetStackHighWaterMark */ /*-----------------------------------------------------------*/ +#if (INCLUDE_pxTaskGetStackStart == 1) + uint8_t* pxTaskGetStackStart( TaskHandle_t xTask) + { + TCB_t *pxTCB; + UBaseType_t uxReturn; + + pxTCB = prvGetTCBFromHandle( xTask ); + return ( uint8_t * ) pxTCB->pxStack; + } + +#endif /* INCLUDE_pxTaskGetStackStart */ +/*-----------------------------------------------------------*/ + #if ( INCLUDE_vTaskDelete == 1 ) @@ -3954,7 +3984,7 @@ TCB_t *pxTCB; /* Inherit the priority before being moved into the new list. */ pxTCB->uxPriority = pxCurrentTCB[ xPortGetCoreID() ]->uxPriority; - prvAddTaskToReadyList( pxTCB ); + prvReaddTaskToReadyList( pxTCB ); } else { @@ -4025,7 +4055,7 @@ TCB_t *pxTCB; any other purpose if this task is running, and it must be running to give back the mutex. */ listSET_LIST_ITEM_VALUE( &( pxTCB->xEventListItem ), ( TickType_t ) configMAX_PRIORITIES - ( TickType_t ) pxTCB->uxPriority ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ - prvAddTaskToReadyList( pxTCB ); + prvReaddTaskToReadyList( pxTCB ); /* Return true to indicate that a context switch is required. This is only actually required in the corner case whereby @@ -4066,7 +4096,7 @@ TCB_t *pxTCB; /* Gotcha (which seems to be deliberate in FreeRTOS, according to http://www.freertos.org/FreeRTOS_Support_Forum_Archive/December_2012/freertos_PIC32_Bug_-_vTaskEnterCritical_6400806.html ) is that calling vTaskEnterCritical followed by vTaskExitCritical will leave the interrupts DISABLED when the scheduler -is not running. Re-enabling the scheduler will re-enable the interrupts instead. +is not running. Re-enabling the scheduler will re-enable the interrupts instead. For ESP32 FreeRTOS, vTaskEnterCritical implements both portENTER_CRITICAL and portENTER_CRITICAL_ISR. */ @@ -4112,11 +4142,11 @@ For ESP32 FreeRTOS, vTaskEnterCritical implements both portENTER_CRITICAL and po protect against recursive calls if the assert function also uses a critical section. */ - /* DISABLED in the esp32 port - because of SMP, For ESP32 - FreeRTOS, vTaskEnterCritical implements both + /* DISABLED in the esp32 port - because of SMP, For ESP32 + FreeRTOS, vTaskEnterCritical implements both portENTER_CRITICAL and portENTER_CRITICAL_ISR. vTaskEnterCritical has to be used in way more places than before, and some are called - both from ISR as well as non-ISR code, thus we re-organized + both from ISR as well as non-ISR code, thus we re-organized vTaskEnterCritical to also work in ISRs. */ #if 0 if( pxCurrentTCB[ xPortGetCoreID() ]->uxCriticalNesting == 1 ) @@ -4177,7 +4207,7 @@ For ESP32 FreeRTOS, vTaskExitCritical implements both portEXIT_CRITICAL and port mtCOVERAGE_TEST_MARKER(); } } - + #endif /* portCRITICAL_NESTING_IN_TCB */ /*-----------------------------------------------------------*/ @@ -4508,6 +4538,7 @@ TickType_t uxReturn; of a delayed task list to ensure the task is not woken by a timing event. It will block indefinitely. */ + traceMOVED_TASK_TO_SUSPENDED_LIST(pxCurrentTCB); vListInsertEnd( &xSuspendedTaskList, &( pxCurrentTCB[ xPortGetCoreID() ]->xGenericListItem ) ); } else @@ -4624,6 +4655,7 @@ TickType_t uxReturn; of a delayed task list to ensure the task is not woken by a timing event. It will block indefinitely. */ + traceMOVED_TASK_TO_SUSPENDED_LIST(pxCurrentTCB); vListInsertEnd( &xSuspendedTaskList, &( pxCurrentTCB[ xPortGetCoreID() ]->xGenericListItem ) ); } else @@ -4929,7 +4961,7 @@ TickType_t uxReturn; this task pending until the scheduler is resumed. */ vListInsertEnd( &( xPendingReadyList[ xPortGetCoreID() ] ), &( pxTCB->xEventListItem ) ); } - + if( tskCAN_RUN_HERE(pxTCB->xCoreID) && pxTCB->uxPriority > pxCurrentTCB[ xPortGetCoreID() ]->uxPriority ) { /* The notified task has a priority above the currently @@ -4956,6 +4988,22 @@ TickType_t uxReturn; #if ( configENABLE_TASK_SNAPSHOT == 1 ) + static void prvTaskGetSnapshot( TaskSnapshot_t *pxTaskSnapshotArray, UBaseType_t *uxTask, TCB_t *pxTCB ) + { + pxTaskSnapshotArray[ *uxTask ].pxTCB = pxTCB; + pxTaskSnapshotArray[ *uxTask ].pxTopOfStack = (StackType_t *)pxTCB->pxTopOfStack; + #if( portSTACK_GROWTH < 0 ) + { + pxTaskSnapshotArray[ *uxTask ].pxEndOfStack = pxTCB->pxEndOfStack; + } + #else + { + pxTaskSnapshotArray[ *uxTask ].pxEndOfStack = pxTCB->pxStack; + } + #endif + (*uxTask)++; + } + static void prvTaskGetSnapshotsFromList( TaskSnapshot_t *pxTaskSnapshotArray, UBaseType_t *uxTask, const UBaseType_t uxArraySize, List_t *pxList ) { TCB_t *pxNextTCB, *pxFirstTCB; @@ -4970,20 +5018,7 @@ TickType_t uxReturn; if( *uxTask >= uxArraySize ) break; - pxTaskSnapshotArray[ *uxTask ].pxTCB = pxNextTCB; - pxTaskSnapshotArray[ *uxTask ].pxTopOfStack = (StackType_t *)pxNextTCB->pxTopOfStack; - #if( portSTACK_GROWTH < 0 ) - { - pxTaskSnapshotArray[ *uxTask ].pxEndOfStack = pxNextTCB->pxEndOfStack; - } - #else - { - pxTaskSnapshotArray[ *uxTask ].pxEndOfStack = pxNextTCB->pxStack; - } - #endif - - (*uxTask)++; - + prvTaskGetSnapshot( pxTaskSnapshotArray, uxTask, pxNextTCB ); } while( pxNextTCB != pxFirstTCB ); } else @@ -4996,35 +5031,41 @@ TickType_t uxReturn; { UBaseType_t uxTask = 0, i = 0; +PRIVILEGED_DATA TCB_t * volatile pxCurrentTCB[ portNUM_PROCESSORS ] = { NULL }; + + *pxTcbSz = sizeof(TCB_t); - + /* Fill in an TaskStatus_t structure with information on each + task in the Ready state. */ + i = configMAX_PRIORITIES; + do { - /* Fill in an TaskStatus_t structure with information on each - task in the Ready state. */ - i = configMAX_PRIORITIES; - do - { - i--; - prvTaskGetSnapshotsFromList( pxTaskSnapshotArray, &uxTask, uxArraySize, &( pxReadyTasksLists[ i ] ) ); - } while( i > ( UBaseType_t ) tskIDLE_PRIORITY ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ + i--; + prvTaskGetSnapshotsFromList( pxTaskSnapshotArray, &uxTask, uxArraySize, &( pxReadyTasksLists[ i ] ) ); + } while( i > ( UBaseType_t ) tskIDLE_PRIORITY ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ - /* Fill in an TaskStatus_t structure with information on each - task in the Blocked state. */ - prvTaskGetSnapshotsFromList( pxTaskSnapshotArray, &uxTask, uxArraySize, ( List_t * ) pxDelayedTaskList ); - prvTaskGetSnapshotsFromList( pxTaskSnapshotArray, &uxTask, uxArraySize, ( List_t * ) pxOverflowDelayedTaskList ); + /* Fill in an TaskStatus_t structure with information on each + task in the Blocked state. */ + prvTaskGetSnapshotsFromList( pxTaskSnapshotArray, &uxTask, uxArraySize, ( List_t * ) pxDelayedTaskList ); + prvTaskGetSnapshotsFromList( pxTaskSnapshotArray, &uxTask, uxArraySize, ( List_t * ) pxOverflowDelayedTaskList ); + for (i = 0; i < portNUM_PROCESSORS; i++) { + if( uxTask >= uxArraySize ) + break; + prvTaskGetSnapshot( pxTaskSnapshotArray, &uxTask, pxCurrentTCB[ i ] ); + prvTaskGetSnapshotsFromList( pxTaskSnapshotArray, &uxTask, uxArraySize, &( xPendingReadyList[ i ] ) ); + } - #if( INCLUDE_vTaskDelete == 1 ) - { - prvTaskGetSnapshotsFromList( pxTaskSnapshotArray, &uxTask, uxArraySize, &xTasksWaitingTermination ); - } - #endif - - #if ( INCLUDE_vTaskSuspend == 1 ) - { - prvTaskGetSnapshotsFromList( pxTaskSnapshotArray, &uxTask, uxArraySize, &xSuspendedTaskList ); - } - #endif + #if( INCLUDE_vTaskDelete == 1 ) + { + prvTaskGetSnapshotsFromList( pxTaskSnapshotArray, &uxTask, uxArraySize, &xTasksWaitingTermination ); } + #endif + + #if ( INCLUDE_vTaskSuspend == 1 ) + { + prvTaskGetSnapshotsFromList( pxTaskSnapshotArray, &uxTask, uxArraySize, &xSuspendedTaskList ); + } + #endif return uxTask; } diff --git a/components/freertos/timers.c b/components/freertos/timers.c index 92e4bf94ad..2c66f072bf 100644 --- a/components/freertos/timers.c +++ b/components/freertos/timers.c @@ -780,9 +780,9 @@ static void prvCheckForValidListAndQueue( void ) /* Check that the list from which active timers are referenced, and the queue used to communicate with the timer service, have been initialised. */ - + /* Erm, yes, this is a problem. We can't lock until the lock is initialized, and we can't initialize the lock - atomically because we don't have a lock yet... I'm pretty sure doubly-initializing a lock on 2 cpus + atomically because we don't have a lock yet... I'm pretty sure doubly-initializing a lock on 2 cpus is no problem in the current implementation, but this is not a nice way to solve things. ToDo - improve. */ if( xTimerQueue == NULL ) vPortCPUInitializeMutex( &xTimerMux ); diff --git a/components/freertos/xtensa_intr.c b/components/freertos/xtensa_intr.c index 4767032277..856096d55e 100644 --- a/components/freertos/xtensa_intr.c +++ b/components/freertos/xtensa_intr.c @@ -138,6 +138,21 @@ xt_handler xt_set_interrupt_handler(int n, xt_handler f, void * arg) return ((old == &xt_unhandled_interrupt) ? 0 : old); } +#if CONFIG_SYSVIEW_ENABLE +void * xt_get_interrupt_handler_arg(int n) +{ + xt_handler_table_entry * entry; + + if( n < 0 || n >= XCHAL_NUM_INTERRUPTS ) + return 0; /* invalid interrupt number */ + + /* Convert exception number to _xt_exception_table name */ + n = n * portNUM_PROCESSORS + xPortGetCoreID(); + + entry = _xt_interrupt_table + n; + return entry->arg; +} +#endif #endif /* XCHAL_HAVE_INTERRUPTS */ diff --git a/docs/Doxyfile b/docs/Doxyfile index b5ca4b7f84..9cd987fb58 100644 --- a/docs/Doxyfile +++ b/docs/Doxyfile @@ -1,7 +1,7 @@ # This is Doxygen configuration file # # Doxygen provides over 260 configuration statements -# To make this file easier to follow, +# To make this file easier to follow, # it contains only statements that are non-default # # NOTE: @@ -17,7 +17,7 @@ PROJECT_NAME = "ESP32 Programming Guide" ## The 'INPUT' statement below is used as input by script 'gen-df-input.py' ## to automatically generate API reference list files heder_file.inc -## These files are placed in '_inc' directory +## These files are placed in '_inc' directory ## and used to include in API reference documentation INPUT = \ @@ -126,10 +126,14 @@ INPUT = \ ## ULP Coprocessor - API Guides ## ## NOTE: for line below header_file.inc is not used - ../components/ulp/include/esp32/ulp.h + ../components/ulp/include/esp32/ulp.h \ + ## + ## Application Level Tracing - API Reference + ## + ../components/app_trace/include/esp_app_trace.h -## Get warnings for functions that have no documentation for their parameters or return value +## Get warnings for functions that have no documentation for their parameters or return value ## WARN_NO_PARAMDOC = YES diff --git a/docs/_static/app_trace/overview.png b/docs/_static/app_trace/overview.png new file mode 100644 index 0000000000..7e4e94b038 Binary files /dev/null and b/docs/_static/app_trace/overview.png differ diff --git a/docs/api-guides/SYSVIEW_FreeRTOS.txt b/docs/api-guides/SYSVIEW_FreeRTOS.txt new file mode 100644 index 0000000000..b19b47572b --- /dev/null +++ b/docs/api-guides/SYSVIEW_FreeRTOS.txt @@ -0,0 +1,104 @@ +128 vTaskAllocateMPURegions xTask=%t pxRegions=%u +33 vTaskDelete xTaskToDelete=%t +34 vTaskDelay xTicksToDelay=%u +35 vTaskDelayUntil +129 uxTaskPriorityGet xTask=%t +56 uxTaskPriorityGetFromISR xTask=%t +130 eTaskGetState xTask=%t +55 vTaskPrioritySet xTask=%t uxNewPriority=%u +36 vTaskSuspend xTaskToSuspend=%t +40 vTaskResume xTaskToResume=%t +43 xTaskResumeFromISR xTaskToResume=%t +131 vTaskStartScheduler +132 vTaskEndScheduler +133 vTaskSuspendAll +134 xTaskResumeAll +135 xTaskGetTickCount +57 xTaskGetTickCountFromISR +136 uxTaskGetNumberOfTasks +137 pcTaskGetTaskName xTaskToQuery=%t +138 uxTaskGetStackHighWaterMark xTask=%t +139 vTaskSetApplicationTaskTag xTask=%t pxHookFunction=%u +140 xTaskGetApplicationTaskTag xTask=%t +141 vTaskSetThreadLocalStoragePointer xTaskToSet=%T xIndex=%u pvValue=%u +142 pvTaskGetThreadLocalStoragePointer xTaskToQuery=%T xIndex=%u +143 xTaskCallApplicationTaskHook xTask=%T pvParameter=%u +144 xTaskGetIdleTaskHandle +145 uxTaskGetSystemState pxTaskStatusArray=%u uxArraySize=%u pulTotalRunTime=%u +146 vTaskList pcWriteBuffer=%u +147 vTaskGetRunTimeStats pcWriteBuffer=%u +44 xTaskGenericNotify xTaskToNotify=%t ulValue=%u eAction=%u pulPreviousNotificationValue=%u +45 xTaskGenericNotifyFromISR xTaskToNotify=%t ulValue=%u eAction=%u pulPreviousNotificationValue=%u pxHigherPriorityTaskWoken=%u +46 xTaskNotifyWait ulBitsToClearOnEntry=%u ulBitsToClearOnExit=%u pulNotificationValue=%u xTicksToWait=%u +38 vTaskNotifyGiveFromISR xTaskToNotify=%t pxHigherPriorityTaskWoken=%u +37 ulTaskNotifyTake xClearCountOnExit=%u xTicksToWait=%u +148 xTaskNotifyStateClear xTask=%t +149 xTaskGetCurrentTaskHandle +150 vTaskSetTimeOutState pxTimeOut=%u +151 xTaskCheckForTimeOut pxTimeOut=%u pxTicksToWait=%u +152 vTaskMissedYield +153 xTaskGetSchedulerState +39 vTaskPriorityInherit pxMutexHolder=%p +42 xTaskPriorityDisinherit pxMutexHolder=%p +154 xTaskGenericCreate pxTaskCode=%u pcName=%u usStackDepth=%u pvParameters=%u uxPriority=%u pxCreatedTask=%u puxStackBuffer=%u xRegions=%u +155 uxTaskGetTaskNumber xTask=%u +156 vTaskSetTaskNumber xTask=%u uxHandle=%u +41 vTaskStepTick xTicksToJump=%u +157 eTaskConfirmSleepModeStatus +158 xTimerCreate pcTimerName=%u xTimerPeriodInTicks=%u uxAutoReload=%u pvTimerID=%u pxCallbackFunction=%u +159 pvTimerGetTimerID xTimer=%u +160 vTimerSetTimerID xTimer=%u pvNewID=%u +161 xTimerIsTimerActive xTimer=%u +162 xTimerGetTimerDaemonTaskHandle +163 xTimerPendFunctionCallFromISR xFunctionToPend=%u pvParameter1=%u ulParameter2=%u pxHigherPriorityTaskWoken=%u +164 xTimerPendFunctionCall xFunctionToPend=%u pvParameter1=%u ulParameter2=%u xTicksToWait=%u +165 pcTimerGetTimerName xTimer=%u +166 xTimerCreateTimerTask +167 xTimerGenericCommand xTimer=%u xCommandID=%u xOptionalValue=%u pxHigherPriorityTaskWoken=%u xTicksToWait=%u +53 xQueueGenericSend xQueue=%I pvItemToQueue=%p xTicksToWait=%u xCopyPosition=%u +50 xQueuePeekFromISR xQueue=%I pvBuffer=%p +49 xQueueGenericReceive xQueue=%I pvBuffer=%p xTicksToWait=%u xJustPeek=%u +168 uxQueueMessagesWaiting xQueue=%I +169 uxQueueSpacesAvailable xQueue=%I +48 vQueueDelete xQueue=%I +54 xQueueGenericSendFromISR xQueue=%I pvItemToQueue=%p pxHigherPriorityTaskWoken=%u xCopyPosition=%u +61 xQueueGiveFromISR xQueue=%I pxHigherPriorityTaskWoken=%u +51 xQueueReceiveFromISR xQueue=%I pvBuffer=%p pxHigherPriorityTaskWoken=%u +62 xQueueIsQueueEmptyFromISR xQueue=%I +63 xQueueIsQueueFullFromISR xQueue=%I +170 uxQueueMessagesWaitingFromISR xQueue=%I +171 xQueueAltGenericSend xQueue=%I pvItemToQueue=%p xTicksToWait=%u xCopyPosition=%u +172 xQueueAltGenericReceive xQueue=%I pvBuffer=%p xTicksToWait=%u xJustPeeking=%u +173 xQueueCRSendFromISR xQueue=%I pvItemToQueue=%p xCoRoutinePreviouslyWoken=%u +174 xQueueCRReceiveFromISR xQueue=%I pvBuffer=%p pxTaskWoken=%u +175 xQueueCRSend xQueue=%I pvItemToQueue=%p xTicksToWait=%u +176 xQueueCRReceive xQueue=%I pvBuffer=%p xTicksToWait=%u +177 xQueueCreateMutex ucQueueType=%u +178 xQueueCreateCountingSemaphore uxMaxCount=%u uxInitialCount=%u +179 xQueueGetMutexHolder xSemaphore=%u +180 xQueueTakeMutexRecursive xMutex=%u xTicksToWait=%u +181 xQueueGiveMutexRecursive pxMutex=%u +52 vQueueAddToRegistry xQueue=%I pcName=%u +182 vQueueUnregisterQueue xQueue=%I +47 xQueueGenericCreate uxQueueLength=%u uxItemSize=%u ucQueueType=%u +183 xQueueCreateSet uxEventQueueLength=%u +184 xQueueAddToSet xQueueOrSemaphore=%u xQueueSet=%u +185 xQueueRemoveFromSet xQueueOrSemaphore=%u xQueueSet=%u +186 xQueueSelectFromSet xQueueSet=%u xTicksToWait=%u +187 xQueueSelectFromSetFromISR xQueueSet=%u +188 xQueueGenericReset xQueue=%I xNewQueue=%u +189 vListInitialise pxList=%u +190 vListInitialiseItem pxItem=%u +191 vListInsert pxList=%u pxNewListItem=%u +192 vListInsertEnd pxList=%u pxNewListItem=%u +193 uxListRemove pxItemToRemove=%u +194 xEventGroupCreate +195 xEventGroupWaitBits xEventGroup=%u uxBitsToWaitFor=%u xClearOnExit=%u xWaitForAllBits=%u xTicksToWait=%u +196 xEventGroupClearBits xEventGroup=%u uxBitsToClear=%u +58 xEventGroupClearBitsFromISR xEventGroup=%u uxBitsToSet=%u +197 xEventGroupSetBits xEventGroup=%u uxBitsToSet=%u +59 xEventGroupSetBitsFromISR xEventGroup=%u uxBitsToSet=%u pxHigherPriorityTaskWoken=%u +198 xEventGroupSync xEventGroup=%u uxBitsToSet=%u uxBitsToWaitFor=%u xTicksToWait=%u +60 xEventGroupGetBitsFromISR xEventGroup=%u +199 vEventGroupDelete xEventGroup=%u +200 uxEventGroupGetNumber xEventGroup=%u diff --git a/docs/api-guides/app_trace.rst b/docs/api-guides/app_trace.rst new file mode 100644 index 0000000000..0c72ec9d94 --- /dev/null +++ b/docs/api-guides/app_trace.rst @@ -0,0 +1,365 @@ +Application Level Tracing library +================================= + +Overview +-------- + +IDF provides useful feature for program behaviour analysis: application level tracing. It is implemented in the corresponding library and can be enabled via menuconfig. This feature allows to transfer arbitrary data between host and ESP32 via JTAG interface with small overhead on program execution. +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: + +1. System behaviour analysis. See `System Behaviour Analysis with SEGGER SystemView`_. +2. Lightweight logging to the host. See `Logging to Host`_. +3. Collecting application specific data. See `Application Specific Tracing`_. + +Tracing components when working over JTAG interface are shown in the figure below. + +.. figure:: ../_static/app_trace/overview.png + :align: center + :alt: Tracing Components when Working Over JTAG + :figclass: align-center + + Tracing Components when Working Over JTAG + +.. note:: + + Currently only JTAG interface is supported as transport. + +Modes of operation +------------------ + +The library supports two modes of operation: + + - **Post-mortem mode.** This is the default mode. The mode does not need interaction from 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 behaviour 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 ESP32. In this mode before writing new data to *HW UP BUFFER* 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 controled via timeout values passed by users to corresponding API routines. So when application tries to write data to trace buffer using finite value of the maximum waiting time it is possible situation that this data will be dropped. Especially this is 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 ``CONFIG_ESP32_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 etc. But it will not help when average bitrate of trace data stream exceeds HW interface capabilities. + +Config Options and Dependencies +------------------------------- + +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 how to set it up, please, see :doc:`Debugging <../api-guides/openocd>` for details. +2. **Target side:** Application tracing functionality can be enabled by ``CONFIG_ESP32_APPTRACE_ENABLE`` macro via menuconfig. This option enables the module and makes tracing API available for users. Actually there is menu which allows selecting destination for the trace data (HW interface for transport). So choosing one of the destinations automatically enables ``CONFIG_ESP32_APPTRACE_ENABLE`` option. + +.. note:: + + In order to achieve higher data rates and minimize number of dropped packets it is recommended to modify JTAG adapter working frequency in OpenOCD config file ``$IDF_PATH/docs/esp32.cfg``. Maximum tested stable speed on ESP-WROVER-KIT board is 26MHz, so for this board you need to have the following statement in your configuration file ``adapter_khz 26000`` instead of the default ``adapter_khz 200``. Actually maximum stable JTAG frequency can depend on the host system configuration. In general JTAG clock shuld not exceed APB clock / 4. + +There are two additional menuconfig options not mentioned above: + +1. ``CONFIG_ESP32_APPTRACE_POSTMORTEM_FLUSH_TRAX_THRESH``. This option is necessary due to the nature of working over JTAG. In that mode trace data are exposed to the host in 16KB 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 16KB granularity. On panic the latest data from the current input block are exposed to host and host can read them for post-analysis. It can happen that system panic occurs when there are very small amount of data which are not exposed to the host yet. In this case the previous 16KB 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 16KB. The option is only meaningful in post-mortem mode and when working over JTAG. +2. ``CONFIG_ESP32_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. + + +How to use this library +----------------------- + +This library provides API for transferring arbitrary data between host and ESP32. 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. + +Application Specific Tracing +^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +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. Piece of code below shows an example how to do this. + +.. code-block:: c + + #include "esp_app_trace.h" + ... + char buf[] = "Hello World!"; + esp_err_t res = esp_apptrace_write(ESP_APPTRACE_DEST_TRAX, buf, strlen(buf), ESP_APPTRACE_TMO_INFINITE); + if (res != ESP_OK) { + ESP_LOGE(TAG, "Failed to write data to host!"); + return res; + } + +``esp_apptrace_write()`` function uses memcpy to copy user data to the internal buffer. In some cases it can be more optimal to use ``esp_apptrace_buffer_get()`` and ``esp_apptrace_buffer_put()`` functions. They allow developers to allocate buffer and fill it themselves. The following piece of code shows how to do this. + +.. code-block:: c + + #include "esp_app_trace.h" + ... + int number = 10; + char *ptr = (char *)esp_apptrace_buffer_get(32, 100/*tmo in us*/); + if (ptr == NULL) { + ESP_LOGE("Failed to get buffer!"); + return ESP_FAIL; + } + sprintf(ptr, "Here is the number %d", number); + esp_err_t res = esp_apptrace_buffer_put(ptr, 100/*tmo in us*/); + if (res != ESP_OK) { + /* in case of error host tracing tool (e.g. OpenOCD) will report incomplete user buffer */ + ESP_LOGE("Failed to put buffer!"); + return res; + } + +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 + + #include "esp_app_trace.h" + ... + char buf[32]; + size_t sz = sizeof(buf); + /* check for incoming data and read them if any */ + esp_err_t res = esp_apptrace_read(ESP_APPTRACE_DEST_TRAX, buf, &sz, 0/*do not wait*/); + if (res != ESP_OK) { + ESP_LOGE(TAG, "Failed to read data from host!"); + return res; + } + if (sz > 0) { + /* we have data, process them */ + ... + } + +2. The next step is to build the program image and download it to the target as described in :doc:`Build and Flash <../get-started/make-project>`. +3. Run OpenOCD (see :doc:`Debugging <../api-guides/openocd>`). +4. Connect to OpenOCD telnet server. On Linux it can be done using the following command in terminal ``telnet 4444``. If telnet session is opened on the same machine which runs OpenOCD you can use ``localhost`` as ```` in the command above. +5. Start trace data collection using special OpenOCD command. This command will transfer tracing data and redirect them to specified file or socket (currently only files are supported as trace data destination). For description of the corresponding commands see `OpenOCD Application Level Tracing Commands`_. +6. The final step is to process received data. Since format of data is defined by user the processing stage is out of the scope of this document. Good starting points for data processor are python scripts in ``$IDF_PATH/tools/esp_app_trace``: ``apptrace_proc.py`` (used for feature tests) and ``logtrace_proc.py`` (see more details in section `Logging to Host`_). + +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 multithreading environment it can happen that task/ISR which fills the buffer is preempted by another high prio 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. + +Command usage: + +``esp108 apptrace [start ] | [stop] | [status] | [dump ]`` + +Sub-commands: + + .. list-table:: + :widths: 20 80 + :header-rows: 1 + + * - Sub-command + - Description + * - start + - Start tracing (continuous streaming). + * - stop + - Stop tracing. + * - status + - Get tracing status. + * - dump + - Dump all data from *HW UP BUFFER* (post-mortem dump). + +Start command syntax: + + ``start [outfile2] [poll_period [trace_size [stop_tmo [wait4halt [skip_size]]]]`` + + .. list-table:: + :widths: 20 80 + :header-rows: 1 + + * - Argument + - Description + * - outfile1 + - Path to file to save data from PRO CPU. This argument should have the following format: ``file://path/to/file``. + * - 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). 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 + - Idle timeout (in sec). Tracing is stopped if there is no data for specified period of time. By default -1 (disable this stop trigger). + * - 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. + * - skip_size + - Number of bytes to skip at the start. By default 0. + +.. note:: + + If ``poll_period`` is 0 OpenOCD telnet command line will not be avalable until tracing is stopped. You must stop it manually by resetting the board or pressing CTRL+C in OpenOCD window (not one with the telnet session). + +Logging to Host +^^^^^^^^^^^^^^^ + +IDF implements useful feature: logging to host via application level tracing library. This is a kind of semihosting when all ESP_LOGx calls sends 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 vprintf-like function to write formatted output to dedicated UART. In general it invloves 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 implementation of vprintf-like function can be optimised to a certain level, all steps above have to be peformed in any case and every step takes some time (especially item 3). So it is frequent situation when addition of extra logging to the program to diagnose some problem changes its behaviour and problem dissapears or in the worst cases program can not 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 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 +""""""""""" + +Curent implmentation of logging over JTAG has several limitations: + +1. Tracing from ``ESP_EARLY_LOGx`` macros is not supported. +2. No support for printf arguments which size exceeds 4 bytes (e.g. ``double`` and ``uint64_t``). +3. Only strings from .rodata section are supported as format strings and arguments. +4. Maximum number of printf arguments is 256. + +How To Use It +""""""""""""" + +In order to use logging via trace module user needs to perform the following steps: + +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 shown below. + +.. code-block:: c + + #include "esp_app_trace.h" + ... + void app_main() + { + // set log vprintf handler + esp_log_set_vprintf(esp_apptrace_vprintf); + ... + // user code using ESP_LOGx starts here + // all data passed to ESP_LOGx are sent to host + ... + // restore log vprintf handler + esp_log_set_vprintf(vprintf); + // flush last data to host + esp_apptrace_flush(ESP_APPTRACE_DEST_TRAX, 100000 /*tmo in us*/); + ESP_LOGI(TAG, "Tracing is finished."); // this will be printed out to UART + while (1); + } + +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``. + +Log Trace Processor Command Options +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Command usage: + +``logtrace_proc.py [-h] [--no-errors] `` + +Positional arguments: + + .. list-table:: + :widths: 20 80 + :header-rows: 1 + + * - Argument + - Description + * - trace_file + - Path to log trace file + * - elf_file + - Path to program ELF file + +Optional arguments: + + .. list-table:: + :widths: 20 80 + :header-rows: 1 + + * - Argument + - Description + * - -h, --help + - show this help message and exit + * - --no-errors, -n + - Do not print errors + +System Behaviour 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 `_). SEGGER SystemView is a real-time recording and visualization tool that allows to analyze runtime behavior of an application. + +.. note:: + + Currently IDF-based application is able to generate SystemView compatible traces, but tracing process can not be controlled using that tool. + +How To Use It +""""""""""""" + +Support for this feature is enabled by ``CONFIG_SYSVIEW_ENABLE`` menuconfig option. It also enables a bunch of options related to that type of tracing: + +1. ``CONFIG_SYSVIEW_TS_SOURCE`` selects the source of timestamps for SystemView events. In single core mode timestamps are generated using ESP32 internal cycle counter running at maximum 240 Mhz (~4ns granularity). In dual-core mode external timer working at 40Mhz is used, so timestamp granularity is 25 ns. +2. ``CONFIG_SYSVIEW_EVT_XXX`` enables or disables particular SystemView event. + +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. + +OpenOCD SystemView Tracing Command Options +""""""""""""""""""""""""""""""""""""""""""" + +Command usage: + +``esp108 sysview [start ] | [stop] | [status]`` + +Sub-commands: + + .. list-table:: + :widths: 20 80 + :header-rows: 1 + + * - Sub-command + - Description + * - start + - Start tracing (continuous streaming). + * - stop + - Stop tracing. + * - status + - Get tracing status. + +Start command syntax: + + ``start [outfile2] [poll_period [trace_size [stop_tmo]]]`` + + .. list-table:: + :widths: 20 80 + :header-rows: 1 + + * - Argument + - Description + * - outfile1 + - Path to file to save data from PRO CPU. This argument should have the following format: ``file://path/to/file``. + * - 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). 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 + - Idle timeout (in sec). Tracing is stopped if there is no data for specified period of time. By default -1 (disable this stop trigger). + +.. note:: + + If ``poll_period`` is 0 OpenOCD telnet command line will not be avalable until tracing is stopped. You must stop it manually by resetting the board or pressing CTRL+C in OpenOCD window (not one with the telnet session). + +Data Visualization +"""""""""""""""""" + +After trace data are collected user can use special tool to visuailize the results and inspect behaviour of the program. Unfortunately SystemView does not support tracing from multiple cores. So when tracing from ESP32 working 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. 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 its possible to inspect events from both cores in one view. Also this plugin has no limitation of 1000000 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 `_. + +.. note:: + + IDF uses its own mapping for SystemView FreeRTOS events IDs, so user needs to replace original file with mapping ``$SYSVIEW_INSTALL_DIR/Description/SYSVIEW_FreeRTOS.txt`` with ``$IDF_PATH/docs/api-guides/SYSVIEW_FreeRTOS.txt``. + Also contents of that IDF specific file should be used when configuring SystemView serializer using above link. + +Configure Impulse for Dual Core Traces +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +After installing Impulse and ensuring that it can succussefully load trace files for each core in separate tabs user can add special Multi Adapter port and load both files into one view. To do this user needs to do the following in Eclipse: + +1. Open 'Signal Ports' view. Go to Windows->Show View->Other menu. Find 'Signal Ports' view in Impulse folder and double-click on it. +2. In 'Signal Ports' view right-click on 'Ports' and select 'Add ...'->New Multi Adapter Port +3. In open dialog Press 'Add' button and select 'New Pipe/File'. +4. In open dialog select 'SystemView Serializer' as Serializer and set path to PRO CPU trace file. Press OK. +5. Repeat steps 3-4 for APP CPU trace file. +6. Double-click on created port. View for this port should open. +7. Click Start/Stop Streaming button. Data should be loaded. +8. Use 'Zoom Out', 'Zoom In' and 'Zoom Fit' button to inspect data. +9. For settings measurement cursors and other features please see `Impulse documentation `_). + +.. note:: + + If you have problems with visualization (no data are shown or strange behaviour of zoom action is observed) you can try to delete current signal hierarchy and double click on necessary file or port. Eclipse will ask you to create new signal hierarchy. diff --git a/docs/api-guides/index.rst b/docs/api-guides/index.rst index f0b02d1e8b..8ce25d111a 100644 --- a/docs/api-guides/index.rst +++ b/docs/api-guides/index.rst @@ -14,4 +14,4 @@ API Guides Deep Sleep Wake Stubs ULP Coprocessor Unit Testing - + Application Level Tracing diff --git a/docs/api-reference/system/app_trace.rst b/docs/api-reference/system/app_trace.rst new file mode 100644 index 0000000000..cfd02efc93 --- /dev/null +++ b/docs/api-reference/system/app_trace.rst @@ -0,0 +1,44 @@ +Application Level Tracing +========================= + +Overview +-------- + +IDF provides useful feature for program behaviour analysis: application level tracing. It is implemented in the corresponding library and can be enabled via menuconfig. This feature allows to transfer arbitrary data between host and ESP32 via JTAG interface with small overhead on program execution. +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: + +1. System behaviour analysis. +2. Lightweight logging to the host. +3. Collecting application specific data. + +API Reference +------------- + +Header Files +^^^^^^^^^^^^ + + * :component_file:`app_trace/include/esp_app_trace.h` + +Macros +^^^^^^ + +.. doxygendefine:: ESP_APPTRACE_TMO_INFINITE + +Enumerations +^^^^^^^^^^^^ + +.. doxygenenum:: esp_apptrace_dest_t + + +Functions +^^^^^^^^^ + +.. doxygenfunction:: esp_apptrace_init +.. doxygenfunction:: esp_apptrace_buffer_get +.. doxygenfunction:: esp_apptrace_buffer_put +.. doxygenfunction:: esp_apptrace_write +.. doxygenfunction:: esp_apptrace_vprintf_to +.. doxygenfunction:: esp_apptrace_vprintf +.. doxygenfunction:: esp_apptrace_read +.. doxygenfunction:: esp_apptrace_flush +.. doxygenfunction:: esp_apptrace_flush_nolock diff --git a/docs/api-reference/system/index.rst b/docs/api-reference/system/index.rst index a41005bea4..aeee1bef95 100644 --- a/docs/api-reference/system/index.rst +++ b/docs/api-reference/system/index.rst @@ -11,6 +11,7 @@ System API Deep Sleep Logging Base MAC address + Application Level Tracing Example code for this API section is provided in :example:`system` directory of ESP-IDF examples. diff --git a/examples/get-started/blink/main/blink.c b/examples/get-started/blink/main/blink.c index 698bad218a..5ca22bbde0 100644 --- a/examples/get-started/blink/main/blink.c +++ b/examples/get-started/blink/main/blink.c @@ -40,5 +40,5 @@ void blink_task(void *pvParameter) void app_main() { - xTaskCreate(&blink_task, "blink_task", 512, NULL, 5, NULL); + xTaskCreate(&blink_task, "blink_task", 2048, NULL, 5, NULL); } diff --git a/tools/unit-test-app/sdkconfig b/tools/unit-test-app/sdkconfig index abbb292290..76cafd6699 100644 --- a/tools/unit-test-app/sdkconfig +++ b/tools/unit-test-app/sdkconfig @@ -87,6 +87,17 @@ CONFIG_OPTIMIZATION_LEVEL_DEBUG=y # # Component config # + +# +# Application Level Tracing +# +# CONFIG_ESP32_APPTRACE_DEST_TRAX is not set +CONFIG_ESP32_APPTRACE_DEST_NONE=y +# CONFIG_ESP32_APPTRACE_ENABLE is not set + +# +# FreeRTOS SystemView Tracing +# # CONFIG_AWS_IOT_SDK is not set # CONFIG_BT_ENABLED is not set CONFIG_BT_RESERVE_DRAM=0 @@ -107,10 +118,6 @@ CONFIG_TRACEMEM_RESERVE_DRAM=0x0 # CONFIG_ESP32_ENABLE_COREDUMP_TO_UART is not set CONFIG_ESP32_ENABLE_COREDUMP_TO_NONE=y # CONFIG_ESP32_ENABLE_COREDUMP is not set -# CONFIG_ESP32_APPTRACE_DEST_TRAX is not set -# CONFIG_ESP32_APPTRACE_DEST_UART is not set -CONFIG_ESP32_APPTRACE_DEST_NONE=y -# CONFIG_ESP32_APPTRACE_ENABLE is not set # CONFIG_TWO_UNIVERSAL_MAC_ADDRESS is not set CONFIG_FOUR_UNIVERSAL_MAC_ADDRESS=y CONFIG_NUMBER_OF_UNIVERSAL_MAC_ADDRESS=4 @@ -206,7 +213,7 @@ CONFIG_FREERTOS_ASSERT_ON_UNTESTED_FUNCTION=y # CONFIG_FREERTOS_CHECK_STACKOVERFLOW_NONE is not set # CONFIG_FREERTOS_CHECK_STACKOVERFLOW_PTRVAL is not set CONFIG_FREERTOS_CHECK_STACKOVERFLOW_CANARY=y -# CONFIG_FREERTOS_WATCHPOINT_END_OF_STACK is not set +CONFIG_FREERTOS_WATCHPOINT_END_OF_STACK=y CONFIG_FREERTOS_THREAD_LOCAL_STORAGE_POINTERS=3 CONFIG_FREERTOS_ASSERT_FAIL_ABORT=y # CONFIG_FREERTOS_ASSERT_FAIL_PRINT_CONTINUE is not set