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 #include <zephyr/sys/printk-hooks.h>
12 #include <zephyr/sys/libc-hooks.h>
13 
14 #include <zephyr/logging/log.h>
15 LOG_MODULE_REGISTER(ipm_console, CONFIG_IPM_LOG_LEVEL);
16 
17 const struct device *ipm_dev;
18 
console_out(int c)19 static int console_out(int c)
20 {
21 	static char buf[CONFIG_IPM_CONSOLE_LINE_BUF_LEN];
22 	static size_t len;
23 	int ret;
24 
25 	if (c != '\n' && len < sizeof(buf)) {
26 		buf[len++] = c;
27 		return c;
28 	}
29 
30 	ret = ipm_send(ipm_dev, 1, len, buf, len);
31 	if (ret) {
32 		LOG_ERR("Error sending character %c over IPM, ret %d", c, ret);
33 	}
34 
35 	memset(buf, 0, sizeof(buf));
36 	len = 0;
37 
38 	/* After buffer is full start a new one */
39 	if (c != '\n') {
40 		buf[len++] = c;
41 	}
42 
43 	return c;
44 }
45 
46 /* Install printk/stdout hooks */
ipm_console_hook_install(void)47 static void ipm_console_hook_install(void)
48 {
49 #if defined(CONFIG_STDOUT_CONSOLE)
50 	__stdout_hook_install(console_out);
51 #endif
52 #if defined(CONFIG_PRINTK)
53 	__printk_hook_install(console_out);
54 #endif
55 }
56 
ipm_console_init(void)57 static int ipm_console_init(void)
58 {
59 
60 	LOG_DBG("IPM console initialization");
61 
62 	ipm_dev = DEVICE_DT_GET(DT_CHOSEN(zephyr_console));
63 	if (!device_is_ready(ipm_dev)) {
64 		LOG_ERR("%s is not ready", ipm_dev->name);
65 		return -ENODEV;
66 	}
67 
68 	if (ipm_max_id_val_get(ipm_dev) < CONFIG_IPM_CONSOLE_LINE_BUF_LEN) {
69 		LOG_ERR("IPM driver does not support buffer length %d",
70 			CONFIG_IPM_CONSOLE_LINE_BUF_LEN);
71 		return -ENOTSUP;
72 	}
73 
74 	ipm_console_hook_install();
75 
76 	return 0;
77 }
78 
79 /* Need to be initialized after IPM */
80 SYS_INIT(ipm_console_init, POST_KERNEL, CONFIG_CONSOLE_INIT_PRIORITY);
81