[PATCH v7 07/17] printk: Check that index is not defined when a console is preferred via devname

From: Petr Mladek

Date: Wed Nov 11 2026 - 10:53:56 EST


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.

Signed-off-by: Petr Mladek <pmladek@xxxxxxxx>
---
kernel/printk/printk.c | 34 ++++++++++++++++++++++------------
1 file changed, 22 insertions(+), 12 deletions(-)

diff --git a/kernel/printk/printk.c b/kernel/printk/printk.c
index b139314eda70..a76f37c1b431 100644
--- a/kernel/printk/printk.c
+++ b/kernel/printk/printk.c
@@ -2562,7 +2562,7 @@ asmlinkage __visible void early_printk(const char *fmt, ...)
*
* 1. Do not accept empty @name or @devname.
*
- * 2. Either @name OR @devname are allowed. [*]
+ * 2. 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
@@ -2595,23 +2595,33 @@ static int add_or_update_preferred_console(unsigned int i,
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;

if (is_new_entry) {
- if (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",
+ name, idx);
+ return -EINVAL;
+ }
strscpy(pc->name, name);
- if (devname)
+ }
+
+ if (devname) {
+ /*
+ * A valid console name and index will get assigned when
+ * a matching device gets registered.
+ */
+ if (idx >= 0) {
+ 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;
}

--
2.56.0