Skip to content

Commit c47eb30

Browse files
committed
Protect printf with spinlock to prevent interleaved output on SMP
On SMP systems, concurrent calls to printf() from multiple harts can cause interleaved and unreadable output due to racing writes to the shared output buffer. Add a spinlock to serialize access to printf(), ensuring that only one hart writes at a time. This change improves the readability of debug messages and prevents garbled output when multiple harts are active.
1 parent 462d725 commit c47eb30

File tree

1 file changed

+6
-0
lines changed

1 file changed

+6
-0
lines changed

lib/stdio.c

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,13 @@
77

88
#include <lib/libc.h>
99
#include <stdarg.h>
10+
#include <spinlock.h>
1011

1112
#include "private/stdio.h"
1213

14+
static spinlock_t printf_lock = SPINLOCK_INITIALIZER;
15+
static uint32_t printf_flags = 0;
16+
1317
/* Ignores output character, returns 0 (success). */
1418
static int stdout_null(int c)
1519
{
@@ -261,9 +265,11 @@ int32_t printf(const char *fmt, ...)
261265
va_list args;
262266
int32_t v;
263267

268+
spin_lock_irqsave(&printf_lock, &printf_flags);
264269
va_start(args, fmt);
265270
v = vsprintf(0, fmt, args);
266271
va_end(args);
272+
spin_unlock_irqrestore(&printf_lock, printf_flags);
267273
return v;
268274
}
269275

0 commit comments

Comments
 (0)