1 /*
2  * Copyright (C) 2018-2022 Intel Corporation.
3  *
4  * SPDX-License-Identifier: BSD-3-Clause
5  */
6 
7 #include <types.h>
8 #include <asm/lib/atomic.h>
9 #include <sprintf.h>
10 #include <asm/lib/spinlock.h>
11 #include <asm/per_cpu.h>
12 #include <npk_log.h>
13 #include <logmsg.h>
14 #include <ticks.h>
15 
16 /* buf size should be identical to the size in hvlog option, which is
17  * transfered to Service VM:
18  * bsp/uefi/clearlinux/acrn.conf: hvlog=2M@0x1FE00000
19  */
20 
21 struct acrn_logmsg_ctl {
22 	int32_t seq;
23 	spinlock_t lock;
24 };
25 
26 static struct acrn_logmsg_ctl logmsg_ctl;
27 
init_logmsg()28 void init_logmsg()
29 {
30 	logmsg_ctl.seq = 0;
31 
32 	spinlock_init(&(logmsg_ctl.lock));
33 }
34 
do_logmsg(uint32_t severity,const char * fmt,...)35 void do_logmsg(uint32_t severity, const char *fmt, ...)
36 {
37 	va_list args;
38 	uint64_t timestamp, rflags;
39 	uint16_t pcpu_id;
40 	bool do_console_log;
41 	bool do_mem_log;
42 	bool do_npk_log;
43 	char *buffer;
44 	struct thread_object *current;
45 
46 	do_console_log = (severity <= console_loglevel);
47 	do_mem_log = (severity <= mem_loglevel);
48 	do_npk_log = (severity <= npk_loglevel);
49 
50 	if (!do_console_log && !do_mem_log && !do_npk_log) {
51 		return;
52 	}
53 
54 	/* Get time-stamp value */
55 	timestamp = cpu_ticks();
56 
57 	/* Scale time-stamp appropriately */
58 	timestamp = ticks_to_us(timestamp);
59 
60 	/* Get CPU ID */
61 	pcpu_id = get_pcpu_id();
62 	buffer = per_cpu(logbuf, pcpu_id);
63 	current = sched_get_current(pcpu_id);
64 
65 	(void)memset(buffer, 0U, LOG_MESSAGE_MAX_SIZE);
66 	/* Put time-stamp, CPU ID and severity into buffer */
67 	snprintf(buffer, LOG_MESSAGE_MAX_SIZE, "[%luus][cpu=%hu][%s][sev=%u][seq=%u]:",
68 			timestamp, pcpu_id, current->name, severity, atomic_inc_return(&logmsg_ctl.seq));
69 
70 	/* Put message into remaining portion of local buffer */
71 	va_start(args, fmt);
72 	vsnprintf(buffer + strnlen_s(buffer, LOG_MESSAGE_MAX_SIZE),
73 		LOG_MESSAGE_MAX_SIZE
74 		- strnlen_s(buffer, LOG_MESSAGE_MAX_SIZE), fmt, args);
75 	va_end(args);
76 
77 	/* Check whether output to NPK */
78 	if (do_npk_log) {
79 		npk_log_write(buffer, strnlen_s(buffer, LOG_MESSAGE_MAX_SIZE));
80 	}
81 
82 	/* Check whether output to stdout */
83 	if (do_console_log) {
84 		spinlock_irqsave_obtain(&(logmsg_ctl.lock), &rflags);
85 
86 		/* Send buffer to stdout */
87 		printf("%s\n\r", buffer);
88 
89 		spinlock_irqrestore_release(&(logmsg_ctl.lock), rflags);
90 	}
91 
92 	/* Check whether output to memory */
93 	if (do_mem_log) {
94 		uint32_t msg_len;
95 		struct shared_buf *sbuf = per_cpu(sbuf, pcpu_id)[ACRN_HVLOG];
96 
97 		/* If sbuf is not ready, we just drop the massage */
98 		if (sbuf != NULL) {
99 			msg_len = strnlen_s(buffer, LOG_MESSAGE_MAX_SIZE);
100 			(void)sbuf_put_many(sbuf, LOG_ENTRY_SIZE, (uint8_t *)buffer,
101 				LOG_ENTRY_SIZE * (((msg_len - 1U) / LOG_ENTRY_SIZE) + 1));
102 		}
103 	}
104 }
105