Linux kernel mirror (for testing) git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
kernel os linux

spi: fix use-after-free of the add_lock mutex

Commit 6098475d4cb4 ("spi: Fix deadlock when adding SPI controllers on
SPI buses") introduced a per-controller mutex. But mutex_unlock() of
said lock is called after the controller is already freed:

spi_unregister_controller(ctlr)
-> put_device(&ctlr->dev)
-> spi_controller_release(dev)
-> mutex_unlock(&ctrl->add_lock)

Move the put_device() after the mutex_unlock().

Fixes: 6098475d4cb4 ("spi: Fix deadlock when adding SPI controllers on SPI buses")
Signed-off-by: Michael Walle <michael@walle.cc>
Reviewed-by: Uwe Kleine-König <u.kleine-koenig@pengutronix.de>
Reviewed-by: Lukas Wunner <lukas@wunner.de>
Cc: stable@vger.kernel.org # v5.15
Link: https://lore.kernel.org/r/20211111083713.3335171-1-michael@walle.cc
Signed-off-by: Mark Brown <broonie@kernel.org>

authored by

Michael Walle and committed by
Mark Brown
6c53b45c 6532582c

+6 -6
+6 -6
drivers/spi/spi.c
··· 3058 3058 3059 3059 device_del(&ctlr->dev); 3060 3060 3061 - /* Release the last reference on the controller if its driver 3062 - * has not yet been converted to devm_spi_alloc_master/slave(). 3063 - */ 3064 - if (!ctlr->devm_allocated) 3065 - put_device(&ctlr->dev); 3066 - 3067 3061 /* free bus id */ 3068 3062 mutex_lock(&board_lock); 3069 3063 if (found == ctlr) ··· 3066 3072 3067 3073 if (IS_ENABLED(CONFIG_SPI_DYNAMIC)) 3068 3074 mutex_unlock(&ctlr->add_lock); 3075 + 3076 + /* Release the last reference on the controller if its driver 3077 + * has not yet been converted to devm_spi_alloc_master/slave(). 3078 + */ 3079 + if (!ctlr->devm_allocated) 3080 + put_device(&ctlr->dev); 3069 3081 } 3070 3082 EXPORT_SYMBOL_GPL(spi_unregister_controller); 3071 3083