Skip to contentSkip to conversation

printk: Clean up preferred console handling

PATCH Superseded Petr Mladek 3 participants 45 messages Sep 29 – Nov 6

Subsystems (2)

v5 of 7 Superseded Latest is v7 →

lore
Share & tools
lore

Petr Mladek

author maintainer
#0 lore raw

v5 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.

It 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

Note: I split the 4th patch => should be easier for review than v4 ;-) /o\

Important: An extra fix is needed to get the Braille console

	working on a serial port using NBCON API, see
	https://lore.kernel.org/r/[email protected]
	https://lore.kernel.org/r/[email protected]

Changes against [v4]:

+ Removed 1st patch from v4. Already in upstream.

+ Cleanup _braille_(un)register_console() wrappers already in 3rd patch. is_braille_console_preferred() will be needed sooner.

+ Split 4th patch. Start with reshufling the add_preferred_console() code without any functional changes. Add the various checks and behavior changes one by one is a followup patches.

+ Rework the code to make it clear when it is a new entry or an update.

+ Put back braille_set_options() which just updates the optional entry. The logic when the value should get updated is the same as for pc->options.

+ Make sure that options can be overridden by the command line.

+ Add preferred_dev_node to remember the ordering of preferred consoles. Use it when the last one becomes Braille. The previous version tried to remembered just the last preferred console. But the logic because pretty complicated when I tried to make it error proof. AI was able to find many scenarios where it broke. The list is
the ultimate solution and is easier in the end.

+ Use console_call_setup() in braille_register_console() instead of duplicating the code [John]

Changes against [v3]:

+ Move the handling of pre-enabled consoles into register_console() as 1st patch. It prevents a possible invalid access. [Petr]

+ Move the code for handling pre-enabled to console to try_enable_console() in 7th patch. The resulting code is the same as in v3.

This 2nd move was not needed in v3 because the code was moved to this final location later. [Petr]

+ Switch order of the 10th and 11th patch. Aka make try_enable_default_console() return an err before refactoring try_enable_console() call try_enable_preferred_console() only when there is any. [Petr]

+ Initialize err value in try_enable_console() in 11th patch. It prevents using a non-initialized variable. [AI:gemini-3]

+ Make sure that pre-enabled consoles won't get registered when something went wrong in try_enable_console() in 11th patch [Petr]

Changes against [v2]:

+ Move static_assert() after declaration (1st patch) [Steven]

+ Rename update_preferred_console() to add_or_update_preferred_console() [John]
+ WARN_ON() when called without "name" and "devname" [John]
+ print error when reached MAX_PREFERRED_CONSOLES
+ Add comment above code adding new entries [John]
(all in 4th patch)

+ Call console->setup() under console_lock() in braille_register_console() (new patch) [Sashiko]

+ Use "No functional changes." phrase in commit messages. [Steven]

+ Call try_enable_preferred_console() only when there is no preferred console (reworked and split 9th patch) [Petr]

+ Added taken Reviewed-by and Acked-by tags [John, Macros]

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)

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

Petr Mladek (16):
printk: Rename struct console_cmdline to preferred_console
printk: Rename preferred_console to preferred_dev_console
printk: Cleanup _braille_(un)register_console() wrappers
printk: Separate code for adding/updating preferred console metadata
printk: Prefer the console either via name or devname exclusively
printk: Check that index is not defined when a console is preferred
via devname
printk: Ensure consistent name and devname when updating preferred
console
printk: Do not quietly ignore adding entry for a preferred console
when there is no space
printk: Allow to override options via the command line
printk: Allow to debug misuse of add_or_update_preferred_console() console/braille: Lock console->setup() call during the registration
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: Modify try_enable_default_console() to return error/success
printk: Try enable preferred consoles only when there are any

 .../accessibility/braille/braille_console.c   |  17 +-
 include/linux/console.h                       |   1 +
 kernel/printk/braille.c                       |  20 +-
 kernel/printk/braille.h                       |  22 +-
 .../{console_cmdline.h => console_register.h} |   9 +-
 kernel/printk/printk.c                        | 414 ++++++++++++------
 6 files changed, 326 insertions(+), 157 deletions(-)
 rename kernel/printk/{console_cmdline.h => console_register.h} (74%)
Signature · 1 line
2.55.0
author maintainer
#1 lore raw

PATCH v5 1/16 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.

No functional changes.

---
 kernel/printk/braille.c                       | 10 +--
 kernel/printk/braille.h                       | 10 +--
 .../{console_cmdline.h => console_register.h} |  6 +-
 kernel/printk/printk.c                        | 85 ++++++++++---------
 4 files changed, 57 insertions(+), 54 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 -41

179 lines not on this page · raw message

Signature · 1 line
2.55.0
#2 lore raw

Re: [PATCH v5 01/16] printk: Rename struct console_cmdline to preferred_console

Quoted 4 lines · Petr Mladek

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.

A couple of optional nits if you respin:

kernel/printk/printk.c static int __init console_setup(char *str) · line 2638

Quoted 8 lines
kernel/printk/printk.c +4 -0
@@ -2633,6 +2632,10 @@ static int __init console_setup(char *str)
 	char *s;
 	int idx;
 
+	static_assert(sizeof(preferred_consoles[0].devname) >=
+		      sizeof(preferred_consoles[0].name) + 4);
+
+

Double blank line here which checkpatch --strict is not happy about.

kernel/printk/printk.c static int console_locked; · line 362

Quoted 8 lines
kernel/printk/printk.c +1 -1
 #include "printk_ringbuffer.h"
-#include "console_cmdline.h"
+#include "console_register.h"
 #include "braille.h"

#include "internal.h"

kernel/printk/printk.c +0 -0
@@ -362,9 +362,9 @@ static int console_locked;
 *	Array of consoles built from command line options (console=)

This comment still says "Array of consoles built from command line options (console=)", which is exactly what the rename is meant to stop implying (as in, the array also holds SPCR, DT, etc). Could be updated in this patch if you respin.

author maintainer
#3 lore raw

Re: [PATCH v5 01/16] printk: Rename struct console_cmdline to preferred_console

Quoted 6 lines · Chris Down
Quoted 4 lines · Petr Mladek

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.

Quoted 7 lines

Review static int console_locked; · line 362

Quoted 2 lines
(quoted diff) +0 -0
@@ -362,9 +362,9 @@ static int console_locked;
 *	Array of consoles built from command line options (console=)

This comment still says "Array of consoles built from command line options (console=)", which is exactly what the rename is meant to stop implying (as in, the array also holds SPCR, DT, etc). Could be updated in this patch if you respin.

Great catch! I am going to do the following change in v6:

kernel/printk/printk.c +2 -3
@@ -359,11 +359,10 @@ static void __up_console_sem(unsigned long ip)
 static int console_locked;
 
 /*
- *	Array of consoles built from command line options (console=)
+ * Array of consoles preferred via the command line, or by
+ * some platform-specific code, e.g. SPCR, or DT.
  */
-
 #define MAX_PREFERRED_CONSOLES 8
-
 static struct preferred_console preferred_consoles[MAX_PREFERRED_CONSOLES];
 
 static int preferred_console = -1;

Best Regards,
Petr

author maintainer
#4 lore raw

PATCH v5 2/16 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.

No behavior change.

---
 kernel/printk/printk.c | 10 +++++-----
 1 file changed, 5 insertions(+), 5 deletions(-)
kernel/printk/printk.c +5 -5
index 2cff224cf1e2..8166828a9801 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)
@@ -3935,7 +3935,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;
 	}
@@ -4108,7 +4108,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.55.0
author maintainer
#5 lore raw

PATCH v5 3/16 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().

No behavior change.

---
 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 4205c894df17..7e6011f9d823 100644
@@ -394,12 +394,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)
@@ -409,5 +409,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 55cd3178a17a..e9790c28027d 100644
@@ -10,6 +10,12 @@ braille_set_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
@@ -33,6 +39,12 @@ braille_set_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 8166828a9801..c3e50f19a32b 100644
@@ -3927,8 +3927,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)
@@ -4240,17 +4240,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.55.0
author maintainer
#6 lore raw

PATCH v5 4/16 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.

Split the code for adding or updating entries to avoid code duplication. Make it clear what operations are done only for new entries.

Use this opportunity and replace an int with an unsigned int for iterating over the preferred_consoles array.

It is a preparation step before adding more consistency checks. No intended functional changes.

---
 kernel/printk/printk.c | 108 ++++++++++++++++++++++++++---------------
 1 file changed, 68 insertions(+), 40 deletions(-)
kernel/printk/printk.c +68 -40
index c3e50f19a32b..174aee533a53 100644
@@ -2544,26 +2544,33 @@ asmlinkage __visible void early_printk(const char *fmt, ...)
 }
 #endif
 
-static void set_user_specified(struct preferred_console *pc, bool user_specified)
-{
-	if (!user_specified)
-		return;
-
-	/*
-	 * @pc console was defined by the user on the command line.
-	 * Do not clear when added twice also by SPCR or the device tree.
-	 */
-	pc->user_specified = true;
-	/* At least one console defined by the user on the command line. */
-	console_set_on_cmdline = 1;
-}
-
-static int __add_preferred_console(const char *name, const short idx,
-				   const char *devname, char *options,
-				   char *brl_options, bool user_specified)
+/** add_or_update_preferred_console - Add or update a given entry in
+ *	the preferred_consoles[] array.
+ * @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 adds or updates an entry in preferred_consoles[] array. Also
+ * it updates some global variables which are used to make the right decisions
+ * in register_console().
+ */
+static int add_or_update_preferred_console(unsigned int i,
+					   const char *name, const short idx,
+					   const char *devname, char *options,
+					   char *brl_options, bool user_specified)
 {
 	struct preferred_console *pc;
-	int i;
+	bool is_new_entry = false;
+
+	if (i >= MAX_PREFERRED_CONSOLES)
+		return -E2BIG;
+
+	pc = &preferred_consoles[i];
 
 	if (!name && !devname)
 		return -EINVAL;
@@ -2577,35 +2584,56 @@ static int __add_preferred_console(const char *name, const short idx,
 	if (name && idx < 0)
 		return -EINVAL;
 
+	if (!pc->name[0] && !pc->devname[0])
+		is_new_entry = true;
+
+	if (is_new_entry) {
+		if (devname)
+			strscpy(pc->devname, devname);
+		if (name)
+			strscpy(pc->name, name);
+		pc->index = idx;
+	}
+
 	/*
-	 *	See if this tty is not yet registered, and
-	 *	if we have a slot free.
+	 * Historically, the preferred options are stored only by the first
+	 * caller who prefers the particular console.
 	 */
+	if (is_new_entry) {
+		pc->options = options;
+		braille_set_options(pc, brl_options);
+	}
+
+	if (!brl_options)
+		preferred_dev_console = i;
+
+	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,
+				   const char *devname, char *options,
+				   char *brl_options, bool user_specified)
+{
+	struct preferred_console *pc;
+	unsigned int i;
+
+	/* See if this console is already preferred. */
 	for (i = 0, pc = preferred_consoles;
 	     i < MAX_PREFERRED_CONSOLES && (pc->name[0] || pc->devname[0]);
 	     i++, pc++) {
-		if ((name && strcmp(pc->name, name) == 0 && pc->index == idx) ||
-		    (devname && strcmp(pc->devname, devname) == 0)) {
-			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)
+			break;
+		if (devname && strcmp(pc->devname, devname) == 0)
+			break;
 	}
-	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);
 
-	pc->index = idx;
-	return 0;
+	return add_or_update_preferred_console(i, name, idx, devname, options,
+					       brl_options, user_specified);
 }
 
 static int __init console_msg_format_setup(char *str)
Signature · 1 line
2.55.0
maintainer Reviewed-by on v5 4/16
#7 lore raw

Re: [PATCH v5 04/16] printk: Separate code for adding/updating preferred console metadata

Quoted 7 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.

Split the code for adding or updating entries to avoid code duplication. Make it clear what operations are done only for new entries.

Quoted 7 lines

Use this opportunity and replace an int with an unsigned int for iterating over the preferred_consoles array.

It is a preparation step before adding more consistency checks. No intended functional changes.

Some minor comments below...

Quoted 24 lines
kernel/printk/printk.c +13 -2
index c3e50f19a32b..174aee533a53 100644
@@ -2577,35 +2584,56 @@ static int __add_preferred_console(const char *name, const short idx,
 	if (name && idx < 0)
 		return -EINVAL;
 
+	if (!pc->name[0] && !pc->devname[0])
+		is_new_entry = true;
+
+	if (is_new_entry) {
+		if (devname)
+			strscpy(pc->devname, devname);
+		if (name)
+			strscpy(pc->name, name);
+		pc->index = idx;
+	}
+
 	/*
-	 *	See if this tty is not yet registered, and
-	 *	if we have a slot free.
+	 * Historically, the preferred options are stored only by the first
+	 * caller who prefers the particular console.

kernel/printk/printk.c static int __add_preferred_console(const char *name, const short idx, · line 2610

Quoted 10 lines
kernel/printk/printk.c +9 -0
 	 */
+	if (is_new_entry) {
+		pc->options = options;
+		braille_set_options(pc, brl_options);
+	}
+
+	if (!brl_options)
+		preferred_dev_console = i;
+
+	if (user_specified) {

Here you drop the comments:

	/*
	 * @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 static int __add_preferred_console(const char *name, const short idx, · line 2611

Quoted 1 line
kernel/printk/printk.c +1 -0
+		pc->user_specified = true;

And here you drop the comments:

	/* At least one console defined by the user on the command line. */

kernel/printk/printk.c static int __add_preferred_console(const char *name, const short idx, · line 2613

Quoted 2 lines
kernel/printk/printk.c +2 -0
+		console_set_on_cmdline = 1;
+	}

The comments seem useful to help track all this. I do not see this information preserved anywhere by the end of your series. But you have a better understanding of the big picture. If you think the comments are insignificant and/or misleading, I am fine with you dropping them.

John

author maintainer
#8 lore raw

Re: [PATCH v5 04/16] printk: Separate code for adding/updating preferred console metadata

Quoted 68 lines · John Ogness
Quoted 7 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.

Split the code for adding or updating entries to avoid code duplication. Make it clear what operations are done only for new entries.

Quoted 7 lines

Use this opportunity and replace an int with an unsigned int for iterating over the preferred_consoles array.

It is a preparation step before adding more consistency checks. No intended functional changes.

Some minor comments below...

Quoted 24 lines
kernel/printk/printk.c +13 -2
index c3e50f19a32b..174aee533a53 100644
@@ -2577,35 +2584,56 @@ static int __add_preferred_console(const char *name, const short idx,
 	if (name && idx < 0)
 		return -EINVAL;
 
+	if (!pc->name[0] && !pc->devname[0])
+		is_new_entry = true;
+
+	if (is_new_entry) {
+		if (devname)
+			strscpy(pc->devname, devname);
+		if (name)
+			strscpy(pc->name, name);
+		pc->index = idx;
+	}
+
 	/*
-	 *	See if this tty is not yet registered, and
-	 *	if we have a slot free.
+	 * Historically, the preferred options are stored only by the first
+	 * caller who prefers the particular console.

kernel/printk/printk.c static int __add_preferred_console(const char *name, const short idx, · line 2610

Quoted 10 lines
kernel/printk/printk.c +9 -0
 	 */
+	if (is_new_entry) {
+		pc->options = options;
+		braille_set_options(pc, brl_options);
+	}
+
+	if (!brl_options)
+		preferred_dev_console = i;
+
+	if (user_specified) {

Here you drop the comments:

	/*
	 * @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 static int __add_preferred_console(const char *name, const short idx, · line 2611

Quoted 1 line
kernel/printk/printk.c +1 -0
+		pc->user_specified = true;

And here you drop the comments:

	/* At least one console defined by the user on the command line. */
Quoted 7 lines

kernel/printk/printk.c static int __add_preferred_console(const char *name, const short idx, · line 2613

Quoted 2 lines
kernel/printk/printk.c +2 -0
+		console_set_on_cmdline = 1;
+	}

The comments seem useful to help track all this. I do not see this information preserved anywhere by the end of your series. But you have a better understanding of the big picture. If you think the comments are insignificant and/or misleading, I am fine with you dropping them.

Heh, they did not fit 80-characters per-line, so I dropped them ;-) OK, I am going to add them back the following way in v6:

kernel/printk/printk.c +5 -0
@@ -366,6 +366,7 @@ static int console_locked;
 static struct preferred_console preferred_consoles[MAX_PREFERRED_CONSOLES];
 
 static int preferred_dev_console = -1;
+/* Set when there is at least one console preferred via the command line. */
 int console_set_on_cmdline;
 EXPORT_SYMBOL(console_set_on_cmdline);
 
@@ -2607,6 +2608,10 @@ static int add_or_update_preferred_console(unsigned int i,
 		preferred_dev_console = i;
 
 	if (user_specified) {
+		/*
+		 * @pc console was defined by the user on the command line.
+		 * Do not clear when added twice also by SPCR or DT.
+		 */
 		pc->user_specified = true;
 		console_set_on_cmdline = 1;
 	}

I'll keep your Reviewed-by. Speak if you do not like it, please.

Best Regards,
Petr

Acked-by on v5 4/16
#9 lore raw

Re: [PATCH v5 04/16] printk: Separate code for adding/updating preferred console metadata

In reply to Petr Mladek
Quoted 3 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.

I checked that the split itself has no functional change. Thanks!

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

Quoted 8 lines
kernel/printk/printk.c +3 -5
-}
-
-static int __add_preferred_console(const char *name, const short idx,
-				   const char *devname, char *options,
-				   char *brl_options, bool user_specified)
+/** add_or_update_preferred_console - Add or update a given entry in
+ *	the preferred_consoles[] array.
+ * @i: index of the entry in @preferred_consoles table which should get updated.

kernel-doc needs "/**" on its own line, otherwise it silently skips the whole block (scripts/kernel-doc -none -Wall reports nothing for this function right now). With that fixed, -Wall then also wants a "Return:" section. "@preferred_consoles" also reads as a parameter, maybe just "preferred_consoles[]".

I agree with John about keeping the comments explaining user_specified and console_set_on_cmdline as well.

With the kernel-doc comment fixed:

author maintainer
#10 lore raw

Re: [PATCH v5 04/16] printk: Separate code for adding/updating preferred console metadata

Quoted 7 lines · Chris Down
Quoted 3 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.

I checked that the split itself has no functional change. Thanks!

Quoted 14 lines

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

Quoted 8 lines
kernel/printk/printk.c +3 -5
-}
-
-static int __add_preferred_console(const char *name, const short idx,
-				   const char *devname, char *options,
-				   char *brl_options, bool user_specified)
+/** add_or_update_preferred_console - Add or update a given entry in
+ *	the preferred_consoles[] array.
+ * @i: index of the entry in @preferred_consoles table which should get updated.

kernel-doc needs "/**" on its own line, otherwise it silently skips the whole block (scripts/kernel-doc -none -Wall reports nothing for this function right now). With that fixed, -Wall then also wants a "Return:" section. "@preferred_consoles" also reads as a parameter, maybe just "preferred_consoles[]".

Good to know. I was not aware of it. Will fix in v6.

Quoted 2 lines

I agree with John about keeping the comments explaining user_specified and console_set_on_cmdline as well.

Done.

Best Regards,
Petr

author maintainer
#11 lore raw

PATCH v5 5/16 printk: Prefer the console either via name or devname exclusively

In reply to Petr Mladek

The commit 7640f1a44eba0cc1a4 ("printk:
Add match_devname_and_update_preferred_console()") added the possibility to prefer a console driver via device name. The name of the console driver gets assigned when the device gets initialized and it triers whether it is eligible for a console.

The above mentioned commit ensures that __add_preferred_console() is called at least with name or devname value. But it does not check whether both are defined which is a non-sense.

Add the check and do not fail quietly. Also shuffle the code a bit to make it ready for adding more checks.

---
 kernel/printk/printk.c | 30 ++++++++++++++++++++++++------
 1 file changed, 24 insertions(+), 6 deletions(-)
kernel/printk/printk.c +24 -6
index 174aee533a53..0199c918ef03 100644
@@ -2557,7 +2557,13 @@ asmlinkage __visible void early_printk(const char *fmt, ...)
  *
  * The function adds or updates an entry in preferred_consoles[] array. Also
  * it updates some global variables which are used to make the right decisions
- * in register_console().
+ * in register_console(). Finally, it enforces some rules:
+ *
+ *   1. Either @name OR @devname are allowed. [*]
+ *
+ *  [*] A valid @name and @idx will get assigned for a devname later when
+ *	@devname matches during the device initialization, see
+ *	match_devname_and_update_preferred_console().
  */
 static int add_or_update_preferred_console(unsigned int i,
 					   const char *name, const short idx,
@@ -2587,11 +2593,23 @@ static int add_or_update_preferred_console(unsigned int i,
 	if (!pc->name[0] && !pc->devname[0])
 		is_new_entry = true;
 
-	if (is_new_entry) {
-		if (devname)
-			strscpy(pc->devname, devname);
-		if (name)
-			strscpy(pc->name, name);
+	if (is_new_entry && 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;
+		}
+
+		strscpy(pc->devname, devname);
+		pc->index = idx;
+	}
+
+	if (is_new_entry && name) {
+		strscpy(pc->name, name);
 		pc->index = idx;
 	}
 
Signature · 1 line
2.55.0
maintainer Reviewed-by on v5 5/16
#12 lore raw

Re: [PATCH v5 05/16] printk: Prefer the console either via name or devname exclusively

Quoted 6 lines · Petr Mladek

The commit 7640f1a44eba0cc1a4 ("printk:
Add match_devname_and_update_preferred_console()") added the possibility to prefer a console driver via device name. The name of the console driver gets assigned when the device gets initialized and it triers whether it is eligible for a console.

Quoted 8 lines

The above mentioned commit ensures that __add_preferred_console() is called at least with name or devname value. But it does not check whether both are defined which is a non-sense.

Add the check and do not fail quietly. Also shuffle the code a bit to make it ready for adding more checks.

Acked-by on v5 5/16
#13 lore raw

Re: [PATCH v5 05/16] printk: Prefer the console either via name or devname exclusively

In reply to Petr Mladek
Quoted 5 lines · Petr Mladek

The commit 7640f1a44eba0cc1a4 ("printk:
Add match_devname_and_update_preferred_console()") added the possibility to prefer a console driver via device name. The name of the console driver gets assigned when the device gets initialized and it triers whether it is eligible for a console.

A few commit message nits: s/triers/tries/, s/a non-sense/nonsense/, and the usual form for the reference is:

commit 7640f1a44eba ("printk: Add match_devname_and_update_preferred_console()")

With that:

author maintainer
#14 lore raw

PATCH v5 6/16 printk: Check that index is not defined when a console is preferred via devname

In reply to Petr Mladek

The current code makes sure that a valid index is defined when a console is preferred via a name.

On the contrary, the index must not be defined when the console is defined via a devname. The index will be defined later when the device matches and gets registered.

Enforce the 2nd rule. Make the checks symmetric in the code. Do not ignore the errors quietly.

---
 kernel/printk/printk.c | 23 +++++++++++++----------
 1 file changed, 13 insertions(+), 10 deletions(-)
kernel/printk/printk.c +13 -10
index 0199c918ef03..b8c348e305eb 100644
@@ -2559,7 +2559,7 @@ asmlinkage __visible void early_printk(const char *fmt, ...)
  * it updates some global variables which are used to make the right decisions
  * in register_console(). Finally, it enforces some rules:
  *
- *   1. Either @name OR @devname are allowed. [*]
+ *   1. Either @name and valid @idx OR @devname and @idx=-1 are allowed.
  *
  *  [*] A valid @name and @idx will get assigned for a devname later when
  *	@devname matches during the device initialization, see
@@ -2581,15 +2581,6 @@ static int add_or_update_preferred_console(unsigned int i,
 	if (!name && !devname)
 		return -EINVAL;
 
-	/*
-	 * We use a signed short index for struct console for device drivers to
-	 * indicate a not yet assigned index or port. However, a negative index
-	 * value is not valid when the console name and index are defined on
-	 * the command line.
-	 */
-	if (name && idx < 0)
-		return -EINVAL;
-
 	if (!pc->name[0] && !pc->devname[0])
 		is_new_entry = true;
 
@@ -2603,12 +2594,24 @@ static int add_or_update_preferred_console(unsigned int i,
 			       devname, name);
 			return -EINVAL;
 		}
+		if (idx != -1) {
+			pr_err("Adding a preferred console devname with a hard-coded index: %s, %d\n",
+			       devname, idx);
+			return -EINVAL;
+		}
 
 		strscpy(pc->devname, devname);
 		pc->index = idx;
 	}
 
 	if (is_new_entry && name) {
+		/* 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;
+		}
+
 		strscpy(pc->name, name);
 		pc->index = idx;
 	}
Signature · 1 line
2.55.0
maintainer Reviewed-by on v5 6/16
#15 lore raw

Re: [PATCH v5 06/16] printk: Check that index is not defined when a console is preferred via devname

Quoted 11 lines · Petr Mladek

The current code makes sure that a valid index is defined when a console is preferred via a name.

On the contrary, the index must not be defined when the console is defined via a devname. The index will be defined later when the device matches and gets registered.

Enforce the 2nd rule. Make the checks symmetric in the code. Do not ignore the errors quietly.

Minor nit below.

Quoted 9 lines
---
 kernel/printk/printk.c | 23 +++++++++++++----------
 1 file changed, 13 insertions(+), 10 deletions(-)
kernel/printk/printk.c +0 -0
index 0199c918ef03..b8c348e305eb 100644

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

Quoted 8 lines
kernel/printk/printk.c +1 -1
@@ -2559,7 +2559,7 @@ asmlinkage __visible void early_printk(const char *fmt, ...)
  * it updates some global variables which are used to make the right decisions
  * in register_console(). Finally, it enforces some rules:
  *
- *   1. Either @name OR @devname are allowed. [*]
+ *   1. Either @name and valid @idx OR @devname and @idx=-1 are allowed.
  *
  *  [*] A valid @name and @idx will get assigned for a devname later when
  *	@devname matches during the device initialization, see

You drop the [*] from rule #1. I think this was unintentional, considering you later add a [**] for rule #4.

John

Acked-by on v5 6/16
#16 lore raw

Re: [PATCH v5 06/16] printk: Check that index is not defined when a console is preferred via devname

In reply to Petr Mladek
Quoted 2 lines · Petr Mladek

The current code makes sure that a valid index is defined when a console is preferred via a name.

After John's stuff is fixed, all looks good. Thanks!

Once that's done:

author maintainer
#17 lore raw

PATCH v5 7/16 printk: Ensure consistent name and devname when updating preferred console

In reply to Petr Mladek

Make sure that add_or_update_preferred_console() updates the right entry. It is a paranoid check which prevents a potential misuse of the API in the future.

---
 kernel/printk/printk.c | 31 ++++++++++++++++++++++---------
 1 file changed, 22 insertions(+), 9 deletions(-)
kernel/printk/printk.c +22 -9
index b8c348e305eb..0fafc579bdd3 100644
@@ -2561,6 +2561,8 @@ asmlinkage __visible void early_printk(const char *fmt, ...)
  *
  *   1. Either @name and valid @idx OR @devname and @idx=-1 are allowed.
  *
+ *   2. Only matching entries can be updated.
+ *
  *  [*] A valid @name and @idx will get assigned for a devname later when
  *	@devname matches during the device initialization, see
  *	match_devname_and_update_preferred_console().
@@ -2581,10 +2583,7 @@ static int add_or_update_preferred_console(unsigned int i,
 	if (!name && !devname)
 		return -EINVAL;
 
-	if (!pc->name[0] && !pc->devname[0])
-		is_new_entry = true;
-
-	if (is_new_entry && devname) {
+	if (devname) {
 		/*
 		 * A valid console name and index will get assigned when
 		 * a matching device gets registered.
@@ -2600,11 +2599,18 @@ static int add_or_update_preferred_console(unsigned int i,
 			return -EINVAL;
 		}
 
-		strscpy(pc->devname, devname);
-		pc->index = idx;
+		if (!pc->devname[0]) {
+			is_new_entry = true;
+			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",
+			       pc->devname, devname);
+			return -EINVAL;
+		}
 	}
 
-	if (is_new_entry && name) {
+	if (name) {
 		/* 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",
@@ -2612,8 +2618,15 @@ static int add_or_update_preferred_console(unsigned int i,
 			return -EINVAL;
 		}
 
-		strscpy(pc->name, name);
-		pc->index = idx;
+		if (!pc->name[0]) {
+			is_new_entry = true;
+			strscpy(pc->name, name);
+			pc->index = idx;
+		} 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;
+		}
 	}
 
 	/*
Signature · 1 line
2.55.0
#18 lore raw

Re: [PATCH v5 07/16] printk: Ensure consistent name and devname when updating preferred console

kernel/printk/printk.c static int add_or_update_preferred_console(unsigned int i, · line 2624

Quoted 6 lines · Petr Mladek
kernel/printk/printk.c +4 -2
-		strscpy(pc->name, name);
-		pc->index = idx;
+		if (!pc->name[0]) {
+			is_new_entry = true;
+			strscpy(pc->name, name);
+			pc->index = idx;

console_setup() can hand us an empty name or devname:

    console=,115200   -> name "", idx 0, options "115200"
    console=,foo:bar  -> devname "", idx -1, options "foo:bar"

For the devname case, __add_preferred_console() matches the first name-only entry (strcmp(pc->devname, "") == 0), e.g. the SPCR "pl011"/0 entry, and this hunk now treats it as new.

Then index becomes -1 and options become "foo:bar", so the SPCR console never matches again. Before the series that command line only moved preferred_console.

For the !pc->name[0] branch below the slot keeps looking unused, which turns into list corruption with 14/16 (I'll put some details over there instead of duplicating it here).

Rejecting empty strings up front, after the WARN_ON(!name && !devname), fixes both:

    	if ((name && !name[0]) || (devname && !devname[0])) {
    		pr_err("Adding a preferred console with an empty name\n");
    		return -EINVAL;
    	}
author maintainer Reviewed-by
#19 lore raw

Re: [PATCH v5 07/16] printk: Ensure consistent name and devname when updating preferred console

Quoted 17 lines · Chris Down

Review

Quoted 6 lines · Petr Mladek
(quoted diff) +4 -2
-		strscpy(pc->name, name);
-		pc->index = idx;
+		if (!pc->name[0]) {
+			is_new_entry = true;
+			strscpy(pc->name, name);
+			pc->index = idx;

console_setup() can hand us an empty name or devname:

    console=,115200   -> name "", idx 0, options "115200"
    console=,foo:bar  -> devname "", idx -1, options "foo:bar"

For the devname case, __add_preferred_console() matches the first name-only entry (strcmp(pc->devname, "") == 0), e.g. the SPCR "pl011"/0 entry, and this hunk now treats it as new.

Quoted 7 lines

Then index becomes -1 and options become "foo:bar", so the SPCR console never matches again. Before the series that command line only moved preferred_console.

For the !pc->name[0] branch below the slot keeps looking unused, which turns into list corruption with 14/16 (I'll put some details over there instead of duplicating it here).

Great catch! I think that even the original code did not expect that anyone could pass "" as either @name or @devname.

Quoted 7 lines

Rejecting empty strings up front, after the WARN_ON(!name && !devname), fixes both:

    	if ((name && !name[0]) || (devname && !devname[0])) {
    		pr_err("Adding a preferred console with an empty name\n");
    		return -EINVAL;
    	}

I like this. I am going to add this as a separate patch. As mentioned above, I think that it was not handled before...

I have the following as the 5th patch:

From d7990601069c2facc8ca47efe7ed36ac21038be7 Mon Sep 17 00:00:00 2001
From: Petr Mladek <[email protected]>
Date: Tue, 3 Nov 2026 18:02:20 +0100
Subject: [PATCH] printk: Do not accept an empty name or devname as a preferred
console

The current code for storing preferred consoles does not expect the case when an empty string is passed via @name or @devname.

Empty console driver name does not make any sense. Avoid handling such entries completely.

---
 kernel/printk/printk.c | 9 ++++++++-
 1 file changed, 8 insertions(+), 1 deletion(-)
kernel/printk/printk.c +8 -1
index b7543fea865b..6bba67e142e1 100644
@@ -2558,7 +2558,9 @@ asmlinkage __visible void early_printk(const char *fmt, ...)
  *
  * The function adds or updates an entry in preferred_consoles[] array. Also
  * it updates some global variables which are used to make the right decisions
- * in register_console().
+ * in register_console(). Finally, it enforces some rules:
+ *
+ *   1. Do not accept empty @name or @devname.
  */
 static int add_or_update_preferred_console(unsigned int i,
 					   const char *name, const short idx,
@@ -2576,6 +2578,11 @@ static int add_or_update_preferred_console(unsigned int i,
 	if (!name && !devname)
 		return -EINVAL;
 
+	if ((name && !name[0]) || (devname && !devname[0])) {
+		pr_err("Adding a preferred console with an empty name\n");
+		return -EINVAL;
+	}
+
 	/*
 	 * We use a signed short index for struct console for device drivers to
 	 * indicate a not yet assigned index or port. However, a negative index
Signature · 4 lines
2.56.0

Best Regards,
Petr
author maintainer
#20 lore raw

PATCH v5 8/16 printk: Do not quietly ignore adding entry for a preferred console when there is no space

In reply to Petr Mladek

It is hard to imagine that anyone would want to add more than 8 preferred consoles. But never say never. And do not ignore new entries quietly.

---
 kernel/printk/printk.c | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
kernel/printk/printk.c +3 -1
index 0fafc579bdd3..4670787195d1 100644
@@ -2575,8 +2575,10 @@ static int add_or_update_preferred_console(unsigned int i,
 	struct preferred_console *pc;
 	bool is_new_entry = false;
 
-	if (i >= MAX_PREFERRED_CONSOLES)
+	if (i >= MAX_PREFERRED_CONSOLES) {
+		pr_err_once("Reached maximal number of preferred consoles.\n");
 		return -E2BIG;
+	}
 
 	pc = &preferred_consoles[i];
 
Signature · 1 line
2.55.0
author maintainer
#23 lore raw

PATCH v5 9/16 printk: Allow to override options via the command line

In reply to Petr Mladek

Consoles can be preferred either via the console= command line parameter or by some platform specific code, e.g. SPCR, device tree.

Historically, the preferred console options are stored only by the first caller who prefers the particular console. The ordering is:

1. acpi_parse_spcr() is called via setup_arch(). Also some platforms, for example, s390, powerpc, x86 Xen, explicitly call add_preferred_console() before or in setup_arch().

2. console= command line parameter adds the preferred consoles via console_setup().

3. The device tree is read in setup_arch(), see unflatten_device_tree(). But the preferred console entries are added later when probing particular devices in do_initcalls(), see of_console_check().

It means that users could override console options via the command line only for entries defined via the device tree but not for entries added via SPCR or another platform-specific code.

I looks like a bug. It should always be possible to override any platform-specific defaults via the command line. Also it is usual that the last variant wins.

Be conservative when Braille console is wanted and prefer the Braille variant.

The change might theoretically break setups where users passed wrong console options and they used to be ignored. But the fix seems to be worth the risk.

---
 kernel/printk/printk.c | 10 +++++++---
 1 file changed, 7 insertions(+), 3 deletions(-)
kernel/printk/printk.c +7 -3
index 4670787195d1..b458a920ce5a 100644
@@ -2563,6 +2563,9 @@ asmlinkage __visible void early_printk(const char *fmt, ...)
  *
  *   2. Only matching entries can be updated.
  *
+ *   3. Allow to override @options via the command line. Last one wins
+ *	except that the Braille variant is preferred.
+ *
  *  [*] A valid @name and @idx will get assigned for a devname later when
  *	@devname matches during the device initialization, see
  *	match_devname_and_update_preferred_console().
@@ -2632,10 +2635,11 @@ static int add_or_update_preferred_console(unsigned int i,
 	}
 
 	/*
-	 * Historically, the preferred options are stored only by the first
-	 * caller who prefers the particular console.
+	 * Allow to override options via the command line but always
+	 * prefer the Braille variant.
 	 */
-	if (is_new_entry) {
+	if (is_new_entry || brl_options ||
+	    (user_specified && !is_braille_console_preferred(pc))) {
 		pc->options = options;
 		braille_set_options(pc, brl_options);
 	}
Signature · 1 line
2.55.0
#24 lore raw

Re: [PATCH v5 09/16] printk: Allow to override options via the command line

Quoted 2 lines · Petr Mladek

Consoles can be preferred either via the console= command line parameter or by some platform specific code, e.g. SPCR, device tree.

On v4 I recall you said you would probably do the change in a separate series. I think that is still the better plan: the rest of the series is a clean-up and it would be nice to keep it that way.

kernel/printk/printk.c static int add_or_update_preferred_console(unsigned int i, · line 2642

Quoted 8 lines
kernel/printk/printk.c +2 -2
-	 * Historically, the preferred options are stored only by the first
-	 * caller who prefers the particular console.
+	 * Allow to override options via the command line but always
+	 * prefer the Braille variant.
	 */
kernel/printk/printk.c +2 -1
-	if (is_new_entry) {
+	if (is_new_entry || brl_options ||
+	    (user_specified && !is_braille_console_preferred(pc))) {

This also clears options when the later console= has none, which v4 did not do. That breaks at least the MIPS boards that pass the firmware baud rate from setup_arch():

    arch/mips/sgi-ip22/ip22-setup.c: add_preferred_console("ttyS", n, dbaud)
    arch/mips/sgi-ip32/ip32-setup.c: add_preferred_console("ttyS", n, dbaud)
    arch/mips/sni/setup.c:           add_preferred_console("ttyS"/"ttySC", port, baud)

With "console=ttyS0" and no options, the drivers there (ip22zilog, 8250, sccnxp) fall back to 9600, and anyone with the firmware set to another rate is gonna have a bad time.

It also makes a bare "console=uart" after an SPCR "uart" entry oops because univ8250_console_match() hands the now-NULL options to uart_parse_earlycon().

(A bare console=uart on its own already oopses in the base, so that part is an older 8250 problem, but this patch adds a fun new way to get there.)

If you want to keep it here, could it at least only override when the command line actually provides options?

maintainer
#25 lore raw

Re: [PATCH v5 09/16] printk: Allow to override options via the command line

Quoted 28 lines · Chris Down
Quoted 2 lines

Consoles can be preferred either via the console= command line parameter or by some platform specific code, e.g. SPCR, device tree.

On v4 I recall you said you would probably do the change in a separate series. I think that is still the better plan: the rest of the series is a clean-up and it would be nice to keep it that way.

kernel/printk/printk.c static int add_or_update_preferred_console(unsigned int i, · line 2642

Quoted 8 lines
kernel/printk/printk.c +2 -2
-	 * Historically, the preferred options are stored only by the first
-	 * caller who prefers the particular console.
+	 * Allow to override options via the command line but always
+	 * prefer the Braille variant.
	 */
kernel/printk/printk.c +2 -1
-	if (is_new_entry) {
+	if (is_new_entry || brl_options ||
+	    (user_specified && !is_braille_console_preferred(pc))) {

This also clears options when the later console= has none, which v4 did not do. That breaks at least the MIPS boards that pass the firmware baud rate from setup_arch():

    arch/mips/sgi-ip22/ip22-setup.c: add_preferred_console("ttyS", n, dbaud)
    arch/mips/sgi-ip32/ip32-setup.c: add_preferred_console("ttyS", n, dbaud)
    arch/mips/sni/setup.c:           add_preferred_console("ttyS"/"ttySC", port, baud)

With "console=ttyS0" and no options, the drivers there (ip22zilog, 8250, sccnxp) fall back to 9600, and anyone with the firmware set to another rate is gonna have a bad time.

Quoted 8 lines

It also makes a bare "console=uart" after an SPCR "uart" entry oops because univ8250_console_match() hands the now-NULL options to uart_parse_earlycon().

(A bare console=uart on its own already oopses in the base, so that part is an older 8250 problem, but this patch adds a fun new way to get there.)

If you want to keep it here, could it at least only override when the command line actually provides options?

Agreed. It should be (user_specified && options && ...)

A console specified with no options should not be interpretted as "clear options" but rather "not overriding options, just specifying that it is preferred".

John

author maintainer
#26 lore raw

Re: [PATCH v5 09/16] printk: Allow to override options via the command line

In reply to Chris Down
Quoted 7 lines · Chris Down
Quoted 2 lines · Petr Mladek

Consoles can be preferred either via the console= command line parameter or by some platform specific code, e.g. SPCR, device tree.

On v4 I recall you said you would probably do the change in a separate series. I think that is still the better plan: the rest of the series is a clean-up and it would be nice to keep it that way.

Fair enough. I am going to remove this patch in v6. I'll send it separately later.

Quoted 21 lines

kernel/printk/printk.c static int add_or_update_preferred_console(unsigned int i, · line 2642

Quoted 8 lines
kernel/printk/printk.c +2 -2
-	 * Historically, the preferred options are stored only by the first
-	 * caller who prefers the particular console.
+	 * Allow to override options via the command line but always
+	 * prefer the Braille variant.
	 */
kernel/printk/printk.c +2 -1
-	if (is_new_entry) {
+	if (is_new_entry || brl_options ||
+	    (user_specified && !is_braille_console_preferred(pc))) {

This also clears options when the later console= has none, which v4 did not do. That breaks at least the MIPS boards that pass the firmware baud rate from setup_arch():

    arch/mips/sgi-ip22/ip22-setup.c: add_preferred_console("ttyS", n, dbaud)
    arch/mips/sgi-ip32/ip32-setup.c: add_preferred_console("ttyS", n, dbaud)
    arch/mips/sni/setup.c:           add_preferred_console("ttyS"/"ttySC", port, baud)

With "console=ttyS0" and no options, the drivers there (ip22zilog, 8250, sccnxp) fall back to 9600, and anyone with the firmware set to another rate is gonna have a bad time.

Quoted 5 lines

It also makes a bare "console=uart" after an SPCR "uart" entry oops because univ8250_console_match() hands the now-NULL options to uart_parse_earlycon().

(A bare console=uart on its own already oopses in the base, so that part is an older 8250 problem, but this patch adds a fun new way to get there.)

Thanks a lot for finding these probleamtic scenarious. I'll review them before sending this change again.

Quoted 2 lines

If you want to keep it here, could it at least only override when the command line actually provides options?

I guess that it will be the way to go.

Best Regards,
Petr

author maintainer
#27 lore raw

PATCH v5 10/16 printk: Allow to debug misuse of add_or_update_preferred_console()

In reply to Petr Mladek

__add_preferred_console() should always be called only when either @name or @devname is defined. Allow to debug the case when they are misused.

Use WARN_ON() because it is rather an implementation problem, it should never happen. Also the consoles are typically added during boot so this should not panic a running system even when panic_on_warn is enabled.

---
 kernel/printk/printk.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
kernel/printk/printk.c +1 -1
index b458a920ce5a..683083405230 100644
@@ -2585,7 +2585,7 @@ static int add_or_update_preferred_console(unsigned int i,
 
 	pc = &preferred_consoles[i];
 
-	if (!name && !devname)
+	if (WARN_ON(!name && !devname))
 		return -EINVAL;
 
 	if (devname) {
Signature · 1 line
2.55.0
author maintainer
#29 lore raw

PATCH v5 11/16 console/braille: Lock console->setup() call during the registration

In reply to Petr Mladek

In braille_register_console(), the console->setup() callback must be called while holding the console_lock. This prevents a race condition with a possible active boot console that might be using the same hardware registers.

See also the commit 801410b26a0e ("serial: Lock console when calling into driver before registration").

---
 drivers/accessibility/braille/braille_console.c | 10 +++++-----
 include/linux/console.h                         |  1 +
 kernel/printk/printk.c                          |  2 +-
 3 files changed, 7 insertions(+), 6 deletions(-)
drivers/accessibility/braille/braille_console.c +5 -5
index 7e6011f9d823..200ca305c6af 100644
@@ -389,11 +389,11 @@ int braille_register_console(struct console *console, int index,
 		console_options = "57600o8";
 	if (braille_co)
 		return -ENODEV;
-	if (console->setup) {
-		ret = console->setup(console, console_options);
-		if (ret != 0)
-			return ret;
-	}
+
+	ret = console_call_setup(console, console_options);
+	if (ret != 0)
+		return ret;
+
 	console->flags |= CON_ENABLED | CON_BRL;
 	console->index = index;
 	braille_co = console;
include/linux/console.h +1 -0
index d780f6de303a..11d6b854ee63 100644
@@ -699,6 +699,7 @@ enum con_flush_mode {
 };
 
 extern int add_preferred_console(const char *name, const short idx, char *options);
+extern int console_call_setup(struct console *newcon, char *options);
 extern void console_force_preferred_locked(struct console *con);
 extern void register_console(struct console *);
 extern int unregister_console(struct console *);
kernel/printk/printk.c +1 -1
index 683083405230..f2a602a05614 100644
@@ -3948,7 +3948,7 @@ static int __init keep_bootcon_setup(char *str)
 
 early_param("keep_bootcon", keep_bootcon_setup);
 
-static int console_call_setup(struct console *newcon, char *options)
+int console_call_setup(struct console *newcon, char *options)
 {
 	int err;
 
Signature · 1 line
2.55.0
Acked-by on v5 11/16
#30 lore raw

Re: [PATCH v5 11/16] console/braille: Lock console->setup() call during the registration

Quoted 4 lines · Petr Mladek

In braille_register_console(), the console->setup() callback must be called while holding the console_lock. This prevents a race condition with a possible active boot console that might be using the same hardware registers.

include/linux/console.h enum con_flush_mode { · line 702

Quoted 8 lines

index d780f6de303a..11d6b854ee63 100644

include/linux/console.h +1 -0
@@ -699,6 +699,7 @@ enum con_flush_mode {
 };
 
 extern int add_preferred_console(const char *name, const short idx, char *options);
+extern int console_call_setup(struct console *newcon, char *options);

Hmm, now that console_call_setup() is global, a short comment saying it is only meant for the Braille driver might discourage other users if you want. But not a big deal either way.

author maintainer
#31 lore raw

Re: [PATCH v5 11/16] console/braille: Lock console->setup() call during the registration

Quoted 14 lines · Chris Down
Quoted 4 lines · Petr Mladek

In braille_register_console(), the console->setup() callback must be called while holding the console_lock. This prevents a race condition with a possible active boot console that might be using the same hardware registers.

Quoted 6 lines

index d780f6de303a..11d6b854ee63 100644

include/linux/console.h +0 -0
@@ -699,6 +699,7 @@ enum con_flush_mode {
 };
 
Quoted 6 lines

include/linux/console.h enum con_flush_mode { · line 702

Quoted 2 lines
include/linux/console.h +1 -0
 extern int add_preferred_console(const char *name, const short idx, char *options);
+extern int console_call_setup(struct console *newcon, char *options);

Hmm, now that console_call_setup() is global, a short comment saying it is only meant for the Braille driver might discourage other users if you want. But not a big deal either way.

OK, I am going to do the following change in v6:

kernel/printk/printk.c +6 -0
@@ -3957,6 +3957,12 @@ static int __init keep_bootcon_setup(char *str)
 
 early_param("keep_bootcon", keep_bootcon_setup);
 
+/*
+ * The function is intended only for the generic console registration code.
+ * It has been made global only for the Braille console driver which
+ * is partly using the generic console registration code but it is
+ * integrated with VT code instead of printk().
+ */
 int console_call_setup(struct console *newcon, char *options)
 {
 	int err;

Best Regards,
Petr

author maintainer
#32 lore raw

PATCH v5 12/16 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.

No behavior change.

---
 kernel/printk/printk.c | 84 ++++++++++++++++++++++++------------------
 1 file changed, 48 insertions(+), 36 deletions(-)
kernel/printk/printk.c +48 -36
index f2a602a05614..8a51c4b690b7 100644
@@ -4026,6 +4026,53 @@ 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) */
+	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. */
 static u64 get_init_console_seq(struct console *newcon, bool bootcon_registered)
 {
@@ -4100,9 +4147,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);
 
 /*
@@ -4164,39 +4208,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);
-
-	/*
-	 * 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 (err == -ENOENT && (newcon->flags & CON_ENABLED))
-		err = 0;
+	err = try_enable_console(newcon);
 
 	/* printk() messages are not printed to the Braille console. */
 	if (err || newcon->flags & CON_BRL) {
Signature · 1 line
2.55.0
author maintainer
#34 lore raw

PATCH v5 13/16 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 | 58 +++++++++++++++++++++++++++++++++++++-----
 1 file changed, 52 insertions(+), 6 deletions(-)
kernel/printk/printk.c +52 -6
index 8a51c4b690b7..75d2a1085926 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 add_or_update_preferred_console(unsigned int i,
 		braille_set_options(pc, brl_options);
 	}
 
-	if (!brl_options)
+	if (brl_options)
+		want_braille_console = true;
+	else
 		preferred_dev_console = i;
 
 	if (user_specified) {
@@ -3969,8 +3972,9 @@ int console_call_setup(struct console *newcon, char *options)
  * by either the command line or add_preferred_console() and
  * setup/enable it.
  */
-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;
@@ -3981,8 +3985,21 @@ 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 (is_braille_console_preferred(pc))
+				continue;
+			if (pc->user_specified != user_specified)
+				continue;
+		}
+
 		if (!newcon->match ||
 		    newcon->match(newcon, pc->name, pc->index, pc->options) != 0) {
 			/* default matching */
@@ -3995,7 +4012,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);
@@ -4011,6 +4028,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)
 {
@@ -4033,6 +4061,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.55.0
Acked-by on v5 13/16
#35 lore raw

Re: [PATCH v5 13/16] printk: Try to register each console as Braille first

Quoted 5 lines · 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.

This also changes what happens when the same driver is wanted both ways, which might be worth a sentence in the commit message.

For example:

console=ttyS1 console=brl,ttyS0

Here we used to end up with ttyS1 as a normal console and the Braille request was silently ignored. Now ttyS0 becomes the Braille console, and every later register_console() from serial core goes to the Braille round and gets -ENODEV from braille_register_console(), so there is no serial console at all.

I think this is probably fine, but just needs clarifying in the commit message.

kernel/printk/printk.c static int try_enable_preferred_console(struct console *newcon, · line 3990

Quoted 1 line
kernel/printk/printk.c +1 -0
+		 * @try_only_braille and @user_specifified define which

-> @user_specified

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

Quoted 8 lines
kernel/printk/printk.c +4 -0
@@ -4033,6 +4061,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

"@preferred_console" is preferred_dev_console now, and it is a variable rather than a parameter, so no "@".

With those:

Thanks!

author maintainer
#36 lore raw

Re: [PATCH v5 13/16] printk: Try to register each console as Braille first

Quoted 10 lines · Chris Down
Quoted 5 lines · 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.

This also changes what happens when the same driver is wanted both ways, which might be worth a sentence in the commit message.

Quoted 8 lines

For example:

console=ttyS1 console=brl,ttyS0

Here we used to end up with ttyS1 as a normal console and the Braille request was silently ignored. Now ttyS0 becomes the Braille console, and every later register_console() from serial core goes to the Braille round and gets -ENODEV from braille_register_console(), so there is no serial console at all.

Great catch! I actually was not aware of this particular variant. I am going to replace the "The refactoring even fixes two subtle bugs:" section with the following:

<paste>
Behavior change:

1. The Braille console driver is newly always preferred even when different serial ports are preferred. For example, let's have the following command lines:

     a) console=ttyS1,115200     console=brl,ttyS0,115200
     b) console=00:00:0.0,115200 console=brl,ttyS0,115200
     c) console=brl,ttyS0,115200 console=ttyS1,115200

They all create two entries in preferred_consoles[] because:

a) and c) differ in @index (0 vs. 1).
b) defines either @name or @devname.

But the original code registers:

a) ttyS1 as normal console because it is the 1st entry in preferred_consoles[].

b) ttyS0 are Braille console because the generic "ttyS" driver is registered early in univ8250_console_init(). The @devname entry is resolved too late when serial8250_init() registers all found devices, it assigns "tty0" for the given "00:00:0.0" but it is already in use.

c) ttyS0 as Braille console because it is the 1st entry in preferred_consoles[].

The new code would register ttyS0 as the Braille console in all three variants because try_enable_braille_console() is called 1st.

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

The 1st change makes the behavior more consistent and understandable. The 2nd change is an obvious bug fix.
</paste>

Quoted 5 lines

I think this is probably fine, but just needs clarifying in the commit message.

kernel/printk/printk.c static int try_enable_preferred_console(struct console *newcon, · line 3990

Quoted 1 line
kernel/printk/printk.c +1 -0
+		 * @try_only_braille and @user_specifified define which

-> @user_specified

Done.

Quoted 12 lines

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

Quoted 8 lines
kernel/printk/printk.c +4 -0
@@ -4033,6 +4061,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

"@preferred_console" is preferred_dev_console now, and it is a variable rather than a parameter, so no "@".

Quoted 3 lines

With those:

I am going to add this "Acked-by" even when the change in the commit message is a bit bigger. But I believe that it is more correct now and it is "just a commit message". I do not want to force you to review the patch thoughtfully again.

Best Regards,
Petr

author maintainer
#37 lore raw

Re: [PATCH v5 13/16] printk: Try to register each console as Braille first

In reply to Petr Mladek
Quoted 56 lines · 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 static int try_enable_preferred_console(struct console *newcon, · line 4018

Quoted 8 lines
kernel/printk/printk.c +1 -1
@@ -3995,7 +4012,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);

From Sashiko AI:

| Does returning 0 here for a Braille match cause the console to lose its
| preferred status?
| 
| When newcon->match() succeeds, the loop falls through to:
| 
|         newcon->flags |= CON_ENABLED;
|         if (i == preferred_dev_console)
|             newcon->flags |= CON_CONSDEV;
|         return 0;
| 
| When returning 0 here after a successful newcon->match() during the
| try_only_braille phase, CON_CONSDEV is not set because preferred_dev_console
| is never assigned to a Braille entry.

This works as expected. The CON_CONSDEV flag is set here only when the related preferred_consoles[i] entry was the latest added/updated entry for a non-Braille console.

Note that there are more situations when the preferred_dev_console is not registered, for example, when there is a typo, or when the related HW is not available.

For this situation, the CON_CONSDEV flag is always assigned to the 1st registered console driver, see the commit 33225d7b0ac990 ("printk: Correctly set CON_CONSDEV even when preferred console was not registered").

[ ... ]

Quoted 11 lines
kernel/printk/printk.c +7 -0
@@ -4033,6 +4061,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.
+	 *

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

Quoted 10 lines
kernel/printk/printk.c +10 -0
+	 * 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;
+	}

Sashiko AI wrote:

| If the user specified both a regular console and a Braille console
| (e.g. console=ttyS0 console=brl,uart,...), does this early return preempt
| the regular console entry from being evaluated?
| 
| If a driver matches the Braille entry and returns 0 without setting
| CON_CONSDEV, returning early here means the regular preferred console entries
| are skipped. This seems to break /dev/console routing, as the expected
| primary console never receives CON_CONSDEV.

The problem with CON_CONSDEV is basically the same as above.

But there is another interesting question whether the console driver can be used as a classic printk console even it could not get enabled as a Braille console. I mean whether, for example, try_enable_default_console(newcon) would fail when try_enable_braille_console(newcon) failed.

I could imagine that the driver might be usable and only the VT integration failed. But the VT integration never fails, see braille_register_console().

Also I think that we do not want to use this driver as a normal console when it was configured to be used by the Braille console.

Best Regards,
Petr

author maintainer
#38 lore raw

PATCH v5 14/16 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.

Assisted-by gemini-1.5-pro
---
 kernel/printk/console_register.h |  3 +++
 kernel/printk/printk.c           | 33 ++++++++++++++++++++++++++------
 2 files changed, 30 insertions(+), 6 deletions(-)
kernel/printk/console_register.h +3 -0
index 9ab3e1cc749b..64cf12fd6ea5 100644
@@ -2,6 +2,8 @@
 #ifndef _CONSOLE_REGISTER_H
 #define _CONSOLE_REGISTER_H
 
+#include <linux/list.h>
+
 struct preferred_console
 {
 	char	name[16];			/* Name of the driver	    */
@@ -12,6 +14,7 @@ struct preferred_console
 #ifdef CONFIG_A11Y_BRAILLE_CONSOLE
 	char	*brl_options;			/* Options for braille driver */
 #endif
+	struct list_head preferred_dev_node;
 };
 
 #endif
kernel/printk/printk.c +27 -6
index 75d2a1085926..a2cc7bf3a62e 100644
@@ -366,7 +366,7 @@ static int console_locked;
 
 static struct preferred_console preferred_consoles[MAX_PREFERRED_CONSOLES];
 
-static int preferred_dev_console = -1;
+static LIST_HEAD(preferred_dev_console);
 static bool want_braille_console;
 int console_set_on_cmdline;
 EXPORT_SYMBOL(console_set_on_cmdline);
@@ -2567,9 +2567,16 @@ asmlinkage __visible void early_printk(const char *fmt, ...)
  *   3. Allow to override @options via the command line. Last one wins
  *	except that the Braille variant is preferred.
  *
+ *   4. Braille console is never associated with /dev/console.[**]
+ *
  *  [*] A valid @name and @idx will get assigned for a devname later when
  *	@devname matches during the device initialization, see
  *	match_devname_and_update_preferred_console().
+ *
+ * [**] 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 add_or_update_preferred_console(unsigned int i,
 					   const char *name, const short idx,
@@ -2645,10 +2652,24 @@ static int add_or_update_preferred_console(unsigned int i,
 		braille_set_options(pc, brl_options);
 	}
 
-	if (brl_options)
+	if (is_new_entry)
+		INIT_LIST_HEAD(&pc->preferred_dev_node);
+
+	/*
+	 * The last preferred console should get associated with /dev/console.
+	 * Except for the Braille console which can't get associated with
+	 * /dev/console.
+	 */
+	if (brl_options) {
 		want_braille_console = true;
-	else
-		preferred_dev_console = i;
+		if (!list_empty(&pc->preferred_dev_node))
+			list_del_init(&pc->preferred_dev_node);
+	} else if (!is_braille_console_preferred(pc)) {
+		if (list_empty(&pc->preferred_dev_node))
+			list_add(&pc->preferred_dev_node, &preferred_dev_console);
+		else
+			list_move(&pc->preferred_dev_node, &preferred_dev_console);
+	}
 
 	if (user_specified) {
 		pc->user_specified = true;
@@ -4020,7 +4041,7 @@ static int __try_enable_preferred_console(struct console *newcon,
 				return err;
 		}
 		newcon->flags |= CON_ENABLED;
-		if (i == preferred_dev_console)
+		if (list_is_first(&pc->preferred_dev_node, &preferred_dev_console))
 			newcon->flags |= CON_CONSDEV;
 		return 0;
 	}
@@ -4091,7 +4112,7 @@ static int try_enable_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_dev_console < 0) {
+	if (list_empty(&preferred_dev_console)) {
 		if (hlist_empty(&console_list) || !console_first()->device ||
 		    console_first()->flags & CON_BOOT) {
 			try_enable_default_console(newcon);
Signature · 1 line
2.55.0
Acked-by on v5 14/16
#39 lore raw

Re: [PATCH v5 14/16] printk: Do not set Braille console as preferred_console

kernel/printk/printk.c static int add_or_update_preferred_console(unsigned int i, · line 2656

Quoted 3 lines · Petr Mladek
kernel/printk/printk.c +2 -1
-	if (brl_options)
+	if (is_new_entry)
+		INIT_LIST_HEAD(&pc->preferred_dev_node);

is_new_entry is derived from pc->name[0]/pc->devname[0] being empty, and console_setup() can store an empty name:

    console=,115200 console=tty1

The first one creates an entry with name "" (and links it). The second one stops the lookup loop at the same slot, sees it as new again, and re-initialises a node which is still linked, followed by list_add(). With DEBUG_LIST + BUG_ON_DATA_CORRUPTION:

    list_add corruption. next->prev should be prev (ffffb010209fc0c0), but was ffffb01023cd1fa0. (next=ffffb01023cd1fa0).
    kernel BUG at lib/list_debug.c:29!
    Call trace:
     __list_add_valid_or_report+0xbc/0x1c0 (P)
     add_or_update_preferred_console+0x6fc/0x9c0
     __add_preferred_console+0x11c/0x160
     console_setup+0x2e4/0x348
     obsolete_checksetup+0x148/0x190
     unknown_bootoption+0x150/0x328
     parse_one+0x108/0x480
     parse_args+0x158/0x3d0
     start_kernel+0x134/0x488

"console=,foo:bar" does the same on the first console= when SPCR added an entry, since it matches the SPCR slot via the empty devname (see 7/16).

Rejecting empty name/devname in add_or_update_preferred_console() (see my comment on 7/16) should fix that.

kernel/printk/printk.c static int add_or_update_preferred_console(unsigned int i, · line 2671

Quoted 8 lines
kernel/printk/printk.c +7 -1
-		preferred_dev_console = i;
+		if (!list_empty(&pc->preferred_dev_node))
+			list_del_init(&pc->preferred_dev_node);
+	} else if (!is_braille_console_preferred(pc)) {
+		if (list_empty(&pc->preferred_dev_node))
+			list_add(&pc->preferred_dev_node, &preferred_dev_console);
+		else
+			list_move(&pc->preferred_dev_node, &preferred_dev_console);

list_del_init() and list_move() are both fine on an initialised self-linked node (list_move() passes the DEBUG_LIST checks in __list_del_entry_valid()), so the list_empty() checks can go.

With these fixed:

Thanks!

author maintainer
#40 lore raw

Re: [PATCH v5 14/16] printk: Do not set Braille console as preferred_console

Quoted 28 lines · Chris Down

Review

Quoted 3 lines · Petr Mladek
(quoted diff) +2 -1
-	if (brl_options)
+	if (is_new_entry)
+		INIT_LIST_HEAD(&pc->preferred_dev_node);

is_new_entry is derived from pc->name[0]/pc->devname[0] being empty, and console_setup() can store an empty name:

    console=,115200 console=tty1

The first one creates an entry with name "" (and links it). The second one stops the lookup loop at the same slot, sees it as new again, and re-initialises a node which is still linked, followed by list_add(). With DEBUG_LIST + BUG_ON_DATA_CORRUPTION:

    list_add corruption. next->prev should be prev (ffffb010209fc0c0), but was ffffb01023cd1fa0. (next=ffffb01023cd1fa0).
    kernel BUG at lib/list_debug.c:29!
    Call trace:
     __list_add_valid_or_report+0xbc/0x1c0 (P)
     add_or_update_preferred_console+0x6fc/0x9c0
     __add_preferred_console+0x11c/0x160
     console_setup+0x2e4/0x348
     obsolete_checksetup+0x148/0x190
     unknown_bootoption+0x150/0x328
     parse_one+0x108/0x480
     parse_args+0x158/0x3d0
     start_kernel+0x134/0x488
Quoted 5 lines

"console=,foo:bar" does the same on the first console= when SPCR added an entry, since it matches the SPCR slot via the empty devname (see 7/16).

Rejecting empty name/devname in add_or_update_preferred_console() (see my comment on 7/16) should fix that.

Yup, it will be fixed in v6 this way.

Quoted 4 lines
Quoted 4 lines
(quoted diff) +3 -1
-		preferred_dev_console = i;
+		if (!list_empty(&pc->preferred_dev_node))
+			list_del_init(&pc->preferred_dev_node);
+	} else if (!is_braille_console_preferred(pc)) {
Quoted 8 lines

Review

Quoted 4 lines
(quoted diff) +4 -0
+		if (list_empty(&pc->preferred_dev_node))
+			list_add(&pc->preferred_dev_node, &preferred_dev_console);
+		else
+			list_move(&pc->preferred_dev_node, &preferred_dev_console);

list_del_init() and list_move() are both fine on an initialised self-linked node (list_move() passes the DEBUG_LIST checks in __list_del_entry_valid()), so the list_empty() checks can go.

I was lazy to check this and wanted to stay on the safe side ;-) OK, I am going to do the following changes for v6:

kernel/printk/printk.c +2 -6
@@ -2666,13 +2666,9 @@ static int add_or_update_preferred_console(unsigned int i,
 	 */
 	if (brl_options) {
 		want_braille_console = true;
-		if (!list_empty(&pc->preferred_dev_node))
-			list_del_init(&pc->preferred_dev_node);
+		list_del_init(&pc->preferred_dev_node);
 	} else if (!is_braille_console_preferred(pc)) {
-		if (list_empty(&pc->preferred_dev_node))
-			list_add(&pc->preferred_dev_node, &preferred_dev_console);
-		else
-			list_move(&pc->preferred_dev_node, &preferred_dev_console);
+		list_move(&pc->preferred_dev_node, &preferred_dev_console);
 	}
 
 	if (user_specified) {
Quoted 3 lines

With these fixed:

Thanks.

Best Regards,
Petr

author maintainer
#41 lore raw

PATCH v5 15/16 printk: Modify try_enable_default_console() to return error/success

In reply to Petr Mladek

Currently, try_enable_default_console() has a void return type, and its potential failures (specifically when console_call_setup() fails) are ignored by its caller, try_enable_console().

Modify try_enable_default_console() to return error/success, and update try_enable_console() to capture and propagate this error.

With this change, try_enable_console() will no longer return success for a pre-enabled console if try_enable_default_console() failed (such as when newcon->setup() fails). While this might change existing behavior, it is the correct approach to ensure setup errors are not silently ignored or treated as successful registrations simply because the console was marked pre-enabled.

Assisted-by Gemini:gemini-3 # commit message
---
 kernel/printk/printk.c | 15 +++++++++++----
 1 file changed, 11 insertions(+), 4 deletions(-)
kernel/printk/printk.c +11 -4
index a2cc7bf3a62e..1eb749da9e24 100644
@@ -4061,18 +4061,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()				\
@@ -4115,7 +4120,9 @@ static int try_enable_console(struct console *newcon)
 	if (list_empty(&preferred_dev_console)) {
 		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.55.0
author maintainer
#43 lore raw

PATCH v5 16/16 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:

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

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

- 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. The already fixed handling of pre-enabled consoles actually helps even the 3rd case. try_enable_default_console() sets CON_ENABLED flag on success and is later handled as pre-enabled.

Prevent any future hidden effects and call try_enable_preferred_console() only when some console is preferred.

No behavior change.

---
 kernel/printk/printk.c | 26 +++++++++++++++++---------
 1 file changed, 17 insertions(+), 9 deletions(-)
kernel/printk/printk.c +17 -9
index 1eb749da9e24..06c49042dd8f 100644
@@ -4085,7 +4085,7 @@ static int try_enable_default_console(struct console *newcon)
 
 static int try_enable_console(struct console *newcon)
 {
-	int err;
+	int err = -ENOENT;
 
 	/*
 	 * First, try to enable the console driver as a Braille console.
@@ -4124,16 +4124,24 @@ static int try_enable_console(struct console *newcon)
 			if (err != -ENOENT)
 				return err;
 		}
+	} else {
+		/* 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;
 	}
 
-	/* 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)
+	/*
+	 * Make sure that pre-enabled consoles won't get registered when
+	 * something went wrong. This is just a paranoid check that all
+	 * branches above returned on error.
+	 */
+	if (WARN_ON(err != -ENOENT))
 		return err;
 
 	/*
Signature · 1 line
2.55.0