Re: [PATCH v2 3/4] tty: don't oops in tty_unregister_device() when no cdev is registered

Greg Kroah-Hartman <[email protected]> Thu, 30 Jul 2026 16:29:57 +0200
Newsgroups gmane.linux.kernel.stable,gmane.linux.serial,gmane.linux.kernel
Message-ID <2026073057-moustache-unfixable-5ab1@gregkh>
On Mon, Jul 20, 2026 at 12:10:13AM +0200, Karl Mehltretter wrote:
> serial_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.

Note, LLMs love to write a lot.  Please always rewrite the changelog
text to be sane and concise.

> 
> Fixes: c1a752ba2d6b ("tty: don't leak cdev in tty_cdev_add()")
> Fixes: 8cde11b2baa1 ("tty/serdev: add serdev registration interface")
> Cc: [email protected]
> Assisted-by: Claude:claude-fable-5
> Signed-off-by: Karl Mehltretter <[email protected]>
> ---
>  drivers/tty/tty_io.c | 6 ++++--
>  1 file changed, 4 insertions(+), 2 deletions(-)
> 
> diff --git a/drivers/tty/tty_io.c b/drivers/tty/tty_io.c
> index 6b283fd03ff8..4889076b975f 100644
> --- a/drivers/tty/tty_io.c
> +++ b/drivers/tty/tty_io.c
> @@ -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]) {

This looks to be doing 2 different things in one patch, or am I
confused?

thanks,

greg k-h