1 /*
2  * Copyright (c) 2016 Cadence Design Systems, Inc.
3  * SPDX-License-Identifier: Apache-2.0
4  */
5 
6 #include <xtensa/simcall.h>
7 #include <zephyr/device.h>
8 #include <zephyr/init.h>
9 #include <zephyr/sys/printk-hooks.h>
10 #include <zephyr/sys/libc-hooks.h>
11 
12 #if defined(CONFIG_PRINTK) || defined(CONFIG_STDOUT_CONSOLE)
13 /**
14  * @brief Output one character to SIMULATOR console
15  * @param c Character to output
16  * @return The character passed as input.
17  */
arch_printk_char_out(int c)18 int arch_printk_char_out(int c)
19 {
20 	char buf[16];
21 
22 	register int a2 __asm__ ("a2") = SYS_write;
23 	register int a3 __asm__ ("a3") = 1;
24 	register char *a4 __asm__ ("a4") = buf;
25 	register int a5 __asm__ ("a5") = 1;
26 	register int ret_val __asm__ ("a2");
27 	register int ret_err __asm__ ("a3");
28 
29 	buf[0] = (char)c;
30 	__asm__ volatile ("simcall"
31 				: "=a" (ret_val), "=a" (ret_err)
32 				: "a" (a2), "a" (a3), "a" (a4), "a" (a5)
33 				: "memory");
34 	return c;
35 }
36 #endif
37 
38 /**
39  * @brief Install printk/stdout hook for Xtensa Simulator console output
40  */
xt_sim_console_hook_install(void)41 static void xt_sim_console_hook_install(void)
42 {
43 #if defined(CONFIG_STDOUT_CONSOLE)
44 	__stdout_hook_install(arch_printk_char_out);
45 #endif
46 #if defined(CONFIG_PRINTK)
47 	__printk_hook_install(arch_printk_char_out);
48 #endif
49 }
50 
51 /**
52  * @brief Initialize the console/debug port
53  * @return 0 if successful, otherwise failed.
54  */
xt_sim_console_init(void)55 static int xt_sim_console_init(void)
56 {
57 	xt_sim_console_hook_install();
58 	return 0;
59 }
60 
61 /* UART console initializes after the UART device itself */
62 SYS_INIT(xt_sim_console_init,
63 #if defined(CONFIG_EARLY_CONSOLE)
64 	 PRE_KERNEL_1,
65 #else
66 	 POST_KERNEL,
67 #endif
68 	 CONFIG_CONSOLE_INIT_PRIORITY);
69