1 /*
2  * Copyright (c) 2022 Intel Corporation
3  * SPDX-License-Identifier: Apache-2.0
4  */
5 
6 #include <zephyr/device.h>
7 #include <zephyr/init.h>
8 #include <zephyr/kernel.h>
9 #include <zephyr/sys/winstream.h>
10 #include <zephyr/sys/printk-hooks.h>
11 #include <zephyr/sys/libc-hooks.h>
12 #include <zephyr/devicetree.h>
13 #include <zephyr/cache.h>
14 
15 #include <adsp_memory.h>
16 #include <mem_window.h>
17 
18 struct k_spinlock trace_lock;
19 
20 static struct sys_winstream *winstream;
21 
winstream_console_trace_out(int8_t * str,size_t len)22 void winstream_console_trace_out(int8_t *str, size_t len)
23 {
24 	if (len == 0) {
25 		return;
26 	}
27 
28 #ifdef CONFIG_ADSP_TRACE_SIMCALL
29 	register int a2 __asm__("a2") = 4; /* SYS_write */
30 	register int a3 __asm__("a3") = 1; /* fd 1 == stdout */
31 	register int a4 __asm__("a4") = (int)str;
32 	register int a5 __asm__("a5") = len;
33 
34 	__asm__ volatile("simcall" : "+r"(a2), "+r"(a3) : "r"(a4), "r"(a5) : "memory");
35 #endif
36 
37 	k_spinlock_key_t key = k_spin_lock(&trace_lock);
38 
39 	sys_winstream_write(winstream, str, len);
40 	k_spin_unlock(&trace_lock, key);
41 }
42 
arch_printk_char_out(int c)43 int arch_printk_char_out(int c)
44 {
45 	int8_t s = c;
46 
47 	winstream_console_trace_out(&s, 1);
48 	return 0;
49 }
50 
winstream_console_hook_install(void)51 static void winstream_console_hook_install(void)
52 {
53 #if defined(CONFIG_STDOUT_CONSOLE)
54 	__stdout_hook_install(arch_printk_char_out);
55 #endif
56 #if defined(CONFIG_PRINTK)
57 	__printk_hook_install(arch_printk_char_out);
58 #endif
59 }
60 
61 
winstream_console_init(void)62 static int winstream_console_init(void)
63 {
64 	const struct device *dev = DEVICE_DT_GET(DT_CHOSEN(zephyr_console));
65 
66 	if (!device_is_ready(dev)) {
67 		return -ENODEV;
68 	}
69 	const struct mem_win_config *config = dev->config;
70 	void *buf =
71 		sys_cache_uncached_ptr_get((__sparse_force void __sparse_cache *)config->mem_base);
72 
73 	winstream = sys_winstream_init(buf, config->size);
74 	winstream_console_hook_install();
75 
76 	return 0;
77 }
78 
79 SYS_INIT(winstream_console_init, PRE_KERNEL_1, CONFIG_CONSOLE_INIT_PRIORITY);
80