1 /*
2  * Copyright (c) 2020 Intel Corporation
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <zephyr/kernel.h>
8 #include <zephyr/device.h>
9 #include <zephyr/init.h>
10 #include <zephyr/drivers/ipm.h>
11 
12 #include <zephyr/logging/log.h>
13 LOG_MODULE_REGISTER(ipm_console, CONFIG_IPM_LOG_LEVEL);
14 
15 const struct device *ipm_dev;
16 
console_out(int c)17 static int console_out(int c)
18 {
19 	static char buf[CONFIG_IPM_CONSOLE_LINE_BUF_LEN];
20 	static size_t len;
21 	int ret;
22 
23 	if (c != '\n' && len < sizeof(buf)) {
24 		buf[len++] = c;
25 		return c;
26 	}
27 
28 	ret = ipm_send(ipm_dev, 1, len, buf, len);
29 	if (ret) {
30 		LOG_ERR("Error sending character %c over IPM, ret %d", c, ret);
31 	}
32 
33 	memset(buf, 0, sizeof(buf));
34 	len = 0;
35 
36 	/* After buffer is full start a new one */
37 	if (c != '\n') {
38 		buf[len++] = c;
39 	}
40 
41 	return c;
42 }
43 
44 #if defined(CONFIG_STDOUT_CONSOLE)
45 extern void __stdout_hook_install(int (*hook)(int));
46 #else
47 #define __stdout_hook_install(x)	\
48 	do {    /* nothing */		\
49 	} while ((0))
50 #endif
51 
52 #if defined(CONFIG_PRINTK)
53 extern void __printk_hook_install(int (*fn)(int));
54 #else
55 #define __printk_hook_install(x)	\
56 	do {    /* nothing */		\
57 	} while ((0))
58 #endif
59 
60 /* Install printk/stdout hooks */
ipm_console_hook_install(void)61 static void ipm_console_hook_install(void)
62 {
63 	__stdout_hook_install(console_out);
64 	__printk_hook_install(console_out);
65 }
66 
ipm_console_init(void)67 static int ipm_console_init(void)
68 {
69 
70 	LOG_DBG("IPM console initialization");
71 
72 	ipm_dev = DEVICE_DT_GET(DT_CHOSEN(zephyr_console));
73 	if (!device_is_ready(ipm_dev)) {
74 		LOG_ERR("%s is not ready", ipm_dev->name);
75 		return -ENODEV;
76 	}
77 
78 	if (ipm_max_id_val_get(ipm_dev) < CONFIG_IPM_CONSOLE_LINE_BUF_LEN) {
79 		LOG_ERR("IPM driver does not support buffer length %d",
80 			CONFIG_IPM_CONSOLE_LINE_BUF_LEN);
81 		return -ENOTSUP;
82 	}
83 
84 	ipm_console_hook_install();
85 
86 	return 0;
87 }
88 
89 /* Need to be initialized after IPM */
90 SYS_INIT(ipm_console_init, POST_KERNEL, CONFIG_CONSOLE_INIT_PRIORITY);
91