Skip to content

Commit 11e4b63

Browse files
committed
printk/console: Check consistent sequence number when handling race in console_unlock()
The standard printk() tries to flush the message to the console immediately. It tries to take the console lock. If the lock is already taken then the current owner is responsible for flushing even the new message. There is a small race window between checking whether a new message is available and releasing the console lock. It is solved by re-checking the state after releasing the console lock. If the check is positive then console_unlock() tries to take the lock again and process the new message as well. The commit 996e966 ("printk: remove logbuf_lock") causes that console_seq is not longer read atomically. As a result, the re-check might be done with an inconsistent 64-bit index. Solve it by using the last sequence number that has been checked under the console lock. In the worst case, it will take the lock again only to realized that the new message has already been proceed. But it was possible even before. The variable next_seq is marked as __maybe_unused to call down compiler warning when CONFIG_PRINTK is not defined. Fixes: commit 996e966 ("printk: remove logbuf_lock") Reported-by: kernel test robot <[email protected]> # unused next_seq warning Cc: [email protected] # 5.13 Signed-off-by: Petr Mladek <[email protected]> Acked-by: Sergey Senozhatsky <[email protected]> Reviewed-by: John Ogness <[email protected]> Link: https://lore.kernel.org/r/[email protected]
1 parent e563592 commit 11e4b63

File tree

1 file changed

+5
-2
lines changed

1 file changed

+5
-2
lines changed

kernel/printk/printk.c

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2545,6 +2545,7 @@ void console_unlock(void)
25452545
bool do_cond_resched, retry;
25462546
struct printk_info info;
25472547
struct printk_record r;
2548+
u64 __maybe_unused next_seq;
25482549

25492550
if (console_suspended) {
25502551
up_console_sem();
@@ -2654,8 +2655,10 @@ void console_unlock(void)
26542655
cond_resched();
26552656
}
26562657

2657-
console_locked = 0;
2658+
/* Get consistent value of the next-to-be-used sequence number. */
2659+
next_seq = console_seq;
26582660

2661+
console_locked = 0;
26592662
up_console_sem();
26602663

26612664
/*
@@ -2664,7 +2667,7 @@ void console_unlock(void)
26642667
* there's a new owner and the console_unlock() from them will do the
26652668
* flush, no worries.
26662669
*/
2667-
retry = prb_read_valid(prb, console_seq, NULL);
2670+
retry = prb_read_valid(prb, next_seq, NULL);
26682671
printk_safe_exit_irqrestore(flags);
26692672

26702673
if (retry && console_trylock())

0 commit comments

Comments
 (0)