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 
10 #if defined(CONFIG_PRINTK) || defined(CONFIG_STDOUT_CONSOLE)
11 /**
12  * @brief Output one character to SIMULATOR console
13  * @param c Character to output
14  * @return The character passed as input.
15  */
console_out(int c)16 static int console_out(int c)
17 {
18 	char buf[16];
19 
20 	register int a2 __asm__ ("a2") = SYS_write;
21 	register int a3 __asm__ ("a3") = 1;
22 	register char *a4 __asm__ ("a4") = buf;
23 	register int a5 __asm__ ("a5") = 1;
24 	register int ret_val __asm__ ("a2");
25 	register int ret_err __asm__ ("a3");
26 
27 	buf[0] = (char)c;
28 	__asm__ volatile ("simcall"
29 				: "=a" (ret_val), "=a" (ret_err)
30 				: "a" (a2), "a" (a3), "a" (a4), "a" (a5)
31 				: "memory");
32 	return c;
33 }
34 #endif
35 
36 #if defined(CONFIG_STDOUT_CONSOLE)
37 extern void __stdout_hook_install(int (*hook)(int));
38 #else
39 #define __stdout_hook_install(x)		\
40 	do {/* nothing */			\
41 	} while ((0))
42 #endif
43 
44 #if defined(CONFIG_PRINTK)
45 extern void __printk_hook_install(int (*fn)(int));
46 #else
47 #define __printk_hook_install(x)		\
48 	do {/* nothing */			\
49 	} while ((0))
50 #endif
51 
52 /**
53  * @brief Install printk/stdout hook for Xtensa Simulator console output
54  */
xt_sim_console_hook_install(void)55 static void xt_sim_console_hook_install(void)
56 {
57 	__stdout_hook_install(console_out);
58 	__printk_hook_install(console_out);
59 }
60 
61 /**
62  * @brief Initialize the console/debug port
63  * @return 0 if successful, otherwise failed.
64  */
xt_sim_console_init(void)65 static int xt_sim_console_init(void)
66 {
67 	xt_sim_console_hook_install();
68 	return 0;
69 }
70 
71 /* UART console initializes after the UART device itself */
72 SYS_INIT(xt_sim_console_init,
73 #if defined(CONFIG_EARLY_CONSOLE)
74 	 PRE_KERNEL_1,
75 #else
76 	 POST_KERNEL,
77 #endif
78 	 CONFIG_CONSOLE_INIT_PRIORITY);
79