[PATCH] printk: add cpu id information to printk() output

Enlin Mu
2023-09-15T07:41:03Z

From: Enlin Mu <enlin.mu@unisoc.com>

Sometimes we want to print cpu id of printk() messages to consoles

Signed-off-by: Enlin Mu <enlin.mu@unisoc.com>
---
include/linux/threads.h | 3 +++
kernel/printk/printk.c | 18 +++++++++++++-----
2 files changed, 16 insertions(+), 5 deletions(-)

diff --git a/include/linux/threads.h b/include/linux/threads.h
index c34173e6c5f1..6700bd9a174f 100644
--- a/include/linux/threads.h
+++ b/include/linux/threads.h
@@ -34,6 +34,9 @@
#define PID_MAX_LIMIT (CONFIG_BASE_SMALL ? PAGE_SIZE * 8 : \
(sizeof(long) > 4 ? 4 * 1024 * 1024 : PID_MAX_DEFAULT))

+#define CPU_ID_SHIFT 23
+#define CPU_ID_MASK 0xff800000
+
/*
* Define a minimum number of pids per cpu. Heuristically based
* on original pid max of 32k for 32 cpus. Also, increase the
diff --git a/kernel/printk/printk.c b/kernel/printk/printk.c
index 7e0b4dd02398..f3f3ca89b251 100644
--- a/kernel/printk/printk.c
+++ b/kernel/printk/printk.c
@@ -629,8 +629,12 @@ static ssize_t info_print_ext_header(char *buf, size_t size,
#ifdef CONFIG_PRINTK_CALLER
u32 id = info->caller_id;

- snprintf(caller, sizeof(caller), ",caller=%c%u",
- id & 0x80000000 ? 'C' : 'T', id & ~0x80000000);
+ if (id&0x80000000)
+ snprintf(caller, sizeof(caller), ",caller=C%u",
+ id & ~0x80000000);
+ else
+ snprintf(caller, sizeof(caller), ",caller=T%uC%u",
+ id & ~CPU_ID_MASK, id >> CPU_ID_SHIFT);
#else
caller[0] = '\0';
#endif
@@ -1333,8 +1337,12 @@ static size_t print_caller(u32 id, char *buf)
{
char caller[12];

- snprintf(caller, sizeof(caller), "%c%u",
- id & 0x80000000 ? 'C' : 'T', id & ~0x80000000);
+ if (id & 0x80000000)
+ snprintf(caller, sizeof(caller), "C%u",
+ id & ~0x80000000);
+ else
+ snprintf(caller, sizeof(caller), "T%uC%u",
+ id & ~CPU_ID_MASK, id >> CPU_ID_SHIFT);
return sprintf(buf, "[%6s]", caller);
}
#else
@@ -2069,7 +2077,7 @@ static inline void printk_delay(int level)

static inline u32 printk_caller_id(void)
{
- return in_task() ? task_pid_nr(current) :
+ return in_task() ? task_pid_nr(current) | (smp_processor_id() << CPU_ID_SHIFT) :
0x80000000 + smp_processor_id();
}

--
2.25.1