Skip to contentSkip to conversation

printk: Clean up preferred console handling

PATCH Superseded Petr Mladek 4 participants 23 messages Apr 23 – May 29 Printk

v2 of 7 Superseded Latest is v7 →

lore
Share & tools
lore

Petr Mladek

author maintainer
#0 lore raw

v2 cover printk: Clean up preferred console handling

Hi,

this patchset does some clean up of the code for handling preferred consoles in the console registration code.

+ 1st and 2nd patch try to improve some naming.

+ 3rd patch removes some code duplication. It better defines and describes the rules for adding and updating preferred consoles. It uses a more defensive coding style.

+ 4th, 5th, 6th, and 7th patch improve handling of Braille consoles. They are preferred via the command line but they do not get printk() messages and are not associated with /dev/console.

The new code makes this more obvious. Also it explicitly defines the relation against default consoles and other non-Braille preferred consoles.

+ 8th patch removes a hidden side effect of
try_enable_preferred_console()

+ 9th patch removes the last hidden side effect of try_enable_preferred_console() and allows to call it only when there are any non-Braille preferred consoles.

This patchset is a prerequisite for Marcos' clean up of CON_ENABLE
flag handling. It should prevent regressions caused by the
hidden effects of try_enable_preferred_console(), for example,
see https://lore.kernel.org/r/[email protected]

Also I am working on a feature which would allow to explicitly enable/prefer consoles proposed by SPCR, device tree, or platform-specific code using a generic "console=platform". This clean up is a prerequisite, see
https://github.com/pmladek/linux/tree/console-platform-poc1-iter9

Changes against [v1]:

+ Fix stale comment (1st patch, Chris)

+ Add comment descibing update_preferred_console() behavior (3rd patch, John)

+ Better describe behavior changes caused by update_preferred_console() in the commit message (3rd patch, Chris)

+ Use unsigned int for iterating/indexing preferred_consoles[] table (3rd patch, John)

+ Add a check preventing an update via "devname" is already assigned to a real "name". (3rd patch, Petr)

+ Use only Braille entries when trying to enable Braille console (Chris)

+ Split all try_enable_*console() calls into new try_enable_console() and return early when try_enable_braille_console() succeeded. Note that we do not longer need to initialize "err" variable in this case. (new 5th patch, Chris, Petr)

+ Put back the explicit check of CON_BRL flag in register_console() so that it returns prelimitary only when the driver is used in Braille mode. (6th patch, Chris, Petr)

+ Add comments explaining that try_enable_braille_console() might succeeded also when newcon->match() succeeded. In this case, the Braille mode can't be used because the console device was already used as an early console.[*] (6th patch, Chris, Petr)

+ Reset preferred_dev_console_prev when used to revert the value. (7th patch, John)

+ Add Acked-by and Reviewed-by tags (1st, 2nd, 4th patch, Chris, Marcos)

[*] This is a questional behavior. I would personally prefer when
the early console is unregistered at this point and the console device is converted into Braille console. I consider the Braille mode more important. But it might be changed/fixed later in another patchset.

[v1] https://lore.kernel.org/r/[email protected]

Petr Mladek (9):
printk: Rename struct console_cmdline to preferred_console
printk: Rename preferred_console to preferred_dev_console
printk: Separate code for adding/updating preferred console metadata
printk: Cleanup _braille_(un)register_console() wrappers
printk: Separate code for enabling console
printk: Try to register each console as Braille first
printk: Do not set Braille console as preferred_console
printk: Handle pre-enabled consoles in the top-level
try_enable_console()
printk: Try enable preferred consoles only when there are any

 .../accessibility/braille/braille_console.c   |   7 +-
 kernel/printk/braille.c                       |  20 +-
 kernel/printk/braille.h                       |  23 +-
 .../{console_cmdline.h => console_register.h} |   6 +-
 kernel/printk/printk.c                        | 390 ++++++++++++------
 5 files changed, 301 insertions(+), 145 deletions(-)
 rename kernel/printk/{console_cmdline.h => console_register.h} (83%)
Signature · 1 line
2.53.0
author maintainer
#1 lore raw

PATCH v2 1/9 printk: Rename struct console_cmdline to preferred_console

The structure 'console_cmdline' was originally intended to store details about consoles defined on the kernel command line. However, its usage has since expanded; it now stores information for consoles preferred via SPCR, device tree, or by particular platforms, e.g. XEN.

The current naming is misleading as it implies the configuration only originates from the command line.

Rename the structure and associated artifacts to better reflect their current purpose, for example:

- struct console_cmdline c -> struct preferred_console pc
- console_cmdline[] -> preferred_consoles[]
- console_cmdline.h -> console_register.h
- c -> pc

Additionally, renaming the header file to console_register.h would eventually allow to decouple console registration logic from the monolithic printk.c.

Finally, renaming the local variable from "c" to "pc" helps to distinguish it from struct console variables. Note that "c" is used for struct console in some code, for example see vt_console_device() function definition.

The patch should not change the existing behaivor.

---
 kernel/printk/braille.c                       | 10 +--
 kernel/printk/braille.h                       | 10 +--
 .../{console_cmdline.h => console_register.h} |  6 +-
 kernel/printk/printk.c                        | 86 ++++++++++---------
 4 files changed, 57 insertions(+), 55 deletions(-)
 rename kernel/printk/{console_cmdline.h => console_register.h} (83%)
kernel/printk/braille.c +5 -5
index 17a9591e54ff..9d21a2bb1d38 100644
@@ -6,7 +6,7 @@
 #include <linux/errno.h>
 #include <linux/string.h>
 
-#include "console_cmdline.h"
+#include "console_register.h"
 #include "braille.h"
 
 int _braille_console_setup(char **str, char **brl_options)
@@ -35,14 +35,14 @@ int _braille_console_setup(char **str, char **brl_options)
 }
 
 int
-_braille_register_console(struct console *console, struct console_cmdline *c)
+_braille_register_console(struct console *console, struct preferred_console *pc)
 {
 	int rtn = 0;
 
-	if (c->brl_options) {
+	if (pc->brl_options) {
 		console->flags |= CON_BRL;
-		rtn = braille_register_console(console, c->index, c->options,
-					       c->brl_options);
+		rtn = braille_register_console(console, pc->index, pc->options,
+					       pc->brl_options);
 	}
 
 	return rtn;
kernel/printk/braille.h +5 -5
index 123154f86304..55cd3178a17a 100644
@@ -5,9 +5,9 @@
 #ifdef CONFIG_A11Y_BRAILLE_CONSOLE
 
 static inline void
-braille_set_options(struct console_cmdline *c, char *brl_options)
+braille_set_options(struct preferred_console *pc, char *brl_options)
 {
-	c->brl_options = brl_options;
+	pc->brl_options = brl_options;
 }
 
 /*
@@ -21,7 +21,7 @@ int
 _braille_console_setup(char **str, char **brl_options);
 
 int
-_braille_register_console(struct console *console, struct console_cmdline *c);
+_braille_register_console(struct console *console, struct preferred_console *pc);
 
 int
 _braille_unregister_console(struct console *console);
@@ -29,7 +29,7 @@ _braille_unregister_console(struct console *console);
 #else
 
 static inline void
-braille_set_options(struct console_cmdline *c, char *brl_options)
+braille_set_options(struct preferred_console *pc, char *brl_options)
 {
 }
 
@@ -40,7 +40,7 @@ _braille_console_setup(char **str, char **brl_options)
 }
 
 static inline int
-_braille_register_console(struct console *console, struct console_cmdline *c)
+_braille_register_console(struct console *console, struct preferred_console *pc)
 {
 	return 0;
 }
kernel/printk/console_register.h renamed from kernel/printk/console_cmdline.h +3 -3
similarity index 83%
rename from kernel/printk/console_cmdline.h
rename to kernel/printk/console_register.h
index 0ab573b6d4dc..9ab3e1cc749b 100644
@@ -1,8 +1,8 @@
 /* SPDX-License-Identifier: GPL-2.0 */
-#ifndef _CONSOLE_CMDLINE_H
-#define _CONSOLE_CMDLINE_H
+#ifndef _CONSOLE_REGISTER_H
+#define _CONSOLE_REGISTER_H
 
-struct console_cmdline
+struct preferred_console
 {
 	char	name[16];			/* Name of the driver	    */
 	int	index;				/* Minor dev. to use	    */
kernel/printk/printk.c +44 -42

180 lines not on this page · raw message

Signature · 1 line
2.53.0
#2 lore raw

Re: [PATCH v2 1/9] printk: Rename struct console_cmdline to preferred_console

Quoted 8 lines · On Thu, 23 Apr 2026 15:00:06 +0200 Petr Mladek <[email protected]> wrote:

The structure 'console_cmdline' was originally intended to store details about consoles defined on the kernel command line. However, its usage has since expanded; it now stores information for consoles preferred via SPCR, device tree, or by particular platforms, e.g. XEN.

The current naming is misleading as it implies the configuration only originates from the command line.

Quoted 7 lines

Rename the structure and associated artifacts to better reflect their current purpose, for example:

- struct console_cmdline c -> struct preferred_console pc
- console_cmdline[] -> preferred_consoles[]
- console_cmdline.h -> console_register.h
- c -> pc

Nice.

Quoted 10 lines

Additionally, renaming the header file to console_register.h would eventually allow to decouple console registration logic from the monolithic printk.c.

Finally, renaming the local variable from "c" to "pc" helps to distinguish it from struct console variables. Note that "c" is used for struct console in some code, for example see vt_console_device() function definition.

The patch should not change the existing behaivor.

I believe the phrase is: "No functional changes" ;-)

Quoted 8 lines

---

kernel/printk/printk.c __setup("console_msg_format=", console_msg_format_setup); · line 2628

Quoted 7 lines
kernel/printk/printk.c +2 -2
@@ -2624,8 +2624,10 @@ __setup("console_msg_format=", console_msg_format_setup);
  */
 static int __init console_setup(char *str)
 {
-	static_assert(sizeof(console_cmdline[0].devname) >= sizeof(console_cmdline[0].name) + 4);
-	char buf[sizeof(console_cmdline[0].devname)];
+	static_assert(sizeof(preferred_consoles[0].devname) >=
+		      sizeof(preferred_consoles[0].name) + 4);

Hmm with the line break and you adding a space before the declarations; If this is going to change, might as well move it below the declarations as it is a compile time check, and the order doesn't matter.

kernel/printk/printk.c __setup("console_msg_format=", console_msg_format_setup); · line 2633

Quoted 5 lines
kernel/printk/printk.c +2 -0
+
+	char buf[sizeof(preferred_consoles[0].devname)];
 	char *brl_options = NULL;
 	char *ttyname = NULL;
 	char *devname = NULL;

-- Steve

maintainer Reviewed-by on v2 1/9
#3 lore raw

Re: [PATCH v2 1/9] printk: Rename struct console_cmdline to preferred_console

In reply to Petr Mladek
Quoted 5 lines · Petr Mladek
kernel/printk/printk.c +0 -0
index 0323149548f6..ca523acbf58d 100644

kernel/printk/printk.c __setup("console_msg_format=", console_msg_format_setup); · line 2630

Quoted 9 lines
kernel/printk/printk.c +4 -2
@@ -2624,8 +2624,10 @@ __setup("console_msg_format=", console_msg_format_setup);
  */
 static int __init console_setup(char *str)
 {
-	static_assert(sizeof(console_cmdline[0].devname) >= sizeof(console_cmdline[0].name) + 4);
-	char buf[sizeof(console_cmdline[0].devname)];
+	static_assert(sizeof(preferred_consoles[0].devname) >=
+		      sizeof(preferred_consoles[0].name) + 4);
+
+	char buf[sizeof(preferred_consoles[0].devname)];

I agree with Steven's suggestion to move the static_assert() below the local variable definitions.

author maintainer
#4 lore raw

PATCH v2 2/9 printk: Rename preferred_console to preferred_dev_console

In reply to Petr Mladek

The preferred_consoles[] array stores information about consoles requested via the command line, SPCR, Device Tree, or platform-specific code. Within this array, the 'preferred_console' variable tracks the specific index that should be associated with /dev/console (typically the last non-braille console defined).

The current name "preferred_console" is ambiguous and leads to confusion. It does not clearly communicate why one console is "more preferred" than others in the array. Furthermore, entries for Braille consoles can exist within the preferred_consoles[] array, yet they are never associated with /dev/console and do not receive standard printk() output. Consequently, the 'preferred_console' index must skip these entries, which is not immediately obvious from the name.

Rename the variable to 'preferred_dev_console' to explicitly clarify its role in identifying which entry is linked to /dev/console.

The patch should not change the existing behavior.

---
 kernel/printk/printk.c | 10 +++++-----
 1 file changed, 5 insertions(+), 5 deletions(-)
kernel/printk/printk.c +5 -5
index ca523acbf58d..13c98285892b 100644
@@ -366,7 +366,7 @@ static int console_locked;
 
 static struct preferred_console preferred_consoles[MAX_PREFERRED_CONSOLES];
 
-static int preferred_console = -1;
+static int preferred_dev_console = -1;
 int console_set_on_cmdline;
 EXPORT_SYMBOL(console_set_on_cmdline);
 
@@ -2587,7 +2587,7 @@ static int __add_preferred_console(const char *name, const short idx,
 		if ((name && strcmp(pc->name, name) == 0 && pc->index == idx) ||
 		    (devname && strcmp(pc->devname, devname) == 0)) {
 			if (!brl_options)
-				preferred_console = i;
+				preferred_dev_console = i;
 			set_user_specified(pc, user_specified);
 			return 0;
 		}
@@ -2595,7 +2595,7 @@ static int __add_preferred_console(const char *name, const short idx,
 	if (i == MAX_PREFERRED_CONSOLES)
 		return -E2BIG;
 	if (!brl_options)
-		preferred_console = i;
+		preferred_dev_console = i;
 	if (name)
 		strscpy(pc->name, name);
 	if (devname)
@@ -3930,7 +3930,7 @@ static int try_enable_preferred_console(struct console *newcon,
 				return err;
 		}
 		newcon->flags |= CON_ENABLED;
-		if (i == preferred_console)
+		if (i == preferred_dev_console)
 			newcon->flags |= CON_CONSDEV;
 		return 0;
 	}
@@ -4111,7 +4111,7 @@ void register_console(struct console *newcon)
 	 * Note that a console with tty binding will have CON_CONSDEV
 	 * flag set and will be first in the list.
 	 */
-	if (preferred_console < 0) {
+	if (preferred_dev_console < 0) {
 		if (hlist_empty(&console_list) || !console_first()->device ||
 		    console_first()->flags & CON_BOOT) {
 			try_enable_default_console(newcon);
Signature · 1 line
2.53.0
maintainer Reviewed-by on v2 2/9
#5 lore raw

Re: [PATCH v2 2/9] printk: Rename preferred_console to preferred_dev_console

Quoted 14 lines · Petr Mladek

The preferred_consoles[] array stores information about consoles requested via the command line, SPCR, Device Tree, or platform-specific code. Within this array, the 'preferred_console' variable tracks the specific index that should be associated with /dev/console (typically the last non-braille console defined).

The current name "preferred_console" is ambiguous and leads to confusion. It does not clearly communicate why one console is "more preferred" than others in the array. Furthermore, entries for Braille consoles can exist within the preferred_consoles[] array, yet they are never associated with /dev/console and do not receive standard printk() output. Consequently, the 'preferred_console' index must skip these entries, which is not immediately obvious from the name.

Quoted 8 lines

Rename the variable to 'preferred_dev_console' to explicitly clarify its role in identifying which entry is linked to /dev/console.

The patch should not change the existing behavior.

author maintainer
#6 lore raw

PATCH v2 3/9 printk: Separate code for adding/updating preferred console metadata

In reply to Petr Mladek

The logic for adding or updating a preferred console is currently duplicated within __add_preferred_console(), making the code difficult to follow and prone to consistency issues.

Introduce update_preferred_console() to centralize the initialization and updating of struct preferred_console entries. This refactoring explicitly defines and enforces the following rules:

1. Console names and/or indexes are not set when a console is preferred via devname; these are resolved later during device matching.
2. Console names are only added alongside a valid index.
3. Only matching entries are updated.
4. Console and Braille options are never cleared. They are updated only via the command line.
5. The global 'preferred_dev_console' index and 'console_set_on_cmdline' flag are updated consistently.

Additionally, rename braille_set_options() to braille_update_options() to better reflect its conditional behavior.

Behavior change:

The original code never updated the preferred console options when it was preferred more times, e.g. via the command line and/or some platform specific code, e.g. SPCR or device tree.

The new code explicitly allows to update the console options when they are preferred over the command line.

It mostly worked even before but only because the command line was processed early enough before handling SPCR, device tree, or other platform specific init code.

The main behavior change is when the same console is preferred more times on the command line. Newly, the later or Braille variant wins. It is a more common and expected behavior.

---
 kernel/printk/braille.h |   7 +-
 kernel/printk/printk.c  | 149 ++++++++++++++++++++++++++++++----------
 2 files changed, 118 insertions(+), 38 deletions(-)
kernel/printk/braille.h +4 -3
index 55cd3178a17a..0bdac303f8b1 100644
@@ -5,9 +5,10 @@
 #ifdef CONFIG_A11Y_BRAILLE_CONSOLE
 
 static inline void
-braille_set_options(struct preferred_console *pc, char *brl_options)
+braille_update_options(struct preferred_console *pc, char *brl_options)
 {
-	pc->brl_options = brl_options;
+	if (brl_options)
+		pc->brl_options = brl_options;
 }
 
 /*
@@ -29,7 +30,7 @@ _braille_unregister_console(struct console *console);
 #else
 
 static inline void
-braille_set_options(struct preferred_console *pc, char *brl_options)
+braille_update_options(struct preferred_console *pc, char *brl_options)
 {
 }
 
kernel/printk/printk.c +114 -35

179 lines not on this page · raw message

Signature · 1 line
2.53.0
Acked-by on v2 3/9
#7 lore raw

Re: [PATCH v2 3/9] printk: Separate code for adding/updating preferred console metadata

Quoted 33 lines · Petr Mladek

The logic for adding or updating a preferred console is currently duplicated within __add_preferred_console(), making the code difficult
to follow and prone to consistency issues.

Introduce update_preferred_console() to centralize the initialization and updating of struct preferred_console entries. This refactoring explicitly defines and enforces the following rules:

1. Console names and/or indexes are not set when a console is preferred
   via devname; these are resolved later during device matching.
2. Console names are only added alongside a valid index.
3. Only matching entries are updated.
4. Console and Braille options are never cleared. They are updated only via the command line.
5. The global 'preferred_dev_console' index and 'console_set_on_cmdline'
   flag are updated consistently.

Additionally, rename braille_set_options() to
braille_update_options()
to better reflect its conditional behavior.

Behavior change:

The original code never updated the preferred console options when it was preferred more times, e.g. via the command line and/or some platform specific code, e.g. SPCR or device tree.

The new code explicitly allows to update the console options when they are preferred over the command line.

Quoted 7 lines

It mostly worked even before but only because the command line was processed early enough before handling SPCR, device tree, or other platform specific init code.

The main behavior change is when the same console is preferred more times on the command line. Newly, the later or Braille variant wins. It is a more common and expected behavior.

Sorry for the late review. I just wanted to say that the improvement is really great: documentation and code reorganization really improve the code. It was too confusing and rather problematic to follow up.

Quoted 259 lines

---
 kernel/printk/braille.h |   7 +-
 kernel/printk/printk.c  | 149 ++++++++++++++++++++++++++++++-------- --

 2 files changed, 118 insertions(+), 38 deletions(-)
kernel/printk/braille.h +0 -0
index 55cd3178a17a..0bdac303f8b1 100644
@@ -5,9 +5,10 @@
  #ifdef CONFIG_A11Y_BRAILLE_CONSOLE


 static inline void

kernel/printk/braille.h +1 -1
-braille_set_options(struct preferred_console *pc, char *brl_options)
+braille_update_options(struct preferred_console *pc, char

*brl_options)
 {

kernel/printk/braille.h +2 -1
-	pc->brl_options = brl_options;
+	if (brl_options)
+		pc->brl_options = brl_options;

 }

 /*

kernel/printk/braille.h +0 -0
@@ -29,7 +30,7 @@ _braille_unregister_console(struct console
 *console);
  #else


 static inline void

kernel/printk/braille.h +1 -1
-braille_set_options(struct preferred_console *pc, char *brl_options)
+braille_update_options(struct preferred_console *pc, char

*brl_options)
 {
 }

kernel/printk/printk.c +0 -0
index 13c98285892b..d251bf8e104f 100644
@@ -2544,18 +2544,119 @@ asmlinkage __visible void early_printk(const
 char *fmt, ...)
  }
  #endif


-static void set_user_specified(struct preferred_console *pc, bool user_specified)
+/** update_preferred_console - Update a given entry in the preferred_consoles[]
+ * table.
+ * @i: index of the entry in @preferred_consoles table which should get updated.
+ * @name: The name of the preferred console driver.
+ * @idx: Preferred console index, e.g. port number.
+ * @devname: The name of the preferred physical device.
+ * @options: Options used when setting up the console driver.
+ * @brl_options: Options used when setting up the console driver
+ * as a braille console.
+ * @user_specified: True if preferred via the kernel command line.
+ *
+ * The function ensures that the given values are consistent. Also
+ * it updates some global variables which are used to make the right
+ * decisions in register_console().
+ *
+ * Rules:
+ *
+ *   1. Either @name and valid @idx OR @devname and @idx=-1 are allowed.
+ * Note that a valid @name and @idx will get assigned later
when
+ * @devname matches during the device initialization.
+ *   2. Specify @brl_options if the console should be enabled as
+ * a Braille console [*]
+ *   3. Only matching entries can be updated.
+ *   4. @options passed via the command line are used when the same
+ * console is preferred also by some platform-specific code.
+ *
+ * [*] Braille console is using the mechanism for registering consoles
+ *     but it is very special. It is primarily used for user interaction
+ *     with the system. It neither gets printk() messages nor is associated
+ *     with /dev/console.
+ */

kernel/printk/printk.c +2 -0
+static int update_preferred_console(unsigned int i,
+				    const char *name, const short

idx,

kernel/printk/printk.c +1 -0
+				    const char *devname, char

*options,

kernel/printk/printk.c +1 -0
+				    char *brl_options, bool

user_specified)
 {

kernel/printk/printk.c +13 -2
-	if (!user_specified)
-		return;
+	struct preferred_console *pc;
+
+	if (i >= MAX_PREFERRED_CONSOLES)
+		return -E2BIG;
+
+	pc = &preferred_consoles[i];
+
+	if (!name && !devname)
+		return -EINVAL;
+
+	if (devname) {
+		/*
+		 * A valid console name and index will get assigned

when

kernel/printk/printk.c +4 -0
+		 * a matching device gets registered.
+		 */
+		if (name) {
+			pr_err("Adding a preferred console devname

with a hard-coded console name: %s, %s\n",

kernel/printk/printk.c +5 -0
+			       devname, name);
+			return -EINVAL;
+		}
+		if (pc->name[0]) {
+			pr_err("Updating a preferred console entry

with an already assigned console name via devname: %s, %s\n",

kernel/printk/printk.c +5 -0
+			       devname, pc->name);
+			return -EINVAL;
+		}
+		if (idx != -1) {
+			pr_err("Adding a preferred console devname

with a hard-coded index: %s, %d\n",

kernel/printk/printk.c +9 -0
+			       devname, idx);
+			return -EINVAL;
+		}
+
+		if (!pc->devname[0]) {
+			strscpy(pc->devname, devname);
+			pc->index = idx;
+		} else if (strcmp(pc->devname, devname) != 0) {
+			pr_err("Updating a preferred console with an

invalid devname: %s vs. %s\n",

kernel/printk/printk.c +7 -0
+			       pc->devname, devname);
+			return -EINVAL;
+		}
+	}
+
+	if (name) {
+		/* A console name must be defined with a valid

index. */

kernel/printk/printk.c +2 -0
+		if (idx < 0) {
+			pr_err("Adding a preferred console with an

invalid index: %s, %d\n",

kernel/printk/printk.c +8 -0
+			       name, idx);
+			return -EINVAL;
+		}
+
+		if (!pc->name[0]) {
+			strscpy(pc->name, name);
+			pc->index = idx;
+		} else if (strcmp(pc->name, name) != 0 || pc->index

!= idx) {

kernel/printk/printk.c +1 -0
+			pr_err("Updating a preferred console with an

invalid name or index: %s%d vs. %s%d\n",

kernel/printk/printk.c +12 -0
+			       pc->name, pc->index, name, idx);
+			return -EINVAL;
+		}
+	}
+
+	if (!pc->options || (user_specified && options))
+		pc->options = options;
+
+	braille_update_options(pc, brl_options);
+
+	if (!brl_options)
+		preferred_dev_console = i;


  /*
  * @pc console was defined by the user on the command line.
  * Do not clear when added twice also by SPCR or the device tree.
  */

kernel/printk/printk.c +0 -2
-	pc->user_specified = true;
-	/* At least one console defined by the user on the command

line. */

kernel/printk/printk.c +6 -1
-	console_set_on_cmdline = 1;
+	if (user_specified) {
+		pc->user_specified = true;
+		console_set_on_cmdline = 1;
+	}
+
+	return 0;

 }

 static int __add_preferred_console(const char *name, const short idx,

kernel/printk/printk.c +0 -0
@@ -2563,19 +2664,11 @@ static int __add_preferred_console(const char
 *name, const short idx,

     char *brl_options, bool user_specified)
 {
  struct preferred_console *pc;

kernel/printk/printk.c +1 -1
-	int i;
+	unsigned int i;


  if (!name && !devname)
  return -EINVAL;

kernel/printk/printk.c +0 -2
-	/*
-	 * We use a signed short index for struct console for device

drivers to

kernel/printk/printk.c +0 -1
-	 * indicate a not yet assigned index or port. However, a

negative index

kernel/printk/printk.c +0 -1
-	 * value is not valid when the console name and index are

defined on

kernel/printk/printk.c +0 -4
-	 * the command line.
-	 */
-	if (name && idx < 0)
-		return -EINVAL;


  /*
  * See if this tty is not yet registered, and

kernel/printk/printk.c +0 -0
@@ -2584,28 +2677,14 @@ static int __add_preferred_console(const char
 *name, const short idx,
  	for (i = 0, pc = preferred_consoles;

       i < MAX_PREFERRED_CONSOLES && (pc->name[0] || pc-

Quoted 1 line

devname[0]);

       i++, pc++) {

kernel/printk/printk.c +0 -1
-		if ((name && strcmp(pc->name, name) == 0 && pc-
Quoted 1 line

index == idx) ||

kernel/printk/printk.c +0 -1
-		    (devname && strcmp(pc->devname, devname) == 0))

{

kernel/printk/printk.c +1 -5
-			if (!brl_options)
-				preferred_dev_console = i;
-			set_user_specified(pc, user_specified);
-			return 0;
-		}
+		if (name && strcmp(pc->name, name) == 0 && pc->index

== idx)

kernel/printk/printk.c +3 -0
+			break;
+		if (devname && strcmp(pc->devname, devname) == 0)
+			break;

  }

kernel/printk/printk.c +0 -11
-	if (i == MAX_PREFERRED_CONSOLES)
-		return -E2BIG;
-	if (!brl_options)
-		preferred_dev_console = i;
-	if (name)
-		strscpy(pc->name, name);
-	if (devname)
-		strscpy(pc->devname, devname);
-	pc->options = options;
-	set_user_specified(pc, user_specified);
-	braille_set_options(pc, brl_options);

kernel/printk/printk.c +1 -2
-	pc->index = idx;
-	return 0;
+	return update_preferred_console(i, name, idx, devname,

options,

kernel/printk/printk.c +1 -0
+					brl_options,

user_specified);
 }

 static int __init console_msg_format_setup(char *str)

maintainer Reviewed-by on v2 3/9
#8 lore raw

Re: [PATCH v2 3/9] printk: Separate code for adding/updating preferred console metadata

In reply to Petr Mladek

kernel/printk/printk.c asmlinkage __visible void early_printk(const char *fmt, ...) · line 2548

Quoted 11 lines · Petr Mladek
kernel/printk/printk.c +2 -1
index 13c98285892b..d251bf8e104f 100644
@@ -2544,18 +2544,119 @@ asmlinkage __visible void early_printk(const char *fmt, ...)
 }
 #endif
 
-static void set_user_specified(struct preferred_console *pc, bool user_specified)
+/** update_preferred_console - Update a given entry in the preferred_consoles[]
+ *	table.

Perhaps the description should be:

Update or add a given entry in the preferred_consoles[] table.

If the caller didn't match an existing preferred_console, this function is called to add a new entry. This is obvious if you are looking at the caller, but it is not obvious at all if you are only looking at this function, i.e. strscpy'ing in @name or @devname is the only clue that you are dealing with a new entry.

Quoted 35 lines
kernel/printk/printk.c +33 -1
+ * @i: index of the entry in @preferred_consoles table which should get updated.
+ * @name: The name of the preferred console driver.
+ * @idx: Preferred console index, e.g. port number.
+ * @devname: The name of the preferred physical device.
+ * @options: Options used when setting up the console driver.
+ * @brl_options: Options used when setting up the console driver
+ *	as a braille console.
+ * @user_specified: True if preferred via the kernel command line.
+ *
+ * The function ensures that the given values are consistent. Also
+ * it updates some global variables which are used to make the right
+ * decisions in register_console().
+ *
+ * Rules:
+ *
+ *   1. Either @name and valid @idx OR @devname and @idx=-1 are allowed.
+ *	Note that a valid @name and @idx will get assigned later when
+ *	@devname matches during the device initialization.
+ *   2. Specify @brl_options if the console should be enabled as
+ *	a Braille console [*]
+ *   3. Only matching entries can be updated.
+ *   4. @options passed via the command line are used when the same
+ *	console is preferred also by some platform-specific code.
+ *
+ * [*] Braille console is using the mechanism for registering consoles
+ *     but it is very special. It is primarily used for user interaction
+ *     with the system. It neither gets printk() messages nor is associated
+ *     with /dev/console.
+ */
+static int update_preferred_console(unsigned int i,
+				    const char *name, const short idx,
+				    const char *devname, char *options,
+				    char *brl_options, bool user_specified)
 {
-	if (!user_specified)

kernel/printk/printk.c asmlinkage __visible void early_printk(const char *fmt, ...) · line 2591

Quoted 10 lines
kernel/printk/printk.c +9 -1
-		return;
+	struct preferred_console *pc;
+
+	if (i >= MAX_PREFERRED_CONSOLES)
+		return -E2BIG;
+
+	pc = &preferred_consoles[i];
+
+	if (!name && !devname)
+		return -EINVAL;

You are adding detailed error messages for all possible wrong calls except for this on. Maybe this should be covered as well with:

	if (WARN_ON(!name && !devname))
		return -EINVAL;
Quoted 14 lines
kernel/printk/printk.c +14 -0
+	if (devname) {
+		/*
+		 * A valid console name and index will get assigned when
+		 * a matching device gets registered.
+		 */
+		if (name) {
+			pr_err("Adding a preferred console devname with a hard-coded console name: %s, %s\n",
+			       devname, name);
+			return -EINVAL;
+		}
+		if (pc->name[0]) {
+			pr_err("Updating a preferred console entry with an already assigned console name via devname: %s, %s\n",
+			       devname, pc->name);
+			return -EINVAL;

kernel/printk/printk.c asmlinkage __visible void early_printk(const char *fmt, ...) · line 2616

Quoted 10 lines
kernel/printk/printk.c +10 -0
+		}
+		if (idx != -1) {
+			pr_err("Adding a preferred console devname with a hard-coded index: %s, %d\n",
+			       devname, idx);
+			return -EINVAL;
+		}
+
+		if (!pc->devname[0]) {
+			strscpy(pc->devname, devname);
+			pc->index = idx;

This block is about setting the devname. Setting the index here as well is copied code and well hidden. I would keep the index setting outside the devname and name blocks (as it was previously).

Quoted 8 lines
kernel/printk/printk.c +8 -0
+		} else if (strcmp(pc->devname, devname) != 0) {
+			pr_err("Updating a preferred console with an invalid devname: %s vs. %s\n",
+			       pc->devname, devname);
+			return -EINVAL;
+		}
+	}
+
+	if (name) {

kernel/printk/printk.c asmlinkage __visible void early_printk(const char *fmt, ...) · line 2634

Quoted 10 lines
kernel/printk/printk.c +10 -0
+		/* A console name must be defined with a valid index. */
+		if (idx < 0) {
+			pr_err("Adding a preferred console with an invalid index: %s, %d\n",
+			       name, idx);
+			return -EINVAL;
+		}
+
+		if (!pc->name[0]) {
+			strscpy(pc->name, name);
+			pc->index = idx;

Here is the copied code. This block is about setting the name.

kernel/printk/printk.c asmlinkage __visible void early_printk(const char *fmt, ...) · line 2640

Quoted 6 lines
kernel/printk/printk.c +6 -0
+		} else if (strcmp(pc->name, name) != 0 || pc->index != idx) {
+			pr_err("Updating a preferred console with an invalid name or index: %s%d vs. %s%d\n",
+			       pc->name, pc->index, name, idx);
+			return -EINVAL;
+		}
+	}

I would put the index setting here as it is relevant regardless of how the devname or name was updated.

	pc->index = idx;

With or without implementing my suggestions:

maintainer
#9 lore raw

Re: [PATCH v2 3/9] printk: Separate code for adding/updating preferred console metadata

Quoted 16 lines · John Ogness

kernel/printk/printk.c asmlinkage __visible void early_printk(const char *fmt, ...) · line 2634

Quoted 3 lines
kernel/printk/printk.c +3 -0
+		if (!pc->name[0]) {
+			strscpy(pc->name, name);
+			pc->index = idx;

Here is the copied code. This block is about setting the name.

kernel/printk/printk.c asmlinkage __visible void early_printk(const char *fmt, ...) · line 2640

Quoted 6 lines
kernel/printk/printk.c +6 -0
+		} else if (strcmp(pc->name, name) != 0 || pc->index != idx) {
+			pr_err("Updating a preferred console with an invalid name or index: %s%d vs. %s%d\n",
+			       pc->name, pc->index, name, idx);
+			return -EINVAL;
+		}
+	}

I would put the index setting here as it is relevant regardless of how the devname or name was updated.

Quoted 1 line
	pc->index = idx;

Ah, I guess you only wanted to update @index if it is a new entry (because otherwise it will already have the value of @idx).

If you want to keep the index setting in the devname and name blocks, maybe just adding a comment to clarify it is a new entry:

	if (!pc->devname[0]) {
		/* This is a new entry */
		strscpy(pc->devname, devname);
		pc->index = idx;

...

	if (!pc->name[0]) {
		/* This is a new entry */
		strscpy(pc->name, name);
		pc->index = idx;

John

author maintainer
#10 lore raw

Re: [PATCH v2 3/9] printk: Separate code for adding/updating preferred console metadata

Quoted 17 lines · John Ogness
Quoted 16 lines · John Ogness

kernel/printk/printk.c asmlinkage __visible void early_printk(const char *fmt, ...) · line 2634

Quoted 3 lines
kernel/printk/printk.c +3 -0
+		if (!pc->name[0]) {
+			strscpy(pc->name, name);
+			pc->index = idx;

Here is the copied code. This block is about setting the name.

kernel/printk/printk.c asmlinkage __visible void early_printk(const char *fmt, ...) · line 2640

Quoted 6 lines
kernel/printk/printk.c +6 -0
+		} else if (strcmp(pc->name, name) != 0 || pc->index != idx) {
+			pr_err("Updating a preferred console with an invalid name or index: %s%d vs. %s%d\n",
+			       pc->name, pc->index, name, idx);
+			return -EINVAL;
+		}
+	}

I would put the index setting here as it is relevant regardless of how the devname or name was updated.

Quoted 4 lines
Quoted 1 line
	pc->index = idx;

Ah, I guess you only wanted to update @index if it is a new entry (because otherwise it will already have the value of @idx).

Exactly ;-)

Quoted 8 lines

If you want to keep the index setting in the devname and name blocks, maybe just adding a comment to clarify it is a new entry:

	if (!pc->devname[0]) {
		/* This is a new entry */
		strscpy(pc->devname, devname);
		pc->index = idx;
Quoted 6 lines

...

	if (!pc->name[0]) {
		/* This is a new entry */
		strscpy(pc->name, name);
		pc->index = idx;

I am going to add the comments in v3.

Best Regards,
Petr

author maintainer
#11 lore raw

Re: [PATCH v2 3/9] printk: Separate code for adding/updating preferred console metadata

In reply to John Ogness
Quoted 15 lines · John Ogness

kernel/printk/printk.c asmlinkage __visible void early_printk(const char *fmt, ...) · line 2548

Quoted 11 lines · Petr Mladek
kernel/printk/printk.c +2 -1
index 13c98285892b..d251bf8e104f 100644
@@ -2544,18 +2544,119 @@ asmlinkage __visible void early_printk(const char *fmt, ...)
 }
 #endif
 
-static void set_user_specified(struct preferred_console *pc, bool user_specified)
+/** update_preferred_console - Update a given entry in the preferred_consoles[]
+ *	table.

Perhaps the description should be:

Quoted 7 lines

Update or add a given entry in the preferred_consoles[] table.

If the caller didn't match an existing preferred_console, this function is called to add a new entry. This is obvious if you are looking at the caller, but it is not obvious at all if you are only looking at this function, i.e. strscpy'ing in @name or @devname is the only clue that you are dealing with a new entry.

Good point! I'll update the comment in v3. Also I'll rename the function to add_or_update_preferred_console(). It is long but the function is used only once so it does not harm that much ;-)

Quoted 49 lines
Quoted 35 lines
kernel/printk/printk.c +33 -1
+ * @i: index of the entry in @preferred_consoles table which should get updated.
+ * @name: The name of the preferred console driver.
+ * @idx: Preferred console index, e.g. port number.
+ * @devname: The name of the preferred physical device.
+ * @options: Options used when setting up the console driver.
+ * @brl_options: Options used when setting up the console driver
+ *	as a braille console.
+ * @user_specified: True if preferred via the kernel command line.
+ *
+ * The function ensures that the given values are consistent. Also
+ * it updates some global variables which are used to make the right
+ * decisions in register_console().
+ *
+ * Rules:
+ *
+ *   1. Either @name and valid @idx OR @devname and @idx=-1 are allowed.
+ *	Note that a valid @name and @idx will get assigned later when
+ *	@devname matches during the device initialization.
+ *   2. Specify @brl_options if the console should be enabled as
+ *	a Braille console [*]
+ *   3. Only matching entries can be updated.
+ *   4. @options passed via the command line are used when the same
+ *	console is preferred also by some platform-specific code.
+ *
+ * [*] Braille console is using the mechanism for registering consoles
+ *     but it is very special. It is primarily used for user interaction
+ *     with the system. It neither gets printk() messages nor is associated
+ *     with /dev/console.
+ */
+static int update_preferred_console(unsigned int i,
+				    const char *name, const short idx,
+				    const char *devname, char *options,
+				    char *brl_options, bool user_specified)
 {
-	if (!user_specified)

kernel/printk/printk.c asmlinkage __visible void early_printk(const char *fmt, ...) · line 2591

Quoted 10 lines
kernel/printk/printk.c +9 -1
-		return;
+	struct preferred_console *pc;
+
+	if (i >= MAX_PREFERRED_CONSOLES)
+		return -E2BIG;
+
+	pc = &preferred_consoles[i];
+
+	if (!name && !devname)
+		return -EINVAL;

You are adding detailed error messages for all possible wrong calls except for this on. Maybe this should be covered as well with:

Quoted 2 lines
	if (WARN_ON(!name && !devname))
		return -EINVAL;

Makes sense.

Also I am going print an error when reached the maximal number of preferred consoles in the above check. It would look like:

	if (i >= MAX_PREFERRED_CONSOLES) {
		pr_err_once("Reached maximal number of preferred consoles.\n");
		return -E2BIG;
	}

It would be nice to print some more details. But it is not that easy because we do not know whether "name" or "devname" is defined, ... IMHO, it is not worth the complexity. I guess not nobody has reached the limit in a real life scenario yet.

Best Regards,
Petr

author maintainer
#12 lore raw

PATCH v2 4/9 printk: Cleanup _braille_(un)register_console() wrappers

In reply to Petr Mladek

The _braille_(un)register_console() wrappers currently attempt to hide implementation details like the CON_BRL flag and pc->brl_options. This forces callers to handle an unconventional tri-state return value (0 for NOP, >0 for success, <0 for error), which makes the control flow harder to follow and non-standard.

Refactor the wrappers to use standard kernel return codes (0 for success, -ERRCODE on failure). Move the responsibility of checking brl_options to the caller to make the logic more explicit.

Additionally, move the assignment of the CON_BRL flag from the internal wrapper to braille_register_console(). This aligns it with how CON_ENABLED is handled. To maintain symmetry and fix a potential bug where flags might persist after removal, explicitly clear both CON_ENABLED and CON_BRL in braille_unregister_console().

The patch should not change the existing behavior.

---
 drivers/accessibility/braille/braille_console.c |  7 ++++---
 kernel/printk/braille.c                         | 16 +++-------------
 kernel/printk/braille.h                         | 12 ++++++++++++
 kernel/printk/printk.c                          | 13 +++++--------
 4 files changed, 24 insertions(+), 24 deletions(-)
drivers/accessibility/braille/braille_console.c +4 -3
index 06b43b678d6e..7b324329882f 100644
@@ -360,12 +360,12 @@ int braille_register_console(struct console *console, int index,
 		if (ret != 0)
 			return ret;
 	}
-	console->flags |= CON_ENABLED;
+	console->flags |= CON_ENABLED | CON_BRL;
 	console->index = index;
 	braille_co = console;
 	register_keyboard_notifier(&keyboard_notifier_block);
 	register_vt_notifier(&vt_notifier_block);
-	return 1;
+	return 0;
 }
 
 int braille_unregister_console(struct console *console)
@@ -375,5 +375,6 @@ int braille_unregister_console(struct console *console)
 	unregister_keyboard_notifier(&keyboard_notifier_block);
 	unregister_vt_notifier(&vt_notifier_block);
 	braille_co = NULL;
-	return 1;
+	console->flags &= ~(CON_ENABLED | CON_BRL);
+	return 0;
 }
kernel/printk/braille.c +3 -13
index 9d21a2bb1d38..593f83eb0487 100644
@@ -37,22 +37,12 @@ int _braille_console_setup(char **str, char **brl_options)
 int
 _braille_register_console(struct console *console, struct preferred_console *pc)
 {
-	int rtn = 0;
-
-	if (pc->brl_options) {
-		console->flags |= CON_BRL;
-		rtn = braille_register_console(console, pc->index, pc->options,
-					       pc->brl_options);
-	}
-
-	return rtn;
+	return braille_register_console(console, pc->index, pc->options,
+					pc->brl_options);
 }
 
 int
 _braille_unregister_console(struct console *console)
 {
-	if (console->flags & CON_BRL)
-		return braille_unregister_console(console);
-
-	return 0;
+	return braille_unregister_console(console);
 }
kernel/printk/braille.h +12 -0
index 0bdac303f8b1..ec5feac1f508 100644
@@ -11,6 +11,12 @@ braille_update_options(struct preferred_console *pc, char *brl_options)
 		pc->brl_options = brl_options;
 }
 
+static inline bool
+is_braille_console_preferred(struct preferred_console *pc)
+{
+	return (!!pc->brl_options);
+}
+
 /*
  * Setup console according to braille options.
  * Return -EINVAL on syntax error, 0 on success (or no braille option was
@@ -34,6 +40,12 @@ braille_update_options(struct preferred_console *pc, char *brl_options)
 {
 }
 
+static inline bool
+is_braille_console_preferred(struct preferred_console *pc)
+{
+	return false;
+}
+
 static inline int
 _braille_console_setup(char **str, char **brl_options)
 {
kernel/printk/printk.c +5 -8
index d251bf8e104f..7a3bbb0cb794 100644
@@ -4001,8 +4001,8 @@ static int try_enable_preferred_console(struct console *newcon,
 			if (newcon->index < 0)
 				newcon->index = pc->index;
 
-			if (_braille_register_console(newcon, pc))
-				return 0;
+			if (is_braille_console_preferred(pc))
+				return _braille_register_console(newcon, pc);
 
 			err = console_call_setup(newcon, pc->options);
 			if (err)
@@ -4314,17 +4314,14 @@ static int unregister_console_locked(struct console *console)
 	bool found_boot_con = false;
 	unsigned long flags;
 	struct console *c;
-	int res;
+	int res = 0;
 
 	lockdep_assert_console_list_lock_held();
 
 	con_printk(KERN_INFO, console, "disabled\n");
 
-	res = _braille_unregister_console(console);
-	if (res < 0)
-		return res;
-	if (res > 0)
-		return 0;
+	if (console->flags & CON_BRL)
+		return _braille_unregister_console(console);
 
 	if (!console_is_registered_locked(console))
 		res = -ENODEV;
Signature · 1 line
2.53.0
maintainer Reviewed-by on v2 4/9
#13 lore raw

Re: [PATCH v2 4/9] printk: Cleanup _braille_(un)register_console() wrappers

Quoted 32 lines · Sashiko
Quoted 7 lines
drivers/accessibility/braille/braille_console.c +0 -0
index 06b43b678d6e..7b324329882f 100644
@@ -360,12 +360,12 @@ int braille_register_console(struct console *console, int index,
 		if (ret != 0)
 			return ret;

drivers/accessibility/braille/braille_console.c int braille_register_console(struct console *console, int index, · line 369

Quoted 10 lines
drivers/accessibility/braille/braille_console.c +2 -2
 	}
-	console->flags |= CON_ENABLED;
+	console->flags |= CON_ENABLED | CON_BRL;
 	console->index = index;
 	braille_co = console;
 	register_keyboard_notifier(&keyboard_notifier_block);
 	register_vt_notifier(&vt_notifier_block);
-	return 1;
+	return 0;
 }

While reviewing this function, I noticed a pre-existing regression. The printk subsystem relies on console_lock() to serialize console setup against boot consoles that might be actively printing to the same hardware port. For normal consoles, this synchronization is handled explicitly:

kernel/printk/printk.c:console_call_setup() {
    ...
    console_lock();
    err = newcon->setup(newcon, options);
    console_unlock();
    ...
}
Quoted 7 lines

However, it looks like braille_register_console() bypasses this protection and directly invokes console->setup() just above this block without acquiring console_lock().

Could this unprotected setup call cause a data race or hardware state corruption if the underlying driver shares the hardware with an active boot console?

I do not know enough about braille consoles if they can also be early consoles, but it makes sense to synchronize the ->setup() callback. Something like this:

drivers/accessibility/braille/braille_console.c +2 -0
@@ -356,7 +356,9 @@ int braille_register_console(struct console *console, int index,
 	if (braille_co)
 		return -ENODEV;
 	if (console->setup) {
+		console_lock();
 		ret = console->setup(console, console_options);
+		console_unlock();
 		if (ret != 0)
 			return ret;
 	}
Quoted 16 lines

drivers/accessibility/braille/braille_console.c int braille_unregister_console(struct console *console) · line 380

Quoted 9 lines
drivers/accessibility/braille/braille_console.c +2 -1
 int braille_unregister_console(struct console *console)
@@ -375,5 +375,6 @@ int braille_unregister_console(struct console *console)
 	unregister_keyboard_notifier(&keyboard_notifier_block);
 	unregister_vt_notifier(&vt_notifier_block);
 	braille_co = NULL;
-	return 1;
+	console->flags &= ~(CON_ENABLED | CON_BRL);
+	return 0;
 }

This also appears to be a pre-existing regression. The unregister_keyboard_notifier() and unregister_vt_notifier() functions remove callbacks from atomic notifier chains. Since atomic notifiers execute their callbacks under RCU read lock, unregistering them only unlinks the node without blocking for concurrent callbacks to finish.

Quoted 7 lines

By immediately clearing the global braille_co pointer and returning, could a concurrently executing keyboard_notifier_call that already passed the braille_co check on another CPU cause a use-after-free or null pointer dereference?

Does this function need a synchronize_rcu() before returning to ensure all callbacks have completed?

atomic_notifier_chain_unregister() already calls synchronize_rcu() before returning, so no action is needed here.

For this patch as it is:

(The console lock/unlock should be a separate patch.)

John

author maintainer
#14 lore raw

PATCH v2 5/9 printk: Separate code for enabling console

In reply to Petr Mladek

There are several code paths which try to enable a newly registered console. Move the logic into a separate try_enable_console() function.

It simplifies a bit the long register_console() function definition.

Also followup patches are going to add even more code paths. And it will be easier to use "return" when it does not make sense to try other variants.

The patch does not change the existing behavior.

---
 kernel/printk/printk.c | 64 ++++++++++++++++++++++++------------------
 1 file changed, 36 insertions(+), 28 deletions(-)
kernel/printk/printk.c +36 -28
index 7a3bbb0cb794..2543c810efcb 100644
@@ -4040,6 +4040,41 @@ static void try_enable_default_console(struct console *newcon)
 		newcon->flags |= CON_CONSDEV;
 }
 
+#define console_first()				\
+	hlist_entry(console_list.first, struct console, node)
+
+static int try_enable_console(struct console *newcon)
+{
+	int err;
+
+	/*
+	 * See if we want to enable this console driver by default.
+	 *
+	 * Nope when a console is preferred by the command line, device
+	 * tree, or SPCR.
+	 *
+	 * The first real console with tty binding (driver) wins. More
+	 * consoles might get enabled before the right one is found.
+	 *
+	 * Note that a console with tty binding will have CON_CONSDEV
+	 * flag set and will be first in the list.
+	 */
+	if (preferred_dev_console < 0) {
+		if (hlist_empty(&console_list) || !console_first()->device ||
+		    console_first()->flags & CON_BOOT) {
+			try_enable_default_console(newcon);
+		}
+	}
+
+	/* See if this console matches one we selected on the command line */
+	err = try_enable_preferred_console(newcon, true);
+	if (err != -ENOENT)
+		return err;
+
+	/* If not, try to match against the platform default(s) */
+	return try_enable_preferred_console(newcon, false);
+}
+
 /* Return the starting sequence number for a newly registered console. */
 static u64 get_init_console_seq(struct console *newcon, bool bootcon_registered)
 {
@@ -4114,9 +4149,6 @@ static u64 get_init_console_seq(struct console *newcon, bool bootcon_registered)
 	return init_seq;
 }
 
-#define console_first()				\
-	hlist_entry(console_list.first, struct console, node)
-
 static int unregister_console_locked(struct console *console);
 
 /*
@@ -4178,31 +4210,7 @@ void register_console(struct console *newcon)
 			goto unlock;
 	}
 
-	/*
-	 * See if we want to enable this console driver by default.
-	 *
-	 * Nope when a console is preferred by the command line, device
-	 * tree, or SPCR.
-	 *
-	 * The first real console with tty binding (driver) wins. More
-	 * consoles might get enabled before the right one is found.
-	 *
-	 * Note that a console with tty binding will have CON_CONSDEV
-	 * flag set and will be first in the list.
-	 */
-	if (preferred_dev_console < 0) {
-		if (hlist_empty(&console_list) || !console_first()->device ||
-		    console_first()->flags & CON_BOOT) {
-			try_enable_default_console(newcon);
-		}
-	}
-
-	/* See if this console matches one we selected on the command line */
-	err = try_enable_preferred_console(newcon, true);
-
-	/* If not, try to match against the platform default(s) */
-	if (err == -ENOENT)
-		err = try_enable_preferred_console(newcon, false);
+	err = try_enable_console(newcon);
 
 	/* printk() messages are not printed to the Braille console. */
 	if (err || newcon->flags & CON_BRL) {
Signature · 1 line
2.53.0
Acked-by on v2 5/9
#15 lore raw

Re: [PATCH v2 5/9] printk: Separate code for enabling console

Quoted 6 lines · Petr Mladek

There are several code paths which try to enable a newly registered console. Move the logic into a separate try_enable_console() function.

It simplifies a bit the long register_console() function definition.

Quoted 8 lines

Also followup patches are going to add even more code paths. And it will
be easier to use "return" when it does not make sense to try other variants.

The patch does not change the existing behavior.

Quoted 109 lines

---
 kernel/printk/printk.c | 64 ++++++++++++++++++++++++---------------- --

 1 file changed, 36 insertions(+), 28 deletions(-)
kernel/printk/printk.c +0 -0
index 7a3bbb0cb794..2543c810efcb 100644
@@ -4040,6 +4040,41 @@ static void try_enable_default_console(struct
 console *newcon)
  		newcon->flags |= CON_CONSDEV;
  }

kernel/printk/printk.c +11 -0
+#define console_first()				\
+	hlist_entry(console_list.first, struct console, node)
+
+static int try_enable_console(struct console *newcon)
+{
+	int err;
+
+	/*
+	 * See if we want to enable this console driver by default.
+	 *
+	 * Nope when a console is preferred by the command line,

device

kernel/printk/printk.c +3 -0
+	 * tree, or SPCR.
+	 *
+	 * The first real console with tty binding (driver) wins.

More

kernel/printk/printk.c +3 -0
+	 * consoles might get enabled before the right one is found.
+	 *
+	 * Note that a console with tty binding will have

CON_CONSDEV

kernel/printk/printk.c +4 -0
+	 * flag set and will be first in the list.
+	 */
+	if (preferred_dev_console < 0) {
+		if (hlist_empty(&console_list) || !console_first()-
Quoted 1 line

device ||

kernel/printk/printk.c +6 -0
+		    console_first()->flags & CON_BOOT) {
+			try_enable_default_console(newcon);
+		}
+	}
+
+	/* See if this console matches one we selected on the

command line */

kernel/printk/printk.c +8 -0
+	err = try_enable_preferred_console(newcon, true);
+	if (err != -ENOENT)
+		return err;
+
+	/* If not, try to match against the platform default(s) */
+	return try_enable_preferred_console(newcon, false);
+}
+

 /* Return the starting sequence number for a newly registered console. */
 static u64 get_init_console_seq(struct console *newcon, bool bootcon_registered)
 {

kernel/printk/printk.c +0 -0
@@ -4114,9 +4149,6 @@ static u64 get_init_console_seq(struct console
 *newcon, bool bootcon_registered)
  	return init_seq;
  }

kernel/printk/printk.c +0 -3
-#define console_first()				\
-	hlist_entry(console_list.first, struct console, node)
-

 static int unregister_console_locked(struct console *console);
 /*

kernel/printk/printk.c +0 -0
@@ -4178,31 +4210,7 @@ void register_console(struct console *newcon)
  			goto unlock;
  	}

kernel/printk/printk.c +0 -4
-	/*
-	 * See if we want to enable this console driver by default.
-	 *
-	 * Nope when a console is preferred by the command line,

device

kernel/printk/printk.c +0 -3
-	 * tree, or SPCR.
-	 *
-	 * The first real console with tty binding (driver) wins.

More

kernel/printk/printk.c +0 -3
-	 * consoles might get enabled before the right one is found.
-	 *
-	 * Note that a console with tty binding will have

CON_CONSDEV

kernel/printk/printk.c +0 -4
-	 * flag set and will be first in the list.
-	 */
-	if (preferred_dev_console < 0) {
-		if (hlist_empty(&console_list) || !console_first()-
Quoted 1 line

device ||

kernel/printk/printk.c +0 -6
-		    console_first()->flags & CON_BOOT) {
-			try_enable_default_console(newcon);
-		}
-	}
-
-	/* See if this console matches one we selected on the

command line */

kernel/printk/printk.c +1 -5
-	err = try_enable_preferred_console(newcon, true);
-
-	/* If not, try to match against the platform default(s) */
-	if (err == -ENOENT)
-		err = try_enable_preferred_console(newcon, false);
+	err = try_enable_console(newcon);


  /* printk() messages are not printed to the Braille console. */
  if (err || newcon->flags & CON_BRL) {

maintainer Reviewed-by on v2 5/9
#16 lore raw

Re: [PATCH v2 5/9] printk: Separate code for enabling console

In reply to Petr Mladek
Quoted 5 lines · Petr Mladek

There are several code paths which try to enable a newly registered console. Move the logic into a separate try_enable_console() function.

It simplifies a bit the long register_console() function definition.

Quoted 7 lines

Also followup patches are going to add even more code paths. And it will be easier to use "return" when it does not make sense to try other variants.

The patch does not change the existing behavior.

author maintainer
#17 lore raw

PATCH v2 6/9 printk: Try to register each console as Braille first

In reply to Petr Mladek

Braille consoles are unique: they can only be enabled via the command line and use the preferred console framework for initialization, yet they are never added to the console_list or associated with /dev/console. Because of this, the preferred_console variable remains unset when only a Braille console is requested.

Currently, try_enable_preferred_console() must be called even when "preferred_dev_console" variable is not set, just to catch these "hidden" Braille requests.

Refactor the logic by adding a parameter to try_enable_preferred_console() to explicitly handle Braille vs. non-Braille cases. It will eventually allow to skip try_enable_preferred_console() when there are no preferred consoles. This improves code robustness by ensuring the console setup is explicit and only performed once.

Note that _braille_register_console() is skipped when the given console driver has a match() callback and it succeeded. It means that it took over an early console and can't be used as a Braille console.

As a result try_enable_braille_console() might return success even when it did not enabled the console in the Braille mode. It is the reason why register_console() has to explicitly check whether CON_BRL flag was really set and could skip the further steps.

The refactoring even fixes two subtle bugs:

1. When only the Braille console is defined on the command line, the original code might attempt to enable the same console twice—once as a default and once as a Braille console. This results in calling the setup() callback twice and incorrectly setting the CON_CONSDEV flag.

2. When the same console is defined on the command line using devname and then as Braille console, for example:

      console=00:00:0.0,115200 console=brl,ttyS0,115200

It would have two separate entries in preferred_consoles[] array.

The 2nd (Braille) entry would be used when univ8250_console_init() tries to register the generic "ttyS" console driver. Note that the 1st entry still does not have defined the "name" entry at this stage.

The 1st non-Braille entry would be used later when serial8250_init() registers all found devices, assigns "tty0" for the given "00:00:0.0" devname and tries to register the same struct console once again.

The original code would call newcon->setup() twice in this scenario. It won't add the console into console_list only because the later check in register_console() would detect CON_BRL flag set from the 1st registration and return early.

---
 kernel/printk/printk.c | 56 +++++++++++++++++++++++++++++++++++++-----
 1 file changed, 50 insertions(+), 6 deletions(-)
kernel/printk/printk.c +50 -6
index 2543c810efcb..e34955189d16 100644
@@ -367,6 +367,7 @@ static int console_locked;
 static struct preferred_console preferred_consoles[MAX_PREFERRED_CONSOLES];
 
 static int preferred_dev_console = -1;
+static bool want_braille_console;
 int console_set_on_cmdline;
 EXPORT_SYMBOL(console_set_on_cmdline);
 
@@ -2644,7 +2645,9 @@ static int update_preferred_console(unsigned int i,
 
 	braille_update_options(pc, brl_options);
 
-	if (!brl_options)
+	if (brl_options)
+		want_braille_console = true;
+	else
 		preferred_dev_console = i;
 
 	/*
@@ -3975,8 +3978,9 @@ static int console_call_setup(struct console *newcon, char *options)
  * Care need to be taken with consoles that are statically
  * enabled such as netconsole
  */
-static int try_enable_preferred_console(struct console *newcon,
-					bool user_specified)
+static int __try_enable_preferred_console(struct console *newcon,
+					  bool user_specified,
+					  bool try_only_braille)
 {
 	struct preferred_console *pc;
 	int i, err;
@@ -3987,8 +3991,19 @@ static int try_enable_preferred_console(struct console *newcon,
 		/* Console not yet initialized? */
 		if (!pc->name[0])
 			continue;
-		if (pc->user_specified != user_specified)
-			continue;
+
+		/*
+		 * @try_only_braille and @user_specifified define which
+		 * preferred console entries are handled in this round.
+		 */
+		if (try_only_braille) {
+			if (!is_braille_console_preferred(pc))
+				continue;
+		} else {
+			if (pc->user_specified != user_specified)
+				continue;
+		}
+
 		if (!newcon->match ||
 		    newcon->match(newcon, pc->name, pc->index, pc->options) != 0) {
 			/* default matching */
@@ -4001,7 +4016,7 @@ static int try_enable_preferred_console(struct console *newcon,
 			if (newcon->index < 0)
 				newcon->index = pc->index;
 
-			if (is_braille_console_preferred(pc))
+			if (try_only_braille)
 				return _braille_register_console(newcon, pc);
 
 			err = console_call_setup(newcon, pc->options);
@@ -4025,6 +4040,17 @@ static int try_enable_preferred_console(struct console *newcon,
 	return -ENOENT;
 }
 
+static int try_enable_preferred_console(struct console *newcon,
+					bool user_specified)
+{
+	return __try_enable_preferred_console(newcon, user_specified, false);
+}
+
+static int try_enable_braille_console(struct console *newcon)
+{
+	return __try_enable_preferred_console(newcon, true, true);
+}
+
 /* Try to enable the console unconditionally */
 static void try_enable_default_console(struct console *newcon)
 {
@@ -4047,6 +4073,24 @@ static int try_enable_console(struct console *newcon)
 {
 	int err;
 
+	/*
+	 * First, try to enable the console driver as a Braille console.
+	 * It would have metadata in the preferred_consoles[] array.
+	 * But it won't be counted as @preferred_console because
+	 * it does not get printk() messages and is not associated
+	 * with /dev/console.
+	 *
+	 * Note that it might succeed also when the driver has a match()
+	 * callback and it took over a boot console. In this case,
+	 * the driver will continue working as a classic non-Braille
+	 * console.
+	 */
+	if (want_braille_console) {
+		err = try_enable_braille_console(newcon);
+		if (err != -ENOENT)
+			return err;
+	}
+
 	/*
 	 * See if we want to enable this console driver by default.
 	 *
Signature · 1 line
2.53.0
author maintainer
#18 lore raw

PATCH v2 7/9 printk: Do not set Braille console as preferred_console

In reply to Petr Mladek

The Braille console reuses the framework for handling consoles preferred via the command line. However, it is a special-purpose interface that neither receives standard printk messages nor associates with /dev/console.

Currently, the "preferred_dev_console" variable can point to a Braille console entry in the "preferred_consoles[]" array. This occurs if an entry was first created for a non-Braille console, but a later 'console=' parameter redefined it as a Braille console.

Since a Braille console will only ever be enabled as such, it should not be tracked as the primary system console. Adjust the logic to ensure "preferred_dev_console" continues to point to the previously designated normal console instead.

---
 kernel/printk/printk.c | 20 +++++++++++++++++---
 1 file changed, 17 insertions(+), 3 deletions(-)
kernel/printk/printk.c +17 -3
index e34955189d16..9143a050c289 100644
@@ -367,6 +367,7 @@ static int console_locked;
 static struct preferred_console preferred_consoles[MAX_PREFERRED_CONSOLES];
 
 static int preferred_dev_console = -1;
+static int preferred_dev_console_prev = -1;
 static bool want_braille_console;
 int console_set_on_cmdline;
 EXPORT_SYMBOL(console_set_on_cmdline);
@@ -2566,10 +2567,11 @@ asmlinkage __visible void early_printk(const char *fmt, ...)
  *	Note that a valid @name and @idx will get assigned later when
  *	@devname matches during the device initialization.
  *   2. Specify @brl_options if the console should be enabled as
- *	a Braille console [*]
+ *	a Braille console.
  *   3. Only matching entries can be updated.
  *   4. @options passed via the command line are used when the same
  *	console is preferred also by some platform-specific code.
+ *   5. Braille console is never associated with /dev/console.[*]
  *
  * [*] Braille console is using the mechanism for registering consoles
  *     but it is very special. It is primarily used for user interaction
@@ -2645,10 +2647,22 @@ static int update_preferred_console(unsigned int i,
 
 	braille_update_options(pc, brl_options);
 
-	if (brl_options)
+	/*
+	 * The last preferred console should get associated with /dev/console.
+	 * Except for the Braille console which can't get associated with
+	 * /dev/console. One level history should be enough because only one,
+	 * the VisioBraille device, is supported at the moment.
+	 */
+	if (brl_options) {
 		want_braille_console = true;
-	else
+		if (preferred_dev_console == i) {
+			preferred_dev_console = preferred_dev_console_prev;
+			preferred_dev_console_prev = -1;
+		}
+	} else if (!is_braille_console_preferred(pc)) {
+		preferred_dev_console_prev = preferred_dev_console;
 		preferred_dev_console = i;
+	}
 
 	/*
 	 * @pc console was defined by the user on the command line.
Signature · 1 line
2.53.0
author maintainer
#19 lore raw

PATCH v2 8/9 printk: Handle pre-enabled consoles in the top-level try_enable_console()

In reply to Petr Mladek

The function try_enable_preferred_console() currently has the non-obvious side effect of returning success for consoles that are already pre-enabled. This obscures the logic flow during console registration.

Move the check for pre-enabled consoles directly into the top-level try_enable_console(). This change makes the handling of pre-enabled consoles explicit and easier to follow.

Furthermore, this separation lays the groundwork for future cleanups where try_enable_preferred_console() can be restricted to cases where an entry actually exists in the preferred_consoles[] array.

Possible behavior change:

try_enable_preferred_console() will newly be called also with @user_specified parameter set to "false" when it failed with the "true" variant. But it looks like the right way to do. It will allow to call newcon->setup() when the console was preferred by some platform specific code.

---
 kernel/printk/printk.c | 25 +++++++++++++------------
 1 file changed, 13 insertions(+), 12 deletions(-)
kernel/printk/printk.c +13 -12
index 9143a050c289..91c3be6843bc 100644
@@ -3988,9 +3988,6 @@ static int console_call_setup(struct console *newcon, char *options)
  * the newly registered console with any of the ones selected
  * by either the command line or add_preferred_console() and
  * setup/enable it.
- *
- * Care need to be taken with consoles that are statically
- * enabled such as netconsole
  */
 static int __try_enable_preferred_console(struct console *newcon,
 					  bool user_specified,
@@ -4043,14 +4040,6 @@ static int __try_enable_preferred_console(struct console *newcon,
 		return 0;
 	}
 
-	/*
-	 * Some consoles, such as pstore and netconsole, can be enabled even
-	 * without matching. Accept the pre-enabled consoles only when match()
-	 * and setup() had a chance to be called.
-	 */
-	if (newcon->flags & CON_ENABLED && pc->user_specified == user_specified)
-		return 0;
-
 	return -ENOENT;
 }
 
@@ -4130,7 +4119,19 @@ static int try_enable_console(struct console *newcon)
 		return err;
 
 	/* If not, try to match against the platform default(s) */
-	return try_enable_preferred_console(newcon, false);
+	err = try_enable_preferred_console(newcon, false);
+	if (err != -ENOENT)
+		return err;
+
+	/*
+	 * Some consoles, such as pstore and netconsole, can be enabled even
+	 * without matching. Accept them at this stage when they had a chance
+	 * to match() and call setup().
+	 */
+	if (newcon->flags & CON_ENABLED)
+		err = 0;
+
+	return err;
 }
 
 /* Return the starting sequence number for a newly registered console. */
Signature · 1 line
2.53.0
author maintainer
#20 lore raw

PATCH v2 9/9 printk: Try enable preferred consoles only when there are any

In reply to Petr Mladek

try_enable_preferred_console() used to be always called because it had several hidden effects, namely:

- enabled Braille consoles which were ignored by "preferred_dev_console" because they were not associated with /dev/console.

- returned success when a console was pre-enabled using CON_ENABLED flag.

- returned success when a console was enabled by default because try_enable_default_console() did not return success.

The first two hidden effects were removed in previous patches. Remove the last one so that try_enable_preferred_console() can be called only when any non-Braille console is preferred.

---
 kernel/printk/printk.c | 15 +++++++++++----
 1 file changed, 11 insertions(+), 4 deletions(-)
kernel/printk/printk.c +11 -4
index 91c3be6843bc..4098ed3b735f 100644
@@ -4055,18 +4055,23 @@ static int try_enable_braille_console(struct console *newcon)
 }
 
 /* Try to enable the console unconditionally */
-static void try_enable_default_console(struct console *newcon)
+static int try_enable_default_console(struct console *newcon)
 {
+	int err;
+
 	if (newcon->index < 0)
 		newcon->index = 0;
 
-	if (console_call_setup(newcon, NULL) != 0)
-		return;
+	err = console_call_setup(newcon, NULL);
+	if (err)
+		return err;
 
 	newcon->flags |= CON_ENABLED;
 
 	if (newcon->device)
 		newcon->flags |= CON_CONSDEV;
+
+	return 0;
 }
 
 #define console_first()				\
@@ -4109,7 +4114,9 @@ static int try_enable_console(struct console *newcon)
 	if (preferred_dev_console < 0) {
 		if (hlist_empty(&console_list) || !console_first()->device ||
 		    console_first()->flags & CON_BOOT) {
-			try_enable_default_console(newcon);
+			err = try_enable_default_console(newcon);
+			if (err != -ENOENT)
+				return err;
 		}
 	}
 
Signature · 1 line
2.53.0
author maintainer
#21 lore raw

Re: [PATCH v2 9/9] printk: Try enable preferred consoles only when there are any

Quoted 46 lines · Petr Mladek

try_enable_preferred_console() used to be always called because it had several hidden effects, namely:

- enabled Braille consoles which were ignored by "preferred_dev_console" because they were not associated with /dev/console.

- returned success when a console was pre-enabled using CON_ENABLED flag.

- returned success when a console was enabled by default because try_enable_default_console() did not return success.

The first two hidden effects were removed in previous patches. Remove the last one so that try_enable_preferred_console() can be called only when any non-Braille console is preferred.

kernel/printk/printk.c +8 -3
@@ -4055,18 +4055,23 @@ static int try_enable_braille_console(struct console *newcon)
 }
 
 /* Try to enable the console unconditionally */
-static void try_enable_default_console(struct console *newcon)
+static int try_enable_default_console(struct console *newcon)
 {
+	int err;
+
 	if (newcon->index < 0)
 		newcon->index = 0;
 
-	if (console_call_setup(newcon, NULL) != 0)
-		return;
+	err = console_call_setup(newcon, NULL);
+	if (err)
+		return err;
 
 	newcon->flags |= CON_ENABLED;
 
 	if (newcon->device)
 		newcon->flags |= CON_CONSDEV;
+
+	return 0;
 }
 
 #define console_first()				\

kernel/printk/printk.c static int try_enable_console(struct console *newcon) · line 4121

Quoted 9 lines
kernel/printk/printk.c +3 -1
@@ -4109,7 +4114,9 @@ static int try_enable_console(struct console *newcon)
 	if (preferred_dev_console < 0) {
 		if (hlist_empty(&console_list) || !console_first()->device ||
 		    console_first()->flags & CON_BOOT) {
-			try_enable_default_console(newcon);
+			err = try_enable_default_console(newcon);
+			if (err != -ENOENT)
+				return err;
 		}
 	}

I am working on v3 and I realized that this is not enough. try_enable_preferred_console() is still called when there already was default console (the if-condition above failed). But it makes sense only when preferred_dev_console >= 0.

I am going to go further and put it into "else" part. I'll actually invert the check and do:

static int try_enable_console(struct console *newcon)

{
	int err;

	/*
	 * First, try to enable the console driver as a Braille console.
	 * It would have metadata in the preferred_consoles[] array.
	 * But it won't be counted as @preferred_console because
	 * it does not get printk() messages and is not associated
	 * with /dev/console.
	 *
	 * Note that it might succeed also when the driver has a match()
	 * callback and it took over a boot console. In this case,
	 * the driver will continue working as a classic non-Braille
	 * console.
	 */
	if (want_braille_console) {
		err = try_enable_braille_console(newcon);
		if (err != -ENOENT)
			return err;
	}

	if (preferred_dev_console >= 0) {
		/* See if this console matches one we selected on the command line */
		err = try_enable_preferred_console(newcon, true);
		if (err != -ENOENT)
			return err;

		/* If not, try to match against the platform default(s) */
		err = try_enable_preferred_console(newcon, false);
		if (err != -ENOENT)
			return err;
	} else {
		/*
		 * See if we want to enable this console driver by default.
		 *
		 * Nope when a console is preferred by the command line, device
		 * tree, or SPCR.
		 *
		 * The first real console with tty binding (driver) wins. More
		 * consoles might get enabled before the right one is found.
		 *
		 * Note that a console with tty binding will have CON_CONSDEV
		 * flag set and will be first in the list.
		 */
		if (hlist_empty(&console_list) || !console_first()->device ||
		    console_first()->flags & CON_BOOT) {
			err = try_enable_default_console(newcon);
			if (err != -ENOENT)
				return err;
		}
	}

	/*
	 * Some consoles, such as pstore and netconsole, can be enabled even
	 * without matching. Accept them at this stage when they had a chance
	 * to match() and call setup().
	 */
	if (newcon->flags & CON_ENABLED)
		err = 0;

	return err;
}

I am going to split this into two patches:

1. Invert the logic and add the "else" part. This should not change the behavior at this stage.

2. Add the return value for try_enabled_default_console() and return immediately on success or error. It might actually change the behavior because pre-enabled console won't be registered when newcon->setup() failed.

Best Regards,
Petr

author maintainer
#22 lore raw
In reply to Petr Mladek
Quoted 4 lines · Petr Mladek

Hi,

this patchset does some clean up of the code for handling preferred consoles in the console registration code.

JFYI, Sashiko AI has already proceed this patchset and reported some interesting problems. [1] I still have to think about it.

Anyway, you do not need to report the issues already reported by Sashiko AI. I am going to process them. But feel free to comment on them especially when the opinion is not obvious ;-)

[1] https://sashiko.dev/#/patchset/20260423130015.85175-1-pmladek%40suse.com

Best Regards,
Petr