Re: [PATCH] media: vim2m: fix reference leak on failed device registration
From: Laurent Pinchart
Date: Thu Apr 16 2026 - 05:50:02 EST
On Wed, Apr 15, 2026 at 11:14:49PM +0800, Guangshuo Li wrote:
> When platform_device_register() fails in vim2m_init(), the embedded
> struct device in vim2m_pdev has already been initialized by
> device_initialize(), but the failure path returns the error without
> dropping the device reference for the current platform device:
>
> vim2m_init()
> -> platform_device_register(&vim2m_pdev)
> -> device_initialize(&vim2m_pdev.dev)
> -> setup_pdev_dma_masks(&vim2m_pdev)
> -> platform_device_add(&vim2m_pdev)
>
> This leads to a reference leak when platform_device_register() fails.
> Fix this by calling platform_device_put() before returning the error.
Functions that don't clean after themselves on failure are not a very
good practice. It indeed seems that platform_device_register() will
leave a dangling kref. Most callers don't seem to be aware of this
though, even platform_add_devices() doesn't call platform_device_put() !
This makes me think that this patch just works around the problem. A
better solution is needed. Have you investigated if
platform_device_register() can drop the reference on failure ? What
problems would that cause ?
> The issue was identified by a static analysis tool I developed and
> confirmed by manual review.
>
> Fixes: 1f923a42033ad ("[media] mem2mem_testdev: rename to vim2m")
Quote unlikely.
> Cc: stable@xxxxxxxxxxxxxxx
> Signed-off-by: Guangshuo Li <lgs201920130244@xxxxxxxxx>
> ---
> drivers/media/test-drivers/vim2m.c | 4 +++-
> 1 file changed, 3 insertions(+), 1 deletion(-)
>
> diff --git a/drivers/media/test-drivers/vim2m.c b/drivers/media/test-drivers/vim2m.c
> index bb2dd11eef0e..80dc7edcbb5e 100644
> --- a/drivers/media/test-drivers/vim2m.c
> +++ b/drivers/media/test-drivers/vim2m.c
> @@ -1601,8 +1601,10 @@ static int __init vim2m_init(void)
> int ret;
>
> ret = platform_device_register(&vim2m_pdev);
> - if (ret)
> + if (ret) {
> + platform_device_put(&vim2m_pdev);
> return ret;
> + }
>
> ret = platform_driver_register(&vim2m_pdrv);
> if (ret)
--
Regards,
Laurent Pinchart