Skip to content

Commit 34fdc56

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 8863bcb commit 34fdc56

File tree

1 file changed

+6
-0
lines changed

1 file changed

+6
-0
lines changed

lib/libc.c

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
#include <lib/libc.h>
22
#include <stdarg.h>
3+
#include <spinlock.h>
34

45
#include "private/stdio.h"
56
#include "private/utils.h"
@@ -896,15 +897,20 @@ static int vsprintf(char **buf, const char *fmt, va_list args)
896897
return len;
897898
}
898899

900+
901+
static spinlock_t printf_lock = SPINLOCK_INITIALIZER;
902+
static uint32_t printf_flags = 0;
899903
/* Formatted output to stdout. */
900904
int32_t printf(const char *fmt, ...)
901905
{
902906
va_list args;
903907
int32_t v;
904908

909+
spin_lock_irqsave(&printf_lock, &printf_flags);
905910
va_start(args, fmt);
906911
v = vsprintf(0, fmt, args);
907912
va_end(args);
913+
spin_unlock_irqrestore(&printf_lock, printf_flags);
908914
return v;
909915
}
910916

0 commit comments

Comments
 (0)