1 /*
2  * Copyright (c) 2018 Intel Corporation
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 #include <zephyr/kernel.h>
7 #include <zephyr/kernel_structs.h>
8 #include <zephyr/init.h>
9 #include <ksched.h>
10 
11 #include <SEGGER_SYSVIEW.h>
12 
13 #define NAMED_EVENT_MAXSTR 20 /* Maximum string length supported by named event */
14 
15 static uint32_t interrupt;
16 
sysview_get_timestamp(void)17 uint32_t sysview_get_timestamp(void)
18 {
19 	return k_cycle_get_32();
20 }
21 
sysview_get_interrupt(void)22 uint32_t sysview_get_interrupt(void)
23 {
24 #ifdef CONFIG_CPU_CORTEX_M
25 	interrupt = ((SCB->ICSR & SCB_ICSR_VECTACTIVE_Msk) >>
26 		     SCB_ICSR_VECTACTIVE_Pos);
27 #endif
28 	return interrupt;
29 }
30 
sys_trace_k_thread_switched_in(void)31 void sys_trace_k_thread_switched_in(void)
32 {
33 	struct k_thread *thread;
34 
35 	thread = k_current_get();
36 
37 	if (z_is_idle_thread_object(thread)) {
38 		SEGGER_SYSVIEW_OnIdle();
39 	} else {
40 		SEGGER_SYSVIEW_OnTaskStartExec((uint32_t)(uintptr_t)thread);
41 	}
42 }
43 
sys_trace_k_thread_switched_out(void)44 void sys_trace_k_thread_switched_out(void)
45 {
46 	SEGGER_SYSVIEW_OnTaskStopExec();
47 }
48 
sys_trace_isr_enter(void)49 void sys_trace_isr_enter(void)
50 {
51 	SEGGER_SYSVIEW_RecordEnterISR();
52 }
53 
sys_trace_isr_exit(void)54 void sys_trace_isr_exit(void)
55 {
56 	SEGGER_SYSVIEW_RecordExitISR();
57 }
58 
sys_trace_isr_exit_to_scheduler(void)59 void sys_trace_isr_exit_to_scheduler(void)
60 {
61 	SEGGER_SYSVIEW_RecordExitISRToScheduler();
62 }
63 
sys_trace_idle(void)64 void sys_trace_idle(void)
65 {
66 	SEGGER_SYSVIEW_OnIdle();
67 }
68 
sys_trace_named_event(const char * name,uint32_t arg0,uint32_t arg1)69 void sys_trace_named_event(const char *name, uint32_t arg0, uint32_t arg1)
70 {
71 	/* Based on SEGGER provided code for user defined packets */
72 	uint8_t a_packet[SEGGER_SYSVIEW_INFO_SIZE + 2 *
73 		SEGGER_SYSVIEW_QUANTA_U32 + NAMED_EVENT_MAXSTR + 1];
74 	uint8_t *payload;
75 
76 	payload = SEGGER_SYSVIEW_PREPARE_PACKET(a_packet);
77 	payload = SEGGER_SYSVIEW_EncodeString(payload, name, NAMED_EVENT_MAXSTR);
78 	payload = SEGGER_SYSVIEW_EncodeU32(payload, arg0);
79 	payload = SEGGER_SYSVIEW_EncodeU32(payload, arg1);
80 	SEGGER_SYSVIEW_SendPacket(a_packet, payload, TID_NAMED_EVENT);
81 }
82 
sysview_init(void)83 static int sysview_init(void)
84 {
85 
86 	SEGGER_SYSVIEW_Conf();
87 	if (IS_ENABLED(CONFIG_SEGGER_SYSTEMVIEW_BOOT_ENABLE)) {
88 		SEGGER_SYSVIEW_Start();
89 	}
90 	return 0;
91 }
92 
93 
94 SYS_INIT(sysview_init, POST_KERNEL, 0);
95