serial: fix console lifetime bugs on failed bind and removal
Subsystems (3)
v2 cover serial: fix console lifetime bugs on failed bind and removal
This series fixes three serial/tty bind-error bugs and an i.MX console port-table lifetime bug. The fixes were found with failslab fail-nth sweeps and sysfs bind/unbind sequences under KASAN on QEMU's raspi1ap and mcimx6ul-evk machines.
Patches 1-3 fix shared serial/tty core code. Patch 1 moves fallible serial core allocations before console registration; patch 2 clears serial-core pointers after uart_driver registration fails; and patch 3 makes a non-NULL tty cdev slot mean that the cdev is live.
Patch 4 clears i.MX's devm-allocated port-table entry on probe failure and removal. It keeps the entry valid through console unregistration and serializes the table updates against sibling probes.
Backporting note: the probe-failure half of patch 4 relies on patch 1, which ensures that uart_add_one_port() cannot fail after registering the console. For complete coverage, patches 1 and 4 should be backported together.
Validation for patch 4 includes reproducing the sibling-probe race under KASAN with and without the fix, a sequential unbind/rebind regression, and the same test with CONFIG_PROVE_LOCKING=y. The fixed kernel keeps the console unregistered and survives an explicit printk in each applicable run.
Changes in v2:
- Patch 4: serialize port registration and removal with imx_uart_ports[] updates to close the reported sibling-probe race.
- Patches 1-3 are unchanged.
v1: https://lore.kernel.org/r/[email protected]
Karl Mehltretter (4):
serial: core: do fallible allocations before the console can be
registered
serial: core: clear freed pointers on uart_register_driver() failure
tty: don't oops in tty_unregister_device() when no cdev is registered
serial: imx: serialize imx_uart_ports[] lifetime
drivers/tty/serial/imx.c | 21 ++++++++++++++++++-- drivers/tty/serial/serial_core.c | 33 ++++++++++++++++++-------------- drivers/tty/tty_io.c | 6 ++++-- 3 files changed, 42 insertions(+), 18 deletions(-)
Signature · 1 line
2.53.0
PATCH v2 1/4 serial: core: do fallible allocations before the console can be registered
serial_core_add_one_port() allocates uport->tty_groups after uart_configure_port() has already registered the port's console. If that allocation fails, the function returns -ENOMEM with the console still registered, and the driver's probe error path then tears down the port state the console callbacks depend on.
Reproduced with fault injection on qemu's raspi1ap board. Failing the tty_groups allocation during a PL011 sysfs bind makes uart_add_one_port() return -ENOMEM. pl011_register_port() then clears amba_ports[0], but ttyAMA0 remains registered as a console. The nbcon printer thread dereferences the NULL entry and oopses:
Unhandled fault: page domain fault (0x01b) at 0x00000178
CPU: 0 UID: 0 PID: 43 Comm: pr/ttyAMA0 Not tainted 7.2.0-rc3+ #1 PC is at pl011_console_write_thread+0x2c/0x168
This is not PL011-specific: the failing allocation is in serial core, after uart_configure_port() has registered the console, so any console UART driver is exposed. On i.MX the retained console references a devm-allocated port that the failed probe frees, causing a use-after-free. Reproduced on qemu's mcimx6ul-evk using the same fail-nth harness under KASAN:
BUG: KASAN: slab-use-after-free in imx_uart_console_write_thread+0x50/0x278 Read of size 4 at addr c5246048 by task pr/ttymxc0/63 imx_uart_console_write_thread from nbcon_emit_next_record+0x360/0x50c nbcon_emit_next_record from nbcon_emit_one+0x140/0x184 Allocated by task 1: devm_kmalloc from imx_uart_probe+0x90/0xa5c Freed by task 1: devres_release_all from device_unbind_cleanup+0x38/0xdc device_unbind_cleanup from really_probe+0x2b4/0x388
The pre-existing kasprintf() failure path has a related problem: it returns with state->uart_port already pointing at a port whose probe is about to unwind and free it.
Reorder the function so the uport->name and uport->tty_groups allocations both happen before the port is linked into the driver state table and before uart_configure_port() registers the console:
1. Allocate uport->name.
2. Allocate the tty_groups array with room for three entries unconditionally (serial core group, optional driver group, NULL terminator). The optional group cannot be examined at this point:
config_port() may only supply uport->attr_group during uart_configure_port(), e.g. 8250 sets it after autodetection.
3. Only then link the port into the driver state table and run uart_configure_port().
4. Fill in the optional attr_group slot afterwards.
A fail-nth sweep over the whole bind path on both boards left the console unregistered after every failed bind and did not reproduce the i.MX use-after-free.
--- drivers/tty/serial/serial_core.c | 31 +++++++++++++++++-------------- 1 file changed, 17 insertions(+), 14 deletions(-)
drivers/tty/serial/serial_core.c +17 -14
@@ -3056,7 +3056,6 @@ static int serial_core_add_one_port(struct uart_driver *drv, struct uart_port *ustruct uart_state *state;struct tty_port *port;struct device *tty_dev; -int num_groups;if (uport->line >= drv->nr)return -EINVAL ;
@@ -3068,6 +3067,23 @@ static int serial_core_add_one_port(struct uart_driver *drv, struct uart_port *uif (state->uart_port)return -EINVAL ; + uport->name =kasprintf (GFP_KERNEL ,"%s%u" , drv->dev_name, + drv->tty_driver->name_base + uport->line); +if (!uport->name) +return -ENOMEM ; + +/* +* uart_configure_port() may set uport->attr_group and register the +* console. Allocate room for both groups and a NULL terminator first. +*/ + uport->tty_groups =kzalloc_objs (*uport->tty_groups,3 ); +if (!uport->tty_groups) { +kfree (uport->name); + uport->name =NULL ; +return -ENOMEM ; + } + uport->tty_groups[0 ] = &tty_dev_attr_group; +/* Link the port to the driver state table and vice versa */ atomic_set (&state->refcount,1 );init_waitqueue_head (&state->remove_wait);
@@ -3084,10 +3100,6 @@ static int serial_core_add_one_port(struct uart_driver *drv, struct uart_port *u state->pm_state =UART_PM_STATE_UNDEFINED ;uart_port_set_cons (uport, drv->cons); uport->minor = drv->tty_driver->minor_start + uport->line; - uport->name =kasprintf (GFP_KERNEL ,"%s%u" , drv->dev_name, - drv->tty_driver->name_base + uport->line); -if (!uport->name) -return -ENOMEM ;if (uport->cons && uport->dev)of_console_check (uport->dev->of_node, uport->cons->name, uport->line);
@@ -3102,15 +3114,6 @@ static int serial_core_add_one_port(struct uart_driver *drv, struct uart_port *u port->console =uart_console (uport); - num_groups =2 ; -if (uport->attr_group) - num_groups++; - - uport->tty_groups =kzalloc_objs (*uport->tty_groups, num_groups); -if (!uport->tty_groups) -return -ENOMEM ; - - uport->tty_groups[0 ] = &tty_dev_attr_group;if (uport->attr_group) uport->tty_groups[1 ] = uport->attr_group;
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerRe: [PATCH v2 1/4] serial: core: do fallible allocations before the console can be registered
Quoted 51 lines · Karl Mehltretter
serial_core_add_one_port()allocatesuport->tty_groupsafteruart_configure_port()has already registered the port's console. If that allocation fails, the function returns-ENOMEMwith the console still registered, and the driver's probe error path then tears down the port state the console callbacks depend on.Reproduced with fault injection on qemu's raspi1ap board. Failing the
tty_groupsallocation during a PL011 sysfs bind makesuart_add_one_port()return-ENOMEM.pl011_register_port()then clears amba_ports[0], but ttyAMA0 remains registered as a console. The nbcon printer thread dereferences the NULL entry and oopses:Unhandled fault: page domain fault (
0x01b) at0x00000178CPU: 0 UID: 0 PID: 43 Comm: pr/ttyAMA0 Not tainted 7.2.0-rc3+ #1 PC is at pl011_console_write_thread+0x2c/0x168This is not PL011-specific: the failing allocation is in serial core, after
uart_configure_port()has registered the console, so any console UART driver is exposed. On i.MX the retained console references a devm-allocated port that the failed probe frees, causing a use-after-free. Reproduced on qemu's mcimx6ul-evk using the same fail-nth harness under KASAN:BUG: KASAN: slab-use-after-free in imx_uart_console_write_thread+0x50/0x278 Read of size 4 at addr c5246048 by task pr/ttymxc0/63 imx_uart_console_write_thread from nbcon_emit_next_record+0x360/0x50c nbcon_emit_next_record from nbcon_emit_one+0x140/0x184 Allocated by task 1: devm_kmalloc from imx_uart_probe+0x90/0xa5c Freed by task 1: devres_release_all from device_unbind_cleanup+0x38/0xdc device_unbind_cleanup from really_probe+0x2b4/0x388The pre-existing
kasprintf()failure path has a related problem: it returns withstate->uart_portalready pointing at a port whose probe is about to unwind and free it.Reorder the function so the
uport->nameanduport->tty_groupsallocations both happen before the port is linked into the driver state table and beforeuart_configure_port()registers the console:1. Allocate
uport->name.
2. Allocate thetty_groupsarray with room for three entries unconditionally (serial core group, optional driver group, NULL terminator). The optional group cannot be examined at this point:
config_port()may only supplyuport->attr_groupduringuart_configure_port(), e.g. 8250 sets it after autodetection.
3. Only then link the port into the driver state table and runuart_configure_port().
4. Fill in the optionalattr_groupslot afterwards.
Quoted 7 lines
A fail-nth sweep over the whole bind path on both boards left the console unregistered after every failed bind and did not reproduce the i.MX use-after-free.
Fixes 266dcff03eed ("Serial: allow port drivers to have a default attribute group")Fixes f7048b15900f ("tty: serial_core: Add name field to uart_port struct")
As this can only be duplicated with fault-injection, it really doesn't need to go to any stable kernels, right?
Quoted 25 lines
Assisted-by Claude:claude-fable-5Signed-off-by Karl Mehltretter <[email protected]>--- drivers/tty/serial/serial_core.c | 31 +++++++++++++++++-------------- 1 file changed, 17 insertions(+), 14 deletions(-)drivers/tty/serial/serial_core.c +3
-1@@ -3056,7 +3056,6 @@ static int serial_core_add_one_port(struct uart_driver *drv, struct uart_port *ustruct uart_state *state;struct tty_port *port;struct device *tty_dev; -int num_groups;if (uport->line >= drv->nr)return -EINVAL ;@@ -3068,6 +3067,23 @@ static int serial_core_add_one_port(struct uart_driver *drv, struct uart_port *uif (state->uart_port)return -EINVAL ; + uport->name =kasprintf (GFP_KERNEL ,"%s%u" , drv->dev_name, + drv->tty_driver->name_base + uport->line); +if (!uport->name)
drivers/tty/serial/serial_core.c static int serial_core_add_one_port(struct uart_driver *drv, struct uart_port *u · line 3082
Quoted 10 lines
drivers/tty/serial/serial_core.c +10
-0+return -ENOMEM ; + +/* +* uart_configure_port() may set uport->attr_group and register the +* console. Allocate room for both groups and a NULL terminator first. +*/ + uport->tty_groups =kzalloc_objs (*uport->tty_groups,3 ); +if (!uport->tty_groups) { +kfree (uport->name); + uport->name =NULL ;
Why set this to NULL?
thanks,
greg k-h
Re: [PATCH v2 1/4] serial: core: do fallible allocations before the console can be registered
Quoted 4 lines · Greg Kroah-Hartman
Quoted 1 line
As this can only be duplicated with fault-injection, it really doesn't need to go to any stable kernels, right?
Agreed, I'll drop it.
Quoted 7 lines
drivers/tty/serial/serial_core.c static int serial_core_add_one_port(struct uart_driver *drv, struct uart_port *u · line 3082
Quoted 4 lines
drivers/tty/serial/serial_core.c +3
-0+if (!uport->tty_groups) { +kfree (uport->name); + uport->name =NULL ;Why set this to NULL?
It's not necessary. I will remove it.
Thanks,
Karl
PATCH v2 2/4 serial: core: clear freed pointers on uart_register_driver() failure
In reply to Karl Mehltretteruart_register_driver() leaves freed pointers behind on failure. If tty_alloc_driver() fails, it frees drv->state without clearing it. If tty_register_driver() fails, it also drops the tty driver reference without clearing drv->tty_driver.
Several drivers register the uart_driver lazily and use drv->state as an "already registered" sentinel. After a failed registration, the next probe sees the stale pointer, skips re-registration and calls uart_add_one_port() with freed state.
The resulting unwind can call uart_unregister_driver() with a NULL or dangling drv->tty_driver and oops in tty_unregister_driver():
Unhandled fault: page domain fault (0x01b) at 0x00000018 PC is at tty_unregister_driver+0x10/0x68
LR is at uart_unregister_driver+0x1c/0x60
Reproduced with failslab fail-nth injection on qemu's raspi1ap board:
fail the tty_alloc_driver() allocation during a sysfs bind of the PL011 port, then bind again in the same boot.
Clear drv->state after freeing the state array and clear drv->tty_driver after dropping the tty driver reference, as uart_unregister_driver() already does.
The tty_register_driver() failure case predates Git history. The tty_alloc_driver() failure case was introduced by commit 9e845abfc8a8 ("serial: fix NULL pointer dereference"), which made that error path return cleanly instead of crashing in put_tty_driver(NULL).
--- drivers/tty/serial/serial_core.c | 2 ++ 1 file changed, 2 insertions(+)
drivers/tty/serial/serial_core.c +2 -0
@@ -2777,8 +2777,10 @@ int uart_register_driver(struct uart_driver *drv)for (i =0 ; i < drv->nr; i++)tty_port_destroy (&drv->state[i].port);tty_driver_kref_put (normal); + drv->tty_driver =NULL ; out_kfree:kfree (drv->state); + drv->state =NULL ; out:return retval; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerRe: [PATCH v2 2/4] serial: core: clear freed pointers on uart_register_driver() failure
Quoted 25 lines · Karl Mehltretter
uart_register_driver()leaves freed pointers behind on failure. Iftty_alloc_driver()fails, it freesdrv->statewithout clearing it. Iftty_register_driver()fails, it also drops the tty driver reference without clearingdrv->tty_driver.Several drivers register the
uart_driverlazily and usedrv->stateas an "already registered" sentinel. After a failed registration, the next probe sees the stale pointer, skips re-registration and callsuart_add_one_port()with freed state.The resulting unwind can call
uart_unregister_driver()with a NULL or danglingdrv->tty_driverand oops intty_unregister_driver():Unhandled fault: page domain fault (
0x01b) at0x00000018PC is attty_unregister_driver+0x10/0x68
LR is atuart_unregister_driver+0x1c/0x60Reproduced with failslab fail-nth injection on qemu's raspi1ap board:
fail thetty_alloc_driver()allocation during a sysfs bind of the PL011 port, then bind again in the same boot.Clear
drv->stateafter freeing the state array and cleardrv->tty_driverafter dropping the tty driver reference, asuart_unregister_driver()already does.
Quoted 8 lines
The
tty_register_driver()failure case predates Git history. Thetty_alloc_driver()failure case was introduced by commit9e845abfc8a8("serial: fix NULL pointer dereference"), which made that error path return cleanly instead of crashing input_tty_driver(NULL).Fixes 1da177e4c3f4 ("Linux-2.6.12-rc2")Fixes 9e845abfc8a8 ("serial: fix NULL pointer dereference")
Same comment here, this can't ever be hit by a "normal" user, right?
thanks,
greg k-h
PATCH v2 3/4 tty: don't oops in tty_unregister_device() when no cdev is registered
In reply to Karl Mehltretterserial_core_add_one_port() keeps a uart_port when tty device registration fails so setserial can still use it. It marks the port UPF_DEAD and returns success. Removing the port later reaches tty_unregister_device(), which unconditionally passes driver->cdevs[index] to cdev_del().
The slot does not always contain a live cdev. A serdev registration error other than -ENODEV returns before tty_register_device_attr(), leaving the slot NULL. If cdev_add() fails, tty_cdev_add() drops the cdev reference but leaves the slot pointing at freed memory. The later cdev_del() is therefore a NULL dereference or use-after-free.
The NULL path was reproduced with failslab during UART bind on qemu's mcimx6ul-evk and raspi1ap boards:
Unhandled fault: page domain fault (0x01b) at 0x00000038 PC is at cdev_del+0x14/0x34
Clear the slot after cdev_add() fails and only call cdev_del() when it is non-NULL. This makes a non-NULL slot mean that a live cdev is registered.
--- drivers/tty/tty_io.c | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-)
drivers/tty/tty_io.c +4 -2
@@ -3167,8 +3167,10 @@ static int tty_cdev_add(struct tty_driver *driver, dev_t dev, driver->cdevs[index]->ops = &tty_fops; driver->cdevs[index]->owner = driver->owner; err =cdev_add (driver->cdevs[index], dev, count); -if (err) +if (err) {kobject_put (&driver->cdevs[index]->kobj); + driver->cdevs[index] =NULL ; + }return err; }
@@ -3305,7 +3307,7 @@ EXPORT_SYMBOL_GPL(tty_register_device_attr);void tty_unregister_device (struct tty_driver *driver,unsigned index) {device_destroy (&tty_class,MKDEV (driver->major, driver->minor_start) + index); -if (!(driver->flags &TTY_DRIVER_DYNAMIC_ALLOC )) { +if (!(driver->flags &TTY_DRIVER_DYNAMIC_ALLOC ) && driver->cdevs[index]) {cdev_del (driver->cdevs[index]); driver->cdevs[index] =NULL ; }
Signature · 1 line
2.53.0
Greg Kroah-Hartman
maintainerRe: [PATCH v2 3/4] tty: don't oops in tty_unregister_device() when no cdev is registered
Quoted 11 lines · Karl Mehltretter
serial_core_add_one_port()keeps auart_portwhen tty device registration fails so setserial can still use it. It marks the portUPF_DEADand returns success. Removing the port later reachestty_unregister_device(), which unconditionally passes driver->cdevs[index] tocdev_del().The slot does not always contain a live cdev. A serdev registration error other than
-ENODEVreturns beforetty_register_device_attr(), leaving the slot NULL. Ifcdev_add()fails,tty_cdev_add()drops the cdev reference but leaves the slot pointing at freed memory. The latercdev_del()is therefore a NULL dereference or use-after-free.
Quoted 8 lines
The NULL path was reproduced with failslab during UART bind on qemu's mcimx6ul-evk and raspi1ap boards:
Unhandled fault: page domain fault (
0x01b) at0x00000038PC is atcdev_del+0x14/0x34Clear the slot after
cdev_add()fails and only callcdev_del()when it is non-NULL. This makes a non-NULL slot mean that a live cdev is registered.
Note, LLMs love to write a lot. Please always rewrite the changelog text to be sane and concise.
Quoted 27 lines
Fixes c1a752ba2d6b ("tty: don't leak cdev in tty_cdev_add()")Fixes 8cde11b2baa1 ("tty/serdev: add serdev registration interface")Assisted-by Claude:claude-fable-5Signed-off-by Karl Mehltretter <[email protected]>--- drivers/tty/tty_io.c | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-)drivers/tty/tty_io.c +3
-1@@ -3167,8 +3167,10 @@ static int tty_cdev_add(struct tty_driver *driver, dev_t dev, driver->cdevs[index]->ops = &tty_fops; driver->cdevs[index]->owner = driver->owner; err =cdev_add (driver->cdevs[index], dev, count); -if (err) +if (err) {kobject_put (&driver->cdevs[index]->kobj); + driver->cdevs[index] =NULL ; + }return err; }
drivers/tty/tty_io.c EXPORT_SYMBOL_GPL(tty_register_device_attr); · line 3310
Quoted 5 lines
drivers/tty/tty_io.c +1
-1@@ -3305,7 +3307,7 @@ EXPORT_SYMBOL_GPL(tty_register_device_attr);void tty_unregister_device (struct tty_driver *driver,unsigned index) {device_destroy (&tty_class,MKDEV (driver->major, driver->minor_start) + index); -if (!(driver->flags &TTY_DRIVER_DYNAMIC_ALLOC )) { +if (!(driver->flags &TTY_DRIVER_DYNAMIC_ALLOC ) && driver->cdevs[index]) {
This looks to be doing 2 different things in one patch, or am I confused?
thanks,
greg k-h
Re: [PATCH v2 3/4] tty: don't oops in tty_unregister_device() when no cdev is registered
Quoted 3 lines · Greg Kroah-Hartman
Note, LLMs love to write a lot. Please always rewrite the changelog text to be sane and concise.
Understood. I'll clean it up more.
Quoted 3 lines
This looks to be doing 2 different things in one patch, or am I confused?
Good point. I'll split it into two for v3, with corresponding Fixes: tags.
Thanks,
Karl
PATCH v2 4/4 serial: imx: serialize imx_uart_ports[] lifetime
In reply to Karl Mehltretterimx_uart_probe() publishes the port in imx_uart_ports[] before uart_add_one_port(), because console setup during that call uses the table. The entry is not cleared if adding the port fails or after imx_uart_remove() removes it.
The port is devm-allocated, so a failed probe or unbind leaves the table pointing at freed memory. A later registration of the shared console can then dereference the stale entry. Reproduced on QEMU's mcimx6ul-evk by unbinding a sibling UART, unbinding the console UART and rebinding the sibling:
BUG: KASAN: slab-use-after-free in imx_uart_console_setup+0xd0/0x3d8
The entry must remain valid until uart_remove_one_port() unregisters the console. Clearing it afterward without serialization still races a sibling probe: the sibling can register the shared console using the dying entry before it is cleared. The next console write then dereferences NULL.
Use a driver-wide mutex to serialize table publication, port addition and rollback with port removal and table clearing. Console callbacks remain lockless because uart_add_one_port() may invoke setup while probe holds the mutex.
The probe-failure path also relies on "serial: core: do fallible allocations before the console can be registered", which moves the uport->name and uport->tty_groups allocations before console registration. Both changes should be backported together.
--- drivers/tty/serial/imx.c | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-)
drivers/tty/serial/imx.c +19 -2
@@ -22,6 +22,7 @@#include <linux/clk.h> #include <linux/delay.h> #include <linux/ktime.h> +#include <linux/mutex.h> #include <linux/pinctrl/consumer.h> #include <linux/rational.h> #include <linux/slab.h>
@@ -2080,6 +2081,15 @@ static const struct uart_ops imx_uart_pops = {static struct imx_port *imx_uart_ports[UART_NR ]; +/* +* Store the port in imx_uart_ports[] before uart_add_one_port() and clear +* it only after uart_remove_one_port() returns. Console callbacks in both +* calls use the table, so this mutex serializes these sequences between +* sibling ports. Callbacks must not take it because uart_add_one_port() +* may invoke setup while it is held. +*/ +static DEFINE_MUTEX (imx_uart_ports_lock); +#if IS_ENABLED (CONFIG_SERIAL_IMX_CONSOLE )static void imx_uart_console_putchar (struct uart_port *port,unsigned char ch) {
@@ -2632,11 +2642,14 @@ static int imx_uart_probe(struct platform_device *pdev) } } - imx_uart_ports[sport->port.line] = sport; -platform_set_drvdata (pdev, sport); +mutex_lock (&imx_uart_ports_lock); + imx_uart_ports[sport->port.line] = sport; ret =uart_add_one_port (&imx_uart_uart_driver, &sport->port); +if (ret) + imx_uart_ports[sport->port.line] =NULL ; +mutex_unlock (&imx_uart_ports_lock); err_clk:clk_disable_unprepare (sport->clk_ipg);
@@ -2647,8 +2660,12 @@ static int imx_uart_probe(struct platform_device *pdev)static void imx_uart_remove (struct platform_device *pdev) {struct imx_port *sport =platform_get_drvdata (pdev); +unsigned int line = sport->port.line; +mutex_lock (&imx_uart_ports_lock);uart_remove_one_port (&imx_uart_uart_driver, &sport->port); + imx_uart_ports[line] =NULL ; +mutex_unlock (&imx_uart_ports_lock); }static void imx_uart_restore_context (struct imx_port *sport)
Signature · 1 line
2.53.0
[email protected]
AI reviewRe: [PATCH v2 4/4] serial: imx: serialize imx_uart_ports[] lifetime
Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider:
Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider:
New issues:
- [High] Clobbering of an active port entry in imx_uart_ports during a duplicate-line probe leads to a NULL pointer dereference.
Pre-existing issues:
- [High] Missing explicit cancellation of hrtimers during device removal leads to Use-After-Free.
- [High] imx_uart_probe() requests interrupts before sport->port.state is initialized, without fully clearing all hardware interrupt enable bits. --
--- Patch [4]: [PATCH v2 4/4] serial: imx: serialize imx_uart_ports[] lifetime --- commit 7a4c9e19ce793ebaff93921ddc3c70f324874180
Author: Karl Mehltretter <[email protected]>
serial: imx: serialize imx_uart_ports[] lifetime
imx_uart_probe() publishes the port in imx_uart_ports[] before uart_add_one_port(), because console setup during that call uses the table. Use a driver-wide mutex to serialize table publication, port addition and rollback with port removal and table clearing.
Quoted 4 lines
drivers/tty/serial/imx.c +0
-0
[ ... ]
drivers/tty/serial/imx.c static int imx_uart_probe(struct platform_device *pdev) · line 2651
Quoted 13 lines
drivers/tty/serial/imx.c +5
-2@@ -2632,11 +2642,14 @@ static int imx_uart_probe(struct platform_device *pdev) } } - imx_uart_ports[sport->port.line] = sport; -platform_set_drvdata (pdev, sport); +mutex_lock (&imx_uart_ports_lock); + imx_uart_ports[sport->port.line] = sport; + ret =uart_add_one_port (&imx_uart_uart_driver, &sport->port); +if (ret) + imx_uart_ports[sport->port.line] =NULL ;
[Severity: High]
If a duplicate UART alias is probed, such as from a misconfigured device tree, does this unconditionally overwrite an already active port's entry in imx_uart_ports?
When uart_add_one_port() subsequently fails for the duplicate, this error path sets the entry to NULL. The original port remains active, but will console callbacks that rely on imx_uart_ports[] encounter a NULL pointer dereference and crash the system?
[Severity: High]
This is a pre-existing issue, but I noticed that just before this code in imx_uart_probe(), devm_request_irq() is called before sport->port.state is initialized by uart_add_one_port().
Since UCR4 interrupt flags (like UCR4_TCEN) are not fully cleared, could an early spurious interrupt fire immediately if left enabled by the bootloader or a previous crash kernel?
If the interrupt fires, the ISR would call:
imx_uart_transmit_buffer()
struct tty_port *tport = &sport->port.state->port;
Would this dereference the uninitialized sport->port.state and cause a kernel panic?
Quoted 7 lines
drivers/tty/serial/imx.c +1
-0+mutex_unlock (&imx_uart_ports_lock); err_clk:clk_disable_unprepare (sport->clk_ipg);return ret; }
drivers/tty/serial/imx.c static int imx_uart_probe(struct platform_device *pdev) · line 2668
Quoted 10 lines
drivers/tty/serial/imx.c +4
-0static void imx_uart_remove (struct platform_device *pdev) {struct imx_port *sport =platform_get_drvdata (pdev); +unsigned int line = sport->port.line; +mutex_lock (&imx_uart_ports_lock);uart_remove_one_port (&imx_uart_uart_driver, &sport->port); + imx_uart_ports[line] =NULL ; +mutex_unlock (&imx_uart_ports_lock);
[Severity: High]
This is a pre-existing issue, but does imx_uart_remove() need to explicitly cancel any pending hrtimers before returning?
During imx_uart_shutdown(), if the TX state is SEND (e.g., in RS485 mode) and the hrtimer fires late, the shutdown loop forces the state to OFF upon timeout but does not cancel the timer:
imx_uart_shutdown()
if (sport->tx_state != OFF) {
dev_warn(sport->port.dev, "unexpected tx_state\n");
...
sport->tx_state = OFF;
}Since sport is devm-allocated, it is freed immediately after imx_uart_remove() returns. Could the pending trigger_stop_tx hrtimer then fire and cause a use-after-free on the sport structure?
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=4
Re: [PATCH v2 4/4] serial: imx: serialize imx_uart_ports[] lifetime
Quoted 10 lines · On Sun, Jul 19, 2026 at 10:25:00PM +0100, [email protected] wrote:
[Severity: High]
If a duplicate UART alias is probed, such as from a misconfigured device tree, does this unconditionally overwrite an already active port's entry inimx_uart_ports?When
uart_add_one_port()subsequently fails for the duplicate, this error path sets the entry to NULL. The original port remains active, but will console callbacks that rely on imx_uart_ports[] encounter a NULL pointer dereference and crash the system?
The existing code already overwrites the active slot.
If uart_add_one_port() fails, this leaves the slot pointing to the freed duplicate port. This patch changes that failure mode to a NULL pointer. I'll reject an occupied slot in v3.
Thanks,
Karl
Greg Kroah-Hartman
maintainerRe: [PATCH v2 4/4] serial: imx: serialize imx_uart_ports[] lifetime
In reply to Karl MehltretterQuoted 54 lines · Karl Mehltretter
imx_uart_probe()publishes the port in imx_uart_ports[] beforeuart_add_one_port(), because console setup during that call uses the table. The entry is not cleared if adding the port fails or afterimx_uart_remove()removes it.The port is devm-allocated, so a failed probe or unbind leaves the table pointing at freed memory. A later registration of the shared console can then dereference the stale entry. Reproduced on QEMU's mcimx6ul-evk by unbinding a sibling UART, unbinding the console UART and rebinding the sibling:
BUG: KASAN: slab-use-after-free in imx_uart_console_setup+0xd0/0x3d8The entry must remain valid until
uart_remove_one_port()unregisters the console. Clearing it afterward without serialization still races a sibling probe: the sibling can register the shared console using the dying entry before it is cleared. The next console write then dereferences NULL.Use a driver-wide mutex to serialize table publication, port addition and rollback with port removal and table clearing. Console callbacks remain lockless because
uart_add_one_port()may invoke setup while probe holds the mutex.The probe-failure path also relies on "serial: core: do fallible allocations before the console can be registered", which moves the
uport->nameanduport->tty_groupsallocations before console registration. Both changes should be backported together.Fixes dbff4e9ea2e8 ("IMX UART: remove statically initialized tables")Fixes 9f322ad064f9 ("imx: serial: handle initialisation failure correctly")Reported-by Sashiko <[email protected]>Assisted-by Claude:claude-fable-5Signed-off-by Karl Mehltretter <[email protected]>--- drivers/tty/serial/imx.c | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-)drivers/tty/serial/imx.c +1
-0@@ -22,6 +22,7 @@#include <linux/clk.h> #include <linux/delay.h> #include <linux/ktime.h> +#include <linux/mutex.h> #include <linux/pinctrl/consumer.h> #include <linux/rational.h> #include <linux/slab.h> @@ -2080,6 +2081,15 @@ static const struct uart_ops imx_uart_pops = {
drivers/tty/serial/imx.c static const struct uart_ops imx_uart_pops = { · line 2091
Quoted 10 lines
drivers/tty/serial/imx.c +8
-0static struct imx_port *imx_uart_ports[UART_NR ]; +/* +* Store the port in imx_uart_ports[] before uart_add_one_port() and clear +* it only after uart_remove_one_port() returns. Console callbacks in both +* calls use the table, so this mutex serializes these sequences between +* sibling ports. Callbacks must not take it because uart_add_one_port() +* may invoke setup while it is held. +*/ +static DEFINE_MUTEX (imx_uart_ports_lock);
Again, LLMs love to write comments/text, be sane please. This comment has nothing to do with the storing and such.
drivers/tty/serial/imx.c static int imx_uart_probe(struct platform_device *pdev) · line 2647
Quoted 13 lines
drivers/tty/serial/imx.c +2
-2+#if IS_ENABLED (CONFIG_SERIAL_IMX_CONSOLE )static void imx_uart_console_putchar (struct uart_port *port,unsigned char ch) {@@ -2632,11 +2642,14 @@ static int imx_uart_probe(struct platform_device *pdev) } } - imx_uart_ports[sport->port.line] = sport; -platform_set_drvdata (pdev, sport); +mutex_lock (&imx_uart_ports_lock);
guard()?
drivers/tty/serial/imx.c static int imx_uart_probe(struct platform_device *pdev) · line 2663
Quoted 13 lines
drivers/tty/serial/imx.c +5
-0+ imx_uart_ports[sport->port.line] = sport; ret =uart_add_one_port (&imx_uart_uart_driver, &sport->port); +if (ret) + imx_uart_ports[sport->port.line] =NULL ; +mutex_unlock (&imx_uart_ports_lock); err_clk:clk_disable_unprepare (sport->clk_ipg);@@ -2647,8 +2660,12 @@ static int imx_uart_probe(struct platform_device *pdev)static void imx_uart_remove (struct platform_device *pdev) {struct imx_port *sport =platform_get_drvdata (pdev); +unsigned int line = sport->port.line;
Why are you reading this outside of the lock?
drivers/tty/serial/imx.c static int imx_uart_probe(struct platform_device *pdev) · line 2664
Quoted 2 lines
drivers/tty/serial/imx.c +1
-0+mutex_lock (&imx_uart_ports_lock);
guard()?
thanks,
greg k-h
Re: [PATCH v2 4/4] serial: imx: serialize imx_uart_ports[] lifetime
Quoted 5 lines · Greg Kroah-Hartman
Review
Quoted 2 lines
(quoted diff) +1
-0+ mutex_lock(&imx_uart_ports_lock);
guard()?
I'll use guards for v3.
Quoted 4 lines
drivers/tty/serial/imx.c static int imx_uart_probe(struct platform_device *pdev) · line 2663
Quoted 1 line
drivers/tty/serial/imx.c +1
-0+unsigned int line = sport->port.line;Why are you reading this outside of the lock?
Good question. The local variable is unnecessary. I'll remove it.
Thanks,
Karl
Re: [PATCH v2 4/4] serial: imx: serialize imx_uart_ports[] lifetime
In reply to Karl MehltretterQuoted 74 lines · Karl Mehltretter
[You don't often get email from [email protected]. Learn why this is important at https://aka.ms/LearnAboutSenderIdentification ]
imx_uart_probe()publishes the port in imx_uart_ports[] beforeuart_add_one_port(), because console setup during that call uses the table. The entry is not cleared if adding the port fails or afterimx_uart_remove()removes it.The port is devm-allocated, so a failed probe or unbind leaves the table pointing at freed memory. A later registration of the shared console can then dereference the stale entry. Reproduced on QEMU's mcimx6ul-evk by unbinding a sibling UART, unbinding the console UART and rebinding the sibling:
BUG: KASAN: slab-use-after-free in imx_uart_console_setup+0xd0/0x3d8The entry must remain valid until
uart_remove_one_port()unregisters the console. Clearing it afterward without serialization still races a sibling probe: the sibling can register the shared console using the dying entry before it is cleared. The next console write then dereferences NULL.Use a driver-wide mutex to serialize table publication, port addition and rollback with port removal and table clearing. Console callbacks remain lockless because
uart_add_one_port()may invoke setup while probe holds the mutex.The probe-failure path also relies on "serial: core: do fallible allocations before the console can be registered", which moves the
uport->nameanduport->tty_groupsallocations before console registration. Both changes should be backported together.Fixes dbff4e9ea2e8 ("IMX UART: remove statically initialized tables")Fixes 9f322ad064f9 ("imx: serial: handle initialisation failure correctly")Reported-by Sashiko <[email protected]>Assisted-by Claude:claude-fable-5Signed-off-by Karl Mehltretter <[email protected]>--- drivers/tty/serial/imx.c | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-)drivers/tty/serial/imx.c +10
-0@@ -22,6 +22,7 @@#include <linux/clk.h> #include <linux/delay.h> #include <linux/ktime.h> +#include <linux/mutex.h> #include <linux/pinctrl/consumer.h> #include <linux/rational.h> #include <linux/slab.h> @@ -2080,6 +2081,15 @@ static const struct uart_ops imx_uart_pops = {static struct imx_port *imx_uart_ports[UART_NR ]; +/* +* Store the port in imx_uart_ports[] before uart_add_one_port() and clear +* it only after uart_remove_one_port() returns. Console callbacks in both +* calls use the table, so this mutex serializes these sequences between +* sibling ports. Callbacks must not take it because uart_add_one_port() +* may invoke setup while it is held. +*/ +static DEFINE_MUTEX (imx_uart_ports_lock); +#if IS_ENABLED (CONFIG_SERIAL_IMX_CONSOLE )static void imx_uart_console_putchar (struct uart_port *port,unsigned char ch) {@@ -2632,11 +2642,14 @@ static int imx_uart_probe(struct platform_device *pdev) } }
drivers/tty/serial/imx.c static int imx_uart_probe(struct platform_device *pdev) · line 2652
Quoted 10 lines
drivers/tty/serial/imx.c +5
-2- imx_uart_ports[sport->port.line] = sport; -platform_set_drvdata (pdev, sport); +mutex_lock (&imx_uart_ports_lock); + imx_uart_ports[sport->port.line] = sport; ret =uart_add_one_port (&imx_uart_uart_driver, &sport->port); +if (ret) + imx_uart_ports[sport->port.line] =NULL ; +mutex_unlock (&imx_uart_ports_lock);
ret = uart_add_one_port(&imx_uart_uart_driver, &sport->port); if (ret)
goto err_clk;
imx_uart_ports[sport->port.line] = sport;
return 0
and at imx_uart_remove()
imx_uart_remove()
{
imx_uart_ports[line] = NULL;
uart_remove_one_port(&imx_uart_uart_driver, &sport->port);
}Is above sequence to avoid use mutex?
Frank
Quoted 19 lines
drivers/tty/serial/imx.c +4
-1err_clk:clk_disable_unprepare (sport->clk_ipg);@@ -2647,8 +2660,12 @@ static int imx_uart_probe(struct platform_device *pdev)static void imx_uart_remove (struct platform_device *pdev) {struct imx_port *sport =platform_get_drvdata (pdev); +unsigned int line = sport->port.line; +mutex_lock (&imx_uart_ports_lock);uart_remove_one_port (&imx_uart_uart_driver, &sport->port); + imx_uart_ports[line] =NULL ; +mutex_unlock (&imx_uart_ports_lock); }static void imx_uart_restore_context (struct imx_port *sport) --2.53.0
Re: [PATCH v2 4/4] serial: imx: serialize imx_uart_ports[] lifetime
Quoted 8 lines · Frank Li
imx_uart_remove(){ imx_uart_ports[line] = NULL; uart_remove_one_port(&imx_uart_uart_driver, &sport->port); }Is above sequence to avoid use mutex?
I now tried this, but it doesn't work as-is:
uart_add_one_port() may call imx_uart_console_setup(), so the entry must be present before the call.
uart_remove_one_port() unregisters the console. Clearing the entry first causes its callbacks to dereference NULL.
The mutex protects those sequences against sibling probes.
Thanks,
Karl
Re: [PATCH v2 4/4] serial: imx: serialize imx_uart_ports[] lifetime
Quoted 12 lines · Karl Mehltretter
Quoted 8 lines · Frank Li
imx_uart_remove(){ imx_uart_ports[line] = NULL; uart_remove_one_port(&imx_uart_uart_driver, &sport->port); }Is above sequence to avoid use mutex?
I now tried this, but it doesn't work as-is:
Quoted 7 lines
uart_add_one_port()may callimx_uart_console_setup(), so the entry must be present before the call.
uart_remove_one_port()unregisters the console. Clearing the entry first causes its callbacks to dereference NULL.The mutex protects those sequences against sibling probes.
Okay
Frank
Quoted 3 lines
Thanks,
Karl