1 From 11e4b63abbe23872b45f325a7c6c8b7f9ff42cad Mon Sep 17 00:00:00 2001
2 From: Petr Mladek <pmladek@suse.com>
3 Date: Fri, 2 Jul 2021 17:06:57 +0200
4 Subject: printk/console: Check consistent sequence number when handling race in console_unlock()
6 From: Petr Mladek <pmladek@suse.com>
8 commit 11e4b63abbe23872b45f325a7c6c8b7f9ff42cad upstream.
10 The standard printk() tries to flush the message to the console
11 immediately. It tries to take the console lock. If the lock is
12 already taken then the current owner is responsible for flushing
15 There is a small race window between checking whether a new message is
16 available and releasing the console lock. It is solved by re-checking
17 the state after releasing the console lock. If the check is positive
18 then console_unlock() tries to take the lock again and process the new
21 The commit 996e966640ddea7b535c ("printk: remove logbuf_lock") causes that
22 console_seq is not longer read atomically. As a result, the re-check might
23 be done with an inconsistent 64-bit index.
25 Solve it by using the last sequence number that has been checked under
26 the console lock. In the worst case, it will take the lock again only
27 to realized that the new message has already been proceed. But it
28 was possible even before.
30 The variable next_seq is marked as __maybe_unused to call down compiler
31 warning when CONFIG_PRINTK is not defined.
33 Fixes: commit 996e966640ddea7b535c ("printk: remove logbuf_lock")
34 Reported-by: kernel test robot <lkp@intel.com> # unused next_seq warning
35 Cc: stable@vger.kernel.org # 5.13
36 Signed-off-by: Petr Mladek <pmladek@suse.com>
37 Acked-by: Sergey Senozhatsky <senozhatsky@chromium.org>
38 Reviewed-by: John Ogness <john.ogness@linutronix.de>
39 Link: https://lore.kernel.org/r/20210702150657.26760-1-pmladek@suse.com
40 Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
42 kernel/printk/printk.c | 7 +++++--
43 1 file changed, 5 insertions(+), 2 deletions(-)
45 --- a/kernel/printk/printk.c
46 +++ b/kernel/printk/printk.c
47 @@ -2545,6 +2545,7 @@ void console_unlock(void)
48 bool do_cond_resched, retry;
49 struct printk_info info;
50 struct printk_record r;
51 + u64 __maybe_unused next_seq;
53 if (console_suspended) {
55 @@ -2654,8 +2655,10 @@ skip:
60 + /* Get consistent value of the next-to-be-used sequence number. */
61 + next_seq = console_seq;
67 @@ -2664,7 +2667,7 @@ skip:
68 * there's a new owner and the console_unlock() from them will do the
71 - retry = prb_read_valid(prb, console_seq, NULL);
72 + retry = prb_read_valid(prb, next_seq, NULL);
73 printk_safe_exit_irqrestore(flags);
75 if (retry && console_trylock())