7.2.5-rc1 review
Greg Kroah-Hartman
maintainerPATCH 264/556 iio: buffer: Fix potential use-after-free in anonymous buffer release
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Lars-Peter Clausen <[email protected]>
commit 6288b593e76eb10329326f2cd51e32557203b9e5 upstream.
An anonymous buffer handle holds a reference to the underlying IIO device. The reference is dropped in the buffer handle's release function. If the device has been removed, either through unbind or hot-unplug, the buffer handle might hold the last reference.
The release function takes the mutex for the buffer using a guard, which means the unlock happens after all the code in the function, including iio_device_put(). If the anonymous buffer holds the last reference this might free both the IIO device and the buffer, which contains the mutex, leading to use-after-free when the mutex is unlocked.
Fix this by using a scoped guard just around the buffer dmabuf list access, making sure the mutex is unlocked before releasing the IIO device.
Version 10 of the patch that introduced this issue used this exact scheme of first unlocking and then dropping the reference [1]. During review it was suggested to use a guard instead, and version 11 made that change [2].
--- drivers/iio/industrialio-buffer.c | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-)
drivers/iio/industrialio-buffer.c +10 -6
@@ -1619,12 +1619,16 @@ static int iio_buffer_chrdev_release(strwake_up (&buffer->pollq); -guard (mutex)(&buffer->dmabufs_mutex); - -/* Close all attached DMABUFs */ -list_for_each_entry_safe (priv, tmp, &buffer->dmabufs, entry) { -list_del_init (&priv->entry); -iio_buffer_dmabuf_put (priv->attach); +/* +* The mutex must be unlocked before iio_device_put(), which might drop the +* last reference and free the buffer. +*/ + scoped_guard(mutex, &buffer->dmabufs_mutex) { +/* Close all attached DMABUFs */ +list_for_each_entry_safe (priv, tmp, &buffer->dmabufs, entry) { +list_del_init (&priv->entry); +iio_buffer_dmabuf_put (priv->attach); + } }kfree (ib);
Greg Kroah-Hartman
maintainerPATCH 265/556 iio: buffer: Make IIO DMA fence release RCU-safe
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Lars-Peter Clausen <[email protected]>
commit 8662e56c31cf23b61ca3d11b516efb94c35b8026 upstream.
The dma_fence documentation states that if a custom release implementation is provided, the dma_fence object must be freed in an RCU-safe way. The current iio_dma_fence implementation uses kfree(), which might result in a use-after-free.
Remove the custom release implementation. This makes the DMA fence core fall back to dma_fence_free(), which calls kfree_rcu() on the fence. This requires that the fence be the first member of struct iio_dma_fence.
Using the default release method for extended DMA fence structures is a common pattern.
--- drivers/iio/industrialio-buffer.c | 13 ++++--------- 1 file changed, 4 insertions(+), 9 deletions(-)
drivers/iio/industrialio-buffer.c +4 -9
@@ -57,6 +57,10 @@ struct iio_dmabuf_priv { };struct iio_dma_fence { +/* +* Must remain the first member so the default release callback can pass +* the fence directly to dma_fence_free(). +*/ struct dma_fence base;struct iio_dmabuf_priv *priv;struct work_struct work;
@@ -1831,18 +1835,9 @@ iio_buffer_dma_fence_get_driver_name(strreturn "iio" ; } -static void iio_buffer_dma_fence_release (struct dma_fence *fence) -{ -struct iio_dma_fence *iio_fence = - container_of(fence, struct iio_dma_fence, base); - -kfree (iio_fence); -} -static const struct dma_fence_ops iio_buffer_dma_fence_ops = { .get_driver_name = iio_buffer_dma_fence_get_driver_name, .get_timeline_name = iio_buffer_dma_fence_get_driver_name, - .release = iio_buffer_dma_fence_release, }; static int iio_buffer_enqueue_dmabuf(struct iio_dev_buffer_pair *ib,
Greg Kroah-Hartman
maintainerPATCH 266/556 iio: buffer: Tie IIO dma fence lock lifetime to the fence
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Lars-Peter Clausen <[email protected]>
commit f25ec4627d935dedfb5fe83bd2c2678cdcc19611 upstream.
The iio_dma_fence implementation currently uses a lock embedded in the iio_dmabuf_priv. But the iio_dma_fence can outlive the iio_dmabuf_priv, which can cause a use-after-free.
Tie the lifetime of the lock to the lifetime of the fence by embedding them in the same struct.
We can't just hold a reference to the iio_dmabuf_priv from the iio_dma_fence since iio_buffer_dmabuf_release() might sleep and the fence release callback is not allowed to sleep.
Note that the dma_fence framework now has an internal lock that gets used when the passing NULL for lock in dma_fence_init(), but in order to allow this patch to be backportable use an external lock.
--- drivers/iio/industrialio-buffer.c | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-)
drivers/iio/industrialio-buffer.c +4 -5
@@ -47,9 +47,6 @@ struct iio_dmabuf_priv {u64 context; -/* Spinlock used for locking the dma_fence */ -spinlock_t lock; -struct dma_buf_attachment *attach;struct sg_table *sgt;enum dma_data_direction dir;
@@ -62,6 +59,7 @@ struct iio_dma_fence {* the fence directly to dma_fence_free(). */ struct dma_fence base; +spinlock_t lock;/* protects base */ struct iio_dmabuf_priv *priv;struct work_struct work; };
@@ -1710,7 +1708,6 @@ static int iio_buffer_attach_dmabuf(struif (!priv)return -ENOMEM ; -spin_lock_init (&priv->lock); priv->context =dma_fence_context_alloc (1 ); dmabuf =dma_buf_get (fd);
@@ -1891,6 +1888,8 @@ static int iio_buffer_enqueue_dmabuf(str goto err_attachment_put; } +spin_lock_init (&fence->lock); + fence->priv = priv; seqno =atomic_add_return (1 , &priv->seqno);
@@ -1901,7 +1900,7 @@ static int iio_buffer_enqueue_dmabuf(str* the dma_fence. */ dma_fence_init (&fence->base, &iio_buffer_dma_fence_ops, - &priv->lock, priv->context, seqno); + &fence->lock, priv->context, seqno); ret =iio_dma_resv_lock (dmabuf, nonblock);if (ret)
Greg Kroah-Hartman
maintainerPATCH 267/556 iio: chemical: atlas-sensor: fix PM reference leak in buffer postenable
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Moksh Panicker <[email protected]>
commit bcd3f72e26314edfce7eaf8d7160b3119c7b7fed upstream.
atlas_buffer_postenable() acquires a runtime PM reference with pm_runtime_resume_and_get() but returns the result of atlas_set_interrupt() directly. If atlas_set_interrupt() fails, the runtime PM reference is leaked and the device can never autosuspend.
Add pm_runtime_put_autosuspend() on the error path to balance the reference.
--- drivers/iio/chemical/atlas-sensor.c | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-)
drivers/iio/chemical/atlas-sensor.c +5 -1
@@ -412,7 +412,11 @@ static int atlas_buffer_postenable(strucif (ret)return ret; -return atlas_set_interrupt (data, true); + ret =atlas_set_interrupt (data, true); +if (ret) +pm_runtime_put_autosuspend (&data->client->dev); + +return ret; }static int atlas_buffer_predisable (struct iio_dev *indio_dev)
Greg Kroah-Hartman
maintainerPATCH 268/556 iio: chemical: atlas-sensor: use iio_trigger_poll_nested() to fix remove UAF
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Fan Wu <[email protected]>
commit be61c8c6252671ecf1fee0ad90f87669e0be1e20 upstream.
The atlas driver requests its hardware data-ready IRQ with devm_request_threaded_irq(); its threaded handler queues an irq_work, atlas_work_handler(), that calls iio_trigger_poll(data->trig).
The IRQ is devm-managed, so free_irq() runs from the devres unwind after atlas_remove() returns without flushing that irq_work. Once a buffer is enabled, conversion-complete IRQs keep firing and queueing it; a pending irq_work can therefore run after the unwind has freed atlas_data/indio_dev and the trigger, when atlas_work_handler() derives the atlas_data pointer via container_of() and dereferences data->trig, a use-after-free.
Call iio_trigger_poll_nested() directly from the threaded handler instead of bouncing through irq_work. free_irq() then drains the threaded handler, closing the window; other iio drivers with a threaded data-ready IRQ do the same (e.g. bmi270).
This issue was found by an in-house static analysis tool.
--- drivers/iio/chemical/atlas-sensor.c | 13 +------------ 1 file changed, 1 insertion(+), 12 deletions(-)
drivers/iio/chemical/atlas-sensor.c +1 -12
@@ -13,7 +13,6 @@#include <linux/mutex.h> #include <linux/err.h> #include <linux/irq.h> -#include <linux/irq_work.h> #include <linux/i2c.h> #include <linux/regmap.h> #include <linux/iio/iio.h>
@@ -87,7 +86,6 @@ struct atlas_data {struct iio_trigger *trig;const struct atlas_device *chip;struct regmap *regmap; -struct irq_work work;unsigned int interrupt_enabled;/* 96-bit data + 32-bit pad + 64-bit timestamp */ __be32 buffer[6 ]__aligned(8) ;
@@ -440,13 +438,6 @@ static const struct iio_buffer_setup_ops .predisable = atlas_buffer_predisable, }; -static void atlas_work_handler (struct irq_work *work) -{ - struct atlas_data *data = container_of(work, struct atlas_data, work); - -iio_trigger_poll (data->trig); -} -static irqreturn_t atlas_trigger_handler (int irq,void *private) {struct iio_poll_func *pf = private;
@@ -473,7 +464,7 @@ static irqreturn_t atlas_interrupt_handlstruct iio_dev *indio_dev = private;struct atlas_data *data =iio_priv (indio_dev); -irq_work_queue (&data->work); +iio_trigger_poll_nested (data->trig);return IRQ_HANDLED ; }
@@ -669,8 +660,6 @@ static int atlas_probe(struct i2c_client goto unregister_trigger; } -init_irq_work (&data->work, atlas_work_handler); -if (client->irq >0 ) {/* interrupt pin toggles on new conversion */ ret = devm_request_threaded_irq(&client->dev, client->irq,
Greg Kroah-Hartman
maintainerPATCH 269/556 iio: chemical: sgp30: Handle IAQ thread creation failure
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Linmao Li <[email protected]>
commit 1135d6875d2dbda3f6ec718f3421a6ce4378bd63 upstream.
kthread_run() can fail and return an error pointer, but sgp_probe() stores it and returns success, so the device is registered without its IAQ thread and sgp_remove() later passes the error pointer to kthread_stop(). Return the error from probe instead.
--- drivers/iio/chemical/sgp30.c | 3 +++ 1 file changed, 3 insertions(+)
drivers/iio/chemical/sgp30.c +3 -0
@@ -548,6 +548,9 @@ static int sgp_probe(struct i2c_client * data->iaq_thread =kthread_run (sgp_iaq_threadfn, data,"%s-iaq" , data->client->name); +if (IS_ERR (data->iaq_thread)) +return dev_err_probe (dev,PTR_ERR (data->iaq_thread), +"failed to start IAQ thread\n" );return 0 ; }
Greg Kroah-Hartman
maintainerPATCH 270/556 iio: dac: ad3552r-hs: fix scnprintf() buffer bound in data source show
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Babanpreet Singh <[email protected]>
commit f2c5c76306fadb834dd5ea76cab0b7cd447e6035 upstream.
ad3552r_hs_show_data_source_avail() formats the available data source names into a 128-byte stack buffer, but bounds each scnprintf() with PAGE_SIZE instead of the buffer size, so the bound does not protect the destination at all.
This cannot overflow today - dbgfs_attr_source[] has two entries, "normal" and "ramp-16bit", 18 bytes formatted - but the bound stops protecting the stack the day the table grows. Use sizeof(buf) so the bound matches the destination.
Found by smatch:
drivers/iio/dac/ad3552r-hs.c:593 ad3552r_hs_show_data_source_avail()
error: scnprintf() 'buf[len]' too small (128 vs 4096)
--- drivers/iio/dac/ad3552r-hs.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/iio/dac/ad3552r-hs.c +1 -1
@@ -590,7 +590,7 @@ static ssize_t ad3552r_hs_show_data_sourint i;for (i =0 ; i <ARRAY_SIZE (dbgfs_attr_source); i++) { - len +=scnprintf (buf + len,PAGE_SIZE - len,"%s " , + len +=scnprintf (buf + len,sizeof (buf) - len,"%s " , dbgfs_attr_source[i]); } buf[len -1 ] ='\n' ;
Greg Kroah-Hartman
maintainerPATCH 271/556 iio: dac: ad5446: fix OF module device table
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Can Peng <[email protected]>
commit a3c03cf36a083893dedad928915471dc8c10692e upstream.
The ad5446 I2C driver exports its OF match table with MODULE_DEVICE_TABLE(OF, ...).
The device table type is used by modpost when generating module aliases, and scripts/mod/file2alias.c matches the lowercase "of" type. Using "OF" prevents the OF table from being recognized, so no OF module alias is generated for the I2C driver.
Use the lowercase "of" type so OF-based module autoloading works.
--- drivers/iio/dac/ad5446-i2c.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/iio/dac/ad5446-i2c.c +1 -1
@@ -83,7 +83,7 @@ static const struct of_device_id ad5446_ { .compatible = "adi,ad5622", .data = &ad5622_chip_info }, { } }; -MODULE_DEVICE_TABLE (OF , ad5446_i2c_of_ids); +MODULE_DEVICE_TABLE (of, ad5446_i2c_of_ids);static struct i2c_driver ad5446_i2c_driver = { .driver = {
Greg Kroah-Hartman
maintainerPATCH 272/556 iio: dac: m62332: Fix regulator reference count imbalance
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Erick Henrique <[email protected]>
commit a130404ce0b69ca1438126bd81c1985d3b4d2e6f upstream.
m62332_set_value() enables the Vcc regulator on every write of a non-zero value and disables it on every write of zero, without tracking the channel's current state. Because the regulator is reference counted, changing a channel directly from one non-zero value to another enables it more than once, while a later write of zero disables it only once. The reference count never returns to zero and the regulator is left enabled indefinitely.
Only enable the regulator on the transition from zero to non-zero, and only disable it on the transition from non-zero to zero, using the previously stored channel value to detect the edge. Balance the regulator on the I2C error path so the reference count stays consistent if the write fails.
--- drivers/iio/dac/m62332.c | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-)
drivers/iio/dac/m62332.c +12 -5
@@ -32,6 +32,7 @@ static int m62332_set_value(struct iio_d {struct m62332_data *data =iio_priv (indio_dev);struct i2c_client *client = data->client; +bool enabling, disabling;u8 outbuf[2 ];int res;
@@ -43,7 +44,10 @@ static int m62332_set_value(struct iio_dmutex_lock (&data->mutex); -if (val) { + enabling = val && !data->raw[channel]; + disabling = !val && data->raw[channel]; + +if (enabling) { res =regulator_enable (data->vcc);if (res) goto out;
@@ -52,14 +56,17 @@ static int m62332_set_value(struct iio_d res =i2c_master_send (client, outbuf,ARRAY_SIZE (outbuf));if (res >=0 && res !=ARRAY_SIZE (outbuf)) res = -EIO ; -if (res <0 ) +if (res <0 ) { +if (enabling) +regulator_disable (data->vcc); goto out; + } - data->raw[channel] = val; - -if (!val) +if (disabling)regulator_disable (data->vcc); + data->raw[channel] = val; +mutex_unlock (&data->mutex);return 0 ;
Greg Kroah-Hartman
maintainerPATCH 273/556 iio: dac: mcp47feb02: add missing select REGMAP_I2C to Kconfig
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Joshua Crofts <[email protected]>
commit 739aac87638f06fcf851df41ecd52d30ab7b0570 upstream.
The Kconfig entry for the MCP47FEB02 is missing a 'select REGMAP_I2C', causing build failures.
--- drivers/iio/dac/Kconfig | 1 + 1 file changed, 1 insertion(+)
drivers/iio/dac/Kconfig +1 -0
@@ -552,6 +552,7 @@ config MCP4728 config MCP47FEB02 tristate "MCP47F(E/V)B01/02/04/08/11/12/14/18/21/22/24/28 DAC driver" depends on I2C + select REGMAP_I2C help Say yes here if you want to build the driver for the Microchip: - 8-bit DAC:
Greg Kroah-Hartman
maintainerPATCH 274/556 iio: gyro: mpu3050: fix sign of raw angular velocity readings
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Cong Nguyen <[email protected]>
commit 06fab97602fe400bea843176f485bbac07a668e2 upstream.
The MPU-3050 gyroscope output registers hold 16-bit two's complement values; the angular velocity channels are declared with .sign = 's'. When mpu3050_read_raw() handles IIO_CHAN_INFO_RAW it reads the register via a big-endian regmap_bulk_read() and assigns it with:
*val = be16_to_cpu(raw_val);
be16_to_cpu() yields an unsigned 16-bit quantity, so negative rates (bit 15 set) are reported to userspace as large positive integers (e.g. -1 becomes 65535) instead of the correct negative value.
Cast to s16 before the assignment, matching the temperature channel a few lines above which already handles the sign correctly.
--- drivers/iio/gyro/mpu3050-core.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/iio/gyro/mpu3050-core.c +1 -1
@@ -356,7 +356,7 @@ static int mpu3050_read_raw(struct iio_d goto out_read_raw_unlock; } - *val =be16_to_cpu (raw_val); + *val = (s16 )be16_to_cpu (raw_val); ret =IIO_VAL_INT ; goto out_read_raw_unlock;
Greg Kroah-Hartman
maintainerPATCH 275/556 iio: imu: st_lsm6dsx: Update enable mask when using sensor fusion
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Francesco Lavra <[email protected]>
commit 4a56c646e1bd4f22a2dcd65ef3723af957c651a9 upstream.
The enable_mask struct member keeps track of which sensors are enabled in the IMU. When enabling and disabling the sensor fusion functionality, the driver does not properly update this struct member. This prevents a correct calculation of the number of samples that should be read from the hardware FIFO; as a result, reads from the FIFO can be unnecessarily split into multiple transactions, some of which can read past the FIFO length.
--- drivers/iio/imu/st_lsm6dsx/st_lsm6dsx_fusion.c | 5 +++++ 1 file changed, 5 insertions(+)
drivers/iio/imu/st_lsm6dsx/st_lsm6dsx_fusion.c +5 -0
@@ -112,6 +112,11 @@ int st_lsm6dsx_fusion_set_enable(structreturn err; } +if (enable) + hw->enable_mask |=BIT (ST_LSM6DSX_ID_FUSION ); +else + hw->enable_mask &= ~BIT (ST_LSM6DSX_ID_FUSION ); +return st_lsm6dsx_fusion_page_disable (hw); }
Greg Kroah-Hartman
maintainerPATCH 276/556 iio: light: apds9306: fix PM reference leak in apds9306_read_data()
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Moksh Panicker <[email protected]>
commit d378fceaafd79e0dc59d3546bda251a3058062c0 upstream.
apds9306_read_data() calls pm_runtime_resume_and_get() but several error paths return directly without calling pm_runtime_put_autosuspend(), leaking the runtime PM reference and preventing the device from autosuspending.
Use PM_RUNTIME_ACQUIRE_AUTOSUSPEND() and PM_RUNTIME_ACQUIRE_ERR() to automatically handle runtime PM reference release on all return paths.
--- drivers/iio/light/apds9306.c | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-)
drivers/iio/light/apds9306.c +3 -5
@@ -469,9 +469,9 @@ static int apds9306_read_data(struct apdint status =0 ;u8 buff[3 ]; - ret =pm_runtime_resume_and_get (data->dev); -if (ret) -return ret; +PM_RUNTIME_ACQUIRE_AUTOSUSPEND (data->dev, pm); +if (PM_RUNTIME_ACQUIRE_ERR (&pm)) +return PM_RUNTIME_ACQUIRE_ERR (&pm); ret =regmap_field_read (rf->intg_time, &intg_time_idx);if (ret)
@@ -535,8 +535,6 @@ static int apds9306_read_data(struct apd *val =get_unaligned_le24 (&buff); -pm_runtime_put_autosuspend (data->dev); -return 0 ; }
Greg Kroah-Hartman
maintainerPATCH 277/556 iio: light: cm32181: return zero after writing calibscale
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Giorgi Tchankvetadze <[email protected]>
commit 8756acd30919a3e9f547ea4a1d4b7f7895f4d340 upstream.
The write_raw callback is documented to return 0 on success or a negative error code. However, the IIO_CHAN_INFO_CALIBSCALE case returns 'val' (the user-supplied value) instead of 0.
Fix it by returning 0 on success, matching the behavior of other calibscale implementations in the subsystem.
--- drivers/iio/light/cm32181.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/iio/light/cm32181.c +1 -1
@@ -368,7 +368,7 @@ static int cm32181_write_raw(struct iio_switch (mask) {case IIO_CHAN_INFO_CALIBSCALE : cm32181->calibscale = val; -return val; +return 0 ;case IIO_CHAN_INFO_INT_TIME : ret =cm32181_write_als_it (cm32181, val2);return ret;
Greg Kroah-Hartman
maintainerPATCH 278/556 iio: light: gp2ap002: Disable regulators on resume failure
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Laxman Acharya Padhya <[email protected]>
commit a41000ba3a230bed1e422f283486ff8f77fe0d30 upstream.
If enabling VIO fails after VDD has been enabled, runtime resume returns without disabling VDD. Likewise, if device reinitialization fails, both supplies remain enabled. The runtime PM core keeps the device suspended when its resume callback fails, so the supplies must be restored to the suspended state.
Disable the supplies enabled by the callback before returning an error.
--- drivers/iio/light/gp2ap002.c | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-)
drivers/iio/light/gp2ap002.c +8 -2
@@ -669,7 +669,7 @@ static int gp2ap002_runtime_resume(struc ret =regulator_enable (gp2ap002->vio);if (ret) {dev_err (dev,"failed to enable VIO regulator in resume path\n" ); -return ret; + goto out_disable_vdd; }msleep (20 );
@@ -677,13 +677,19 @@ static int gp2ap002_runtime_resume(struc ret =gp2ap002_init (gp2ap002);if (ret) {dev_err (dev,"re-initialization failed\n" ); -return ret; + goto out_disable_vio; }/* Re-activate the IRQ */ enable_irq (gp2ap002->irq);return 0 ; + +out_disable_vio: +regulator_disable (gp2ap002->vio); +out_disable_vdd: +regulator_disable (gp2ap002->vdd); +return ret; } static DEFINE_RUNTIME_DEV_PM_OPS(gp2ap002_dev_pm_ops, gp2ap002_runtime_suspend,
Greg Kroah-Hartman
maintainerPATCH 279/556 iio: light: ltrf216a: fix runtime PM reference leak in error path
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Vidhu Sarwal <[email protected]>
commit c132aef0e757a39036b1d40faf0569f2e343b13e upstream.
ltrf216a_get_lux() acquires a runtime PM reference by calling ltrf216a_set_power_state(data, true). However, if ltrf216a_read_data() fails, the function returns immediately without dropping the reference.
This leaves the runtime PM usage count unbalanced, preventing the device from autosuspending after a failed read.
Fix this by releasing the runtime PM reference before returning from the error path.
--- drivers/iio/light/ltrf216a.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-)
drivers/iio/light/ltrf216a.c +1 -2
@@ -247,11 +247,10 @@ static int ltrf216a_get_lux(struct ltrf2return ret; greendata =ltrf216a_read_data (data,LTRF216A_ALS_DATA_0 ); +ltrf216a_set_power_state (data, false);if (greendata <0 )return greendata; -ltrf216a_set_power_state (data, false); - lux = greendata * data->info->lux_multiplier *LTRF216A_WIN_FAC ;return lux;
Greg Kroah-Hartman
maintainerPATCH 280/556 iio: pressure: dps310: fix NULL pointer dereference on ACPI probe
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Rupesh Majhi <[email protected]>
commit 26e9213898fc949923188ef0aeea31fc87708836 upstream.
When the device is enumerated through its ACPI HID (IFX3100), i2c_client_get_device_id() returns NULL: the ACPI-derived client name does not match the driver's i2c_device_id table. dps310_probe() then dereferences that NULL pointer in "iio->name = id->name" and crashes the kernel during probe.
The IIO device name is always "dps310", so set it directly and drop the now-unused device-id lookup.
--- drivers/iio/pressure/dps310.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-)
drivers/iio/pressure/dps310.c +1 -2
@@ -845,7 +845,6 @@ static const struct iio_info dps310_infostatic int dps310_probe (struct i2c_client *client) { -const struct i2c_device_id *id =i2c_client_get_device_id (client);struct dps310_data *data;struct iio_dev *iio;int rc;
@@ -858,7 +857,7 @@ static int dps310_probe(struct i2c_clien data->client = client;mutex_init (&data->lock); - iio->name = id->name; + iio->name =DPS310_DEV_NAME ; iio->channels = dps310_channels; iio->num_channels =ARRAY_SIZE (dps310_channels); iio->info = &dps310_info;
Greg Kroah-Hartman
maintainerPATCH 281/556 iio: pressure: mpl115: Fix runtime PM cleanup
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Can Peng <[email protected]>
commit 0b5e142ced4bcf20532da051934bd694d1bbd470 upstream.
mpl115_probe() enables runtime PM when a shutdown GPIO is present and then returns the result of devm_iio_device_register(). If registration fails, runtime PM remains enabled and autosuspend remains selected.
The same unmanaged runtime PM state is also left behind on driver unbind, as the IIO device registration is managed but the runtime PM setup is not.
Use devm_pm_runtime_enable() so runtime PM is disabled automatically on probe failure and driver unbind, and check pm_runtime_set_active() so setup errors are reported.
Set the autosuspend parameters before enabling runtime PM. Once probe has completed, the driver core queues an idle request for the device, so an explicit pm_runtime_get_noresume()/pm_runtime_put() pair is not needed to start autosuspend.
--- drivers/iio/pressure/mpl115.c | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-)
drivers/iio/pressure/mpl115.c +7 -4
@@ -203,9 +203,9 @@ int mpl115_probe(struct device *dev, conif (data->shutdown) {/* Enable runtime PM */ -pm_runtime_get_noresume (dev); -pm_runtime_set_active (dev); -pm_runtime_enable (dev); + ret =pm_runtime_set_active (dev); +if (ret) +return ret;/* * As the device takes 3 ms to come up with a fresh
@@ -215,7 +215,10 @@ int mpl115_probe(struct device *dev, con*/ pm_runtime_set_autosuspend_delay (dev,2000 );pm_runtime_use_autosuspend (dev); -pm_runtime_put (dev); + + ret =devm_pm_runtime_enable (dev); +if (ret) +return ret;dev_dbg (dev,"low-power mode enabled" ); }else
Greg Kroah-Hartman
maintainerPATCH 282/556 iio: srf04: fix pm_runtime handling on probe error path
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Cong Nguyen <[email protected]>
commit a40b2e7a17f26e38ab054363c9c7cde149588357 upstream.
When pm_runtime_set_active() fails during probe, the driver logs the error and unregisters the IIO device, but then falls through and still calls pm_runtime_enable() before returning the error.
Since probe returns an error, srf04_remove() is never called, so runtime PM is left enabled without a matching pm_runtime_disable(). This leaks the enable and triggers an "Unbalanced pm_runtime_enable!" warning on a subsequent bind of the device.
Return the error right after unregistering the IIO device so that runtime PM is not enabled on the failure path.
--- drivers/iio/proximity/srf04.c | 1 + 1 file changed, 1 insertion(+)
drivers/iio/proximity/srf04.c +1 -0
@@ -330,6 +330,7 @@ static int srf04_probe(struct platform_dif (ret) {dev_err (data->dev,"pm_runtime_set_active: %d\n" , ret);iio_device_unregister (indio_dev); +return ret; }pm_runtime_enable (data->dev);
Greg Kroah-Hartman
maintainerPATCH 283/556 iio: temperature: hid-sensor-temperature: switch to non-devm iio_device_register()
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Sanjay Chitroda <[email protected]>
commit 967d066f5334740f656577bc51c381a1bb707b61 upstream.
Avoid using devm_iio_device_register(), as this driver requires explicit error handling and teardown ordering.
With devm_iio_device_register(), IIO device remains registered until the devres cleanup phase. However, driver's remove() callback removes the sensor hub callback and trigger support. This can create a race window where IIO device is still visible and read_raw() requests are issued. These requests might call sensor_hub_input_attr_get_raw_value(), which waits up to 5 seconds for a response from the sensor hub callback that has already been removed.
Add an explicit iio_device_unregister() call in the teardown path to ensure deterministic cleanup, so that userspace can no longer access the device once backend resources begin to be dismantled.
--- drivers/iio/temperature/hid-sensor-temperature.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/iio/temperature/hid-sensor-temperature.c +2 -1
@@ -243,7 +243,7 @@ static int hid_temperature_probe(structif (ret) goto error_remove_trigger; - ret =devm_iio_device_register (indio_dev->dev.parent, indio_dev); + ret =iio_device_register (indio_dev);if (ret) goto error_remove_callback;
@@ -263,6 +263,7 @@ static void hid_temperature_remove(strucstruct iio_dev *indio_dev =platform_get_drvdata (pdev);struct temperature_state *temp_st =iio_priv (indio_dev); +iio_device_unregister (indio_dev);sensor_hub_remove_callback (hsdev,HID_USAGE_SENSOR_TEMPERATURE );hid_sensor_remove_trigger (indio_dev, &temp_st->common_attributes); }
Greg Kroah-Hartman
maintainerPATCH 284/556 iio: ti-ads7138: Disable STATS_EN bit while reading conversion results
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Paul Geurts <[email protected]>
commit bcb721c1bcb02ab225b3937bf131a0bc6fc1fecd upstream.
There is a data race in reading the STATS registers, resulting in wrong data being read. When the data in the RECENT register switches between 0x24F0 and 0x2500, occasionally value 0x2400 or 0x25F0 is read. This happens when the value is updated in between reading MSB and LSB.
The data sheet says: "Until a new conversion result is available, previous values can be read from the statistics registers. Before reading the statistics registers, set STATS_EN to 0 to prevent any updates to this register block." As the STATS_EN is currently not cleared, the values of the stats registers might change mid read, giving faulty values.
Disable the STATS_EN bit before reading one of the statistics registers to make sure the device does not update the register mid read. This is applicable to registers MAX_CHn_xSB, MIN_CHn_xSB and RECENT_CHn_xSB.
This means reading one of the statistics registers resets the MAX and MIN registers. This is unfortunate, but necessary to get correct data from the device.
--- drivers/iio/adc/ti-ads7138.c | 42 +++++++++++++++++++++++++++++++++--------- 1 file changed, 33 insertions(+), 9 deletions(-)
drivers/iio/adc/ti-ads7138.c +33 -9
@@ -227,6 +227,26 @@ static int ads7138_osr_to_bits(int osr)return -EINVAL ; } +static int ads7138_read_statistics (const struct i2c_client *client,u8 reg, +u8 *out_values,u8 length) +{ +int ret; + +/* Disable statistics update so the value is not updated mid read */ + ret =ads7138_i2c_clear_bit (client,ADS7138_REG_GENERAL_CFG , +ADS7138_GENERAL_CFG_STATS_EN ); +if (ret) +return ret; + + ret =ads7138_i2c_read_block (client, reg, out_values, length); +if (ret) +return ret; + +/* Enable statistics update after read */ +return ads7138_i2c_set_bit (client,ADS7138_REG_GENERAL_CFG , +ADS7138_GENERAL_CFG_STATS_EN ); +} +static int ads7138_read_raw (struct iio_dev *indio_dev,struct iio_chan_spec const *chan,int *val,int *val2,long mask)
@@ -236,28 +256,32 @@ static int ads7138_read_raw(struct iio_du8 values[2 ];switch (mask) { +/* +* Reading the statistics registers reinitializes them. This is +* unfortunate but necessary to prevent data races. +*/ case IIO_CHAN_INFO_RAW : - ret =ads7138_i2c_read_block (data->client, -ADS7138_REG_RECENT_LSB_CH (chan->channel), - values,ARRAY_SIZE (values)); + ret =ads7138_read_statistics (data->client, +ADS7138_REG_RECENT_LSB_CH (chan->channel), + values,ARRAY_SIZE (values));if (ret)return ret; *val =get_unaligned_le16 (values);return IIO_VAL_INT ;case IIO_CHAN_INFO_PEAK : - ret =ads7138_i2c_read_block (data->client, -ADS7138_REG_MAX_LSB_CH (chan->channel), - values,ARRAY_SIZE (values)); + ret =ads7138_read_statistics (data->client, +ADS7138_REG_MAX_LSB_CH (chan->channel), + values,ARRAY_SIZE (values));if (ret)return ret; *val =get_unaligned_le16 (values);return IIO_VAL_INT ;case IIO_CHAN_INFO_TROUGH : - ret =ads7138_i2c_read_block (data->client, -ADS7138_REG_MIN_LSB_CH (chan->channel), - values,ARRAY_SIZE (values)); + ret =ads7138_read_statistics (data->client, +ADS7138_REG_MIN_LSB_CH (chan->channel), + values,ARRAY_SIZE (values));if (ret)return ret;
Greg Kroah-Hartman
maintainerPATCH 285/556 iio: light: opt4060: Reject integration times with a non-zero seconds part
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Vidhu Sarwal <[email protected]>
commit b7e6e9af0d723afdec92364d5e7e064eeef44c8e upstream.
When setting the integration time, opt4060_write_raw() only uses val2 and ignores val. As a result, a write such as 1.000600 is accepted and programmed as 600 us, silently discarding the whole seconds part.
Since all supported integration times are less than one second, any non-zero val represents an invalid input. Reject such values instead of silently accepting them.
--- drivers/iio/light/opt4060.c | 3 +++ 1 file changed, 3 insertions(+)
drivers/iio/light/opt4060.c +3 -0
@@ -632,6 +632,9 @@ static int opt4060_write_raw(struct iio_switch (mask) {case IIO_CHAN_INFO_INT_TIME : +if (val) +return -EINVAL ; + int_time =opt4060_als_time_to_index (val2);if (int_time <0 )return int_time;
Greg Kroah-Hartman
maintainerPATCH 286/556 iio: light: opt4060: Fix incorrect register name in threshold read error message
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Vidhu Sarwal <[email protected]>
commit ad367638212a9f2495ecfa59c886f0cfb7934e9c upstream.
opt4060_get_thresholds() correctly reads OPT4060_THRESHOLD_HIGH, but logs "Failed to read THRESHOLD_LOW." if the read fails. This is a copy-and-paste mistake, as the preceding low-threshold read already uses the correct error message.
Update the error message to reference OPT4060_THRESHOLD_HIGH.
--- drivers/iio/light/opt4060.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/iio/light/opt4060.c +1 -1
@@ -808,7 +808,7 @@ static int opt4060_get_thresholds(struct ret =regmap_read (chip->regmap,OPT4060_THRESHOLD_HIGH , ®val);if (ret) { -dev_err (chip->dev,"Failed to read THRESHOLD_LOW.\n" ); +dev_err (chip->dev,"Failed to read THRESHOLD_HIGH.\n" );return ret; } *th_hi =opt4060_calc_val_from_th_reg (regval);
Greg Kroah-Hartman
maintainerPATCH 287/556 iio: light: opt4001: Fix power down clearing bits of the wrong register
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Nikhil Gautam <[email protected]>
commit 3b2cd82c524c75a2173f2e3f874652a75f81cd1d upstream.
opt4001_power_down() intends to clear the operating mode bits in the CTRL register but reads OPT4001_DEVICE_ID instead of OPT4001_CTRL, so the value written back to CTRL contains device ID bits rather than the current configuration.
Fix and simplify this by using regmap_clear_bits() on the CTRL register directly in the devm action, and drop opt4001_power_down() which has no other users.
--- drivers/iio/light/opt4001.c | 27 ++++----------------------- 1 file changed, 4 insertions(+), 23 deletions(-)
drivers/iio/light/opt4001.c +4 -23
@@ -222,33 +222,14 @@ static int opt4001_set_conf(struct opt40return ret; } -static int opt4001_power_down (struct opt4001_chip *chip) -{ -struct device *dev = &chip->client->dev; -int ret; -unsigned int reg; - - ret =regmap_read (chip->regmap,OPT4001_DEVICE_ID , ®); -if (ret) { -dev_err (dev,"Failed to read configuration\n" ); -return ret; - } - -/* MODE_OFF is 0x0 so just set bits to 0 */ - reg &= ~OPT4001_CTRL_OPER_MODE_MASK ; - - ret =regmap_write (chip->regmap,OPT4001_CTRL , reg); -if (ret) -dev_err (dev,"Failed to set configuration to power down\n" ); - -return ret; -} -static void opt4001_chip_off_action (void *data) {struct opt4001_chip *chip = data; +int ret; -opt4001_power_down (chip); + ret =regmap_clear_bits (chip->regmap,OPT4001_CTRL ,OPT4001_CTRL_OPER_MODE_MASK ); +if (ret) +dev_err (&chip->client->dev,"Failed to power down\n" ); }static const struct iio_chan_spec opt4001_channels[] = {
Greg Kroah-Hartman
maintainerPATCH 288/556 iio: light: opt4001: Fix incompatible pointer type passed to div_u64_rem()
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Nikhil Gautam <[email protected]>
commit afa28741c9a2cf6edb2e41e25ff146a562160bb3 upstream.
div_u64_rem() takes a u32 * for the remainder but is passed val2, which is an int *. There is no functional impact as int and u32 have the same size and representation on all supported architectures and the remainder is always smaller than the divisor, so it fits in the positive range of int. Fix the type mismatch by using a local u32 for the remainder and assigning the result to *val2.
--- drivers/iio/light/opt4001.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-)
drivers/iio/light/opt4001.c +3 -2
@@ -173,6 +173,7 @@ static int opt4001_read_lux_value(structu8 crc;u8 calc_crc;u64 lux_raw; +u32 rem;int ret; ret =regmap_read (chip->regmap,OPT4001_LIGHT1_MSB , &light1);
@@ -199,8 +200,8 @@ static int opt4001_read_lux_value(struct lux_raw = lux_raw << exp; lux_raw = lux_raw * chip->chip_info->mul; - *val =div_u64_rem (lux_raw, chip->chip_info->div, val2); - *val2 = *val2 *100 ; + *val =div_u64_rem (lux_raw, chip->chip_info->div, &rem); + *val2 = rem *100 ;return IIO_VAL_INT_PLUS_NANO ; }
Greg Kroah-Hartman
maintainerPATCH 289/556 iio: light: opt4001: Reject integration times with a non-zero seconds part
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Nikhil Gautam <[email protected]>
commit d0f21621f8b2b46661ea066d20705dbf7253db87 upstream.
opt4001_write_raw() only looks at val2 when setting the integration time, so a write such as 1.000600 is silently accepted as 600 us. Return -EINVAL if val is non-zero.
--- drivers/iio/light/opt4001.c | 3 +++ 1 file changed, 3 insertions(+)
drivers/iio/light/opt4001.c +3 -0
@@ -269,6 +269,9 @@ static int opt4001_write_raw(struct iio_switch (mask) {case IIO_CHAN_INFO_INT_TIME : +if (val) +return -EINVAL ; + int_time =opt4001_als_time_to_index (val2);if (int_time <0 )return int_time;
Greg Kroah-Hartman
maintainerPATCH 290/556 iio: light: opt4001: Fix reversed GENMASK() arguments in fault count mask
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Nikhil Gautam <[email protected]>
commit d64bfd9f3352b9d9bdeca06de1a0a1c1bd47b896 upstream.
GENMASK(h, l) requires h >= l, but OPT4001_CTRL_FAULT_COUNT is defined as GENMASK(0, 1). The define is currently unused so there is no functional impact, but fix it before anyone builds on it, and add the _MASK suffix for consistency with the neighbouring definitions.
--- drivers/iio/light/opt4001.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/iio/light/opt4001.c +1 -1
@@ -39,7 +39,7 @@#define OPT4001_CTRL_OPER_MODE_MASK GENMASK(5, 4)#define OPT4001_CTRL_LATCH_MASK GENMASK(3, 3)#define OPT4001_CTRL_INT_POL_MASK GENMASK(2, 2) -#define OPT4001_CTRL_FAULT_COUNT GENMASK(0, 1) +#define OPT4001_CTRL_FAULT_COUNT_MASK GENMASK(1, 0)/* OPT4001 constants */ #define OPT4001_DEVICE_ID_VAL 0x121
Greg Kroah-Hartman
maintainerPATCH 291/556 KVM: PPC: Book3S HV: Validate arch_compat against host compatibility mode
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Amit Machhiwal <[email protected]>
commit 884ea0283f4effac97ee8f451464a7d1be480d7c upstream.
On IBM POWER systems, newer processor generations can operate in compatibility modes corresponding to earlier generations. This becomes relevant for nested virtualization, where nested KVM guests may need to run with a specific processor compatibility level.
Currently, when running a nested KVM guest (L2) inside a Power11 pSeries logical partition (L1) booted in Power10 compatibility mode, the guest fails to boot while setting 'arch_compat'. This happens because the CPU class is derived from the hardware PVR (via mfspr()), which reflects the physical processor generation (Power11), rather than the effective compatibility mode (Power10).
As a result, userspace may request a Power11 arch_compat for the L2 guest. However, the L1 partition, running in Power10 compatibility, has only negotiated support up to Power10 with the Power Hypervisor (L0). When H_GUEST_SET_STATE is invoked with a Power11 Logical PVR, the hypervisor rejects the request, leading to a late guest boot failure:
KVM-NESTEDv2: couldn't set guest wide elements
[..KVM reg dump..]
This situation should be detected earlier and rejected by KVM. Without proper validation, if userspace ignores the error, the guest may continue to boot in Power11 raw mode on a Power10 compatibility host, which should not be allowed.
Introduce a validation mechanism that detects unsupported arch_compat values early in the guest initialization path. When an unsupported arch_compat is requested (e.g., Power11 on a Power10 compatibility mode host), kvmppc_set_arch_compat() uses cpu_has_feature(CPU_FTR_P11_PVR) to detect the mismatch and sets arch_compat to PVR_ARCH_INVALID (0xffffffff). This sentinel value is architecturally safe: PAPR specifies that valid logical PVR values must have 0x0f as the first byte, ensuring 0xffffffff lies permanently outside the specification-defined range. Setting this value triggers kvmppc_sanity_check() to mark the vCPU as invalid by setting vcpu->arch.sane to false. On the next vCPU run, kvmppc_vcpu_run_hv() checks this flag and returns -EINVAL, preventing the guest from running with an invalid processor compatibility configuration.
With this, when a Power11 arch_compat is requested on a Power10 compatibility mode host, the guest fails early during boot with:
error: kvm run failed Invalid argument
This provides a much clearer failure mode compared to the previous behavior where the guest could boot in Power11 raw mode (if userspace ignored the error) or fail late during H_GUEST_SET_STATE.
--- arch/powerpc/include/asm/reg.h | 12 ++++++++++++ arch/powerpc/kvm/book3s_hv.c | 15 ++++++++++++++- arch/powerpc/kvm/powerpc.c | 6 ++++++ 3 files changed, 32 insertions(+), 1 deletion(-)
arch/powerpc/include/asm/reg.h +12 -0
@@ -1357,6 +1357,18 @@#define PVR_ARCH_31 0x0f000006#define PVR_ARCH_31_P11 0x0f000007 +/* +* Kernel-internal sentinel for invalid processor compatibility modes. +* PAPR specifies that the first byte of a valid logical PVR value is +* 0x0f. So 0xffffffff lies permanently outside the PAPR-defined range +* and is safe to repurpose. KVM stores it in vcpu->arch.arch_compat +* when userspace requests an unsupported compatibility mode (e.g., +* Power11 PVR on a Power11 host booted in Power10 compat). +* kvmppc_sanity_check() detects this and prevents the vCPU from +* running with an unsupported arch_compat. +*/ +#define PVR_ARCH_INVALID 0xffffffff +/* Macros for setting and retrieving special purpose registers */ #ifndef __ASSEMBLER__
arch/powerpc/kvm/book3s_hv.c +14 -1
@@ -446,7 +446,19 @@ static int kvmppc_set_arch_compat(struct guest_pcr_bit =PCR_ARCH_300 ;break ;case PVR_ARCH_31 : + guest_pcr_bit =PCR_ARCH_31 ; +break ;case PVR_ARCH_31_P11 : +/* +* Need to check this for ISA 3.1, as Power10 and +* Power11 share the same PCR. For any subsequent ISA +* versions, this will be taken care of by the guest vs +* host PCR comparison below. +*/ +if (!cpu_has_feature (CPU_FTR_P11_PVR )) { + arch_compat =PVR_ARCH_INVALID ; + goto out; + } guest_pcr_bit =PCR_ARCH_31 ;break ;default :
@@ -469,6 +481,7 @@ static int kvmppc_set_arch_compat(structreturn -EINVAL ; } +out:spin_lock (&vc->lock); vc->arch_compat = arch_compat;kvmhv_nestedv2_mark_dirty (vcpu,KVMPPC_GSID_LOGICAL_PVR );
@@ -479,7 +492,7 @@ static int kvmppc_set_arch_compat(struct vc->pcr = (host_pcr_bit - guest_pcr_bit) |PCR_MASK ;spin_unlock (&vc->lock); -return 0 ; +return kvmppc_sanity_check (vcpu); }static void kvmppc_dump_regs (struct kvm_vcpu *vcpu)
arch/powerpc/kvm/powerpc.c +6 -0
@@ -258,6 +258,12 @@ int kvmppc_sanity_check(struct kvm_vcpuif (!vcpu->arch.pvr) goto out; +#if defined(CONFIG_KVM_BOOK3S_HV_POSSIBLE ) +if (vcpu->arch.vcore && + vcpu->arch.vcore->arch_compat ==PVR_ARCH_INVALID ) + goto out; +#endif +/* PAPR only works with book3s_64 */ if ((vcpu->arch.cpu_type !=KVM_CPU_3S_64 ) && vcpu->arch.papr_enabled) goto out;
Greg Kroah-Hartman
maintainerPATCH 292/556 KVM: nVMX: Always flush vpid02 on first use
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yosry Ahmed <[email protected]>
commit f0772389413dce9657c7d6950abf3edbbd511356 upstream.
Make sure vpid02 is always flushed on first use by setting last_vpid=0 when allocating vpid02. nested_vmx_transition_tlb_flush() will always detect a VPID change on first VM-Enter after VMXON, because VPID=0 in vmcs12 is not allowed if L1 enables VPID.
This avoids using stale TLB entries from a previous lifetime of the VPID, that might have been associated with a different vCPU (or a completely different VM).
Note that last_vpid is already being initialized as 0 when the vCPU is created, but it is not reset when vpid02 is freed on VMXOFF. Hence, the problem can only occur if L1 does VMXOFF -> VMXON, runs an L2, and KVM happens to reuse a VPID that has TLB entries on the physical CPU.
--- arch/x86/kvm/vmx/nested.c | 10 ++++++++++ 1 file changed, 10 insertions(+)
arch/x86/kvm/vmx/nested.c +10 -0
@@ -1326,6 +1326,9 @@ static void nested_vmx_transition_tlb_fl* is the VPID incorporated into the MMU context. I.e. KVM must assume * that the new vpid12 has never been used and thus represents a new * guest ASID that cannot have entries in the TLB. +* +* Note, last_vpid is initialized as 0, so the first nested VM-Enter +* after VMXON will always flush the TLB to avoid using stale entries. */ if (is_vmenter && vmcs12->virtual_processor_id != vmx->nested.last_vpid) { vmx->nested.last_vpid = vmcs12->virtual_processor_id;
@@ -5432,6 +5435,13 @@ static int enter_vmx_operation(struct kv vmx->nested.vpid02 =allocate_vpid (); +/* +* Clear last_vpid to ensure that the VPID is flushed on the first +* nested VM-Enter. Otherwise, stale TLB entries from a previous life of +* the VPID (e.g. different vCPU or even different VM) could be used. +*/ + vmx->nested.last_vpid =0 ; + vmx->nested.vmcs02_initialized = false; vmx->nested.vmxon = true;
Greg Kroah-Hartman
maintainerPATCH 293/556 KVM: nVMX: Decouple INVVPID operand checks from flushing of vpid02
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Sean Christopherson <[email protected]>
commit 32912404b4b1ee98400744941c78f019a63d6e8f upstream.
Separate the INVVPID operand checks from the actual flushing of vpid02 so the flushing can be adjusted to do the right thing when vmcs02 was last loaded on a different pCPU, without having to duplicate the logic across multiple case-statements.
Opportunistically let the VM-Fail paths poke out past 80 chars.
No functional change intended.
--- arch/x86/kvm/vmx/nested.c | 43 +++++++++++++------------------------------ 1 file changed, 13 insertions(+), 30 deletions(-)
arch/x86/kvm/vmx/nested.c +13 -30
@@ -6069,7 +6069,6 @@ static int handle_invvpid(struct kvm_vcpu64 vpid;u64 gla; } operand; -u16 vpid02;int r, gpr_index; if (!(vmx->nested.msrs.secondary_ctls_high &
@@ -6104,8 +6103,15 @@ static int handle_invvpid(struct kvm_vcpreturn kvm_handle_memory_failure (vcpu, r, &e);if (operand.vpid >>16 ) -return nested_vmx_fail (vcpu, -VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID ); +return nested_vmx_fail (vcpu,VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID ); + +if (type !=VMX_VPID_EXTENT_ALL_CONTEXT && !operand.vpid) +return nested_vmx_fail (vcpu,VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID ); + +/* LAM doesn't apply to addresses that are inputs to TLB invalidation. */ +if (type ==VMX_VPID_EXTENT_INDIVIDUAL_ADDR && +is_noncanonical_invlpg_address (operand.gla, vcpu)) +return nested_vmx_fail (vcpu,VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID );/* * Always flush the effective vpid02, i.e. never flush the current VPID
@@ -6113,33 +6119,10 @@ static int handle_invvpid(struct kvm_vcp* VMCS, and so whether or not the current vmcs12 has VPID enabled is * irrelevant (and there may not be a loaded vmcs12). */ - vpid02 =nested_get_vpid02 (vcpu); -switch (type) { -case VMX_VPID_EXTENT_INDIVIDUAL_ADDR : -/* -* LAM doesn't apply to addresses that are inputs to TLB -* invalidation. -*/ -if (!operand.vpid || -is_noncanonical_invlpg_address (operand.gla, vcpu)) -return nested_vmx_fail (vcpu, -VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID ); -vpid_sync_vcpu_addr (vpid02, operand.gla); -break ; -case VMX_VPID_EXTENT_SINGLE_CONTEXT : -case VMX_VPID_EXTENT_SINGLE_NON_GLOBAL : -if (!operand.vpid) -return nested_vmx_fail (vcpu, -VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID ); -vpid_sync_context (vpid02); -break ; -case VMX_VPID_EXTENT_ALL_CONTEXT : -vpid_sync_context (vpid02); -break ; -default : -WARN_ON_ONCE (1 ); -return kvm_skip_emulated_instruction (vcpu); - } +if (type ==VMX_VPID_EXTENT_INDIVIDUAL_ADDR ) +vpid_sync_vcpu_addr (nested_get_vpid02 (vcpu), operand.gla); +else +vpid_sync_context (nested_get_vpid02 (vcpu));/* * Sync the shadow page tables if EPT is disabled, L1 is invalidating
Greg Kroah-Hartman
maintainerPATCH 294/556 KVM: nVMX: Ensure KVM_REQ_GET_NESTED_STATE_PAGES is cleared on VM-Exit
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Sean Christopherson <[email protected]>
commit 11722439fb206c88e6f31be54173efa9880b4ccb upstream.
Always check and clear KVM_REQ_GET_NESTED_STATE_PAGES when emulating a nested VM-Exit to ensure the request is cleared, even when KVM was built with CONFIG_KVM_HYPERV=n, as KVM subtly relies on the "check" to clear the flag and thus avoid double-mapping the vmcs12 pages, e.g. if KVM manages to bail from VM-Enter without processing the request, and then emulates VMLAUNCH or VMRESUME.
--- arch/x86/kvm/vmx/nested.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-)
arch/x86/kvm/vmx/nested.c +3 -2
@@ -5076,8 +5076,9 @@ void __nested_vmx_vmexit(struct kvm_vcpu/* trying to cancel vmlaunch/vmresume is a bug */ kvm_warn_on_nested_run_pending (vcpu); -#ifdef CONFIG_KVM_HYPERV +/* Note, "checking" the request also clears the request. */ if (kvm_check_request (KVM_REQ_GET_NESTED_STATE_PAGES , vcpu)) { +#ifdef CONFIG_KVM_HYPERV /* * KVM_REQ_GET_NESTED_STATE_PAGES is also used to map * Enlightened VMCS after migration and we still need to
@@ -5085,8 +5086,8 @@ void __nested_vmx_vmexit(struct kvm_vcpu* the first L2 run. */ (void )nested_get_evmcs_page (vcpu); - }#endif + }/* Service pending TLB flush requests for L2 before switching to L1. */ kvm_service_local_tlb_flush_requests (vcpu);
Greg Kroah-Hartman
maintainerPATCH 295/556 KVM: nVMX: Service local TLB flushes on failed nested VM-Enter
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yosry Ahmed <[email protected]>
commit 05a0b701d1089fb57beeb8982f23c3bbafe0fa8b upstream.
KVM services local TLB flushes on "full" nested VM-Exits (through __nested_vmx_vmexit()), but not if a nested VM-Enter fails (e.g. due to failed VMCS checks in nested_vmx_enter_non_root_mode()).
However, it is possible that KVM had queued TLB flushes that need to be performed, even if the nested VM-Enter was not successful. For example, if VPID is disabled for L2 (via nested_vmx_transition_tlb_flush(), or if via the MSR load lists, as the SDM says:
If any MSR is being loaded in such a way that would architecturally require a TLB flush, the TLBs are updated so that, after VM entry, the logical processor will not use any translations that were cached before the transition.
The SDM is unclear about when the TLB flush should occur, and whether or not a failed VM entry would flush the TLB, so it is safer to always do the TLB flush in this case.
More concretely, KVM also updates the last VPID L1 used for L2 in nested_vmx_transition_tlb_flush() (i.e. last_vpid), even if the VM entry ultimately fails. With the current code, KVM could miss a TLB flush if L1 changes L2's VPID, then does a failed VM entry followed by a successful one, as the failed VM entry would update last_vpid but not actually flush the TLB. Servicing local TLB flushes on failed VM entries makes sure that the TLB is always flushed when last_vpid is updated.
--- arch/x86/kvm/vmx/nested.c | 8 ++++++++ 1 file changed, 8 insertions(+)
arch/x86/kvm/vmx/nested.c +8 -0
@@ -3763,6 +3763,14 @@ enum nvmx_vmentry_status nested_vmx_ente vmentry_fail_vmexit_guest_mode:if (vmcs12->cpu_based_vm_exec_control &CPU_BASED_USE_TSC_OFFSETTING ) vcpu->arch.tsc_offset -= vmcs12->tsc_offset; + +/* +* Handle any TLB flush requests that were queued for L2 if KVM made it +* far enough along to switch to L2 context. Note, loading host state +* will generate any flushes for L1 required by VM-Exit. +*/ +kvm_service_local_tlb_flush_requests (vcpu); +leave_guest_mode (vcpu); vmentry_fail_vmexit:
Greg Kroah-Hartman
maintainerPATCH 296/556 KVM: nVM: Ensure INVVPID is emulated on the correct physical CPU
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yosry Ahmed <[email protected]>
commit 6d00e67326d831e6e610933a3800712f4ffe6ec1 upstream.
When emulating INVVPID, KVM executes INVVPID on the physical CPU using vpid02 (instead of the L1 assigned VPID), after doing some validations on the operands. However, it is possible that the physical CPU KVM executes INVVPID on is different from the CPU L2 is running on.
For example, in the following scenario:
- L2 runs on CPU #1 and exits to L1 (vmx->nested.vmcs02.cpu=1)
- L1 migrates to CPU #2 and executes INVVPID
- KVM executes INVVPID on CPU #2
- L1 migrates back to CPU #1 and runs L2 (vmx->nested.vmcs02.cpu=1)
The TLB entries on CPU #1 are never invalidated, because INVVPID was executed on CPU #2, and vmcs02 never ran on a different pCPU (i.e. vmx_vcpu_load_vmcs() will *not* request KVM_REQ_TLB_FLUSH).
Ensure that INVVPID is being executed on the same pCPU that L2 last ran on, and if not, fallback to clearing last_vpid=0 to trigger a full VPID flush on the next nested VM-Enter (as KVM will detect L1 using a different VPID for L2). If L2 ends up running on a different pCPU, KVM will flush the TLB anyway through vmx_vcpu_load_vmcs().
--- arch/x86/kvm/vmx/nested.c | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-)
arch/x86/kvm/vmx/nested.c +10 -1
@@ -6079,6 +6079,7 @@ static int handle_invvpid(struct kvm_vcpu64 gla; } operand;int r, gpr_index; +int cpu; if (!(vmx->nested.msrs.secondary_ctls_high & SECONDARY_EXEC_ENABLE_VPID) ||
@@ -6127,11 +6128,19 @@ static int handle_invvpid(struct kvm_vcp* and never explicitly flush vpid01. INVVPID targets a VPID, not a * VMCS, and so whether or not the current vmcs12 has VPID enabled is * irrelevant (and there may not be a loaded vmcs12). +* +* If vmcs02 was last loaded on a different pCPU, then defer the flush +* by invalidating the nested VPID tracking to ensure that KVM performs +* the invalidation on the correct pCPU. */ -if (type ==VMX_VPID_EXTENT_INDIVIDUAL_ADDR ) + cpu =get_cpu (); +if (cpu != vmx->nested.vmcs02.cpu) + vmx->nested.last_vpid =0 ; +else if (type ==VMX_VPID_EXTENT_INDIVIDUAL_ADDR )vpid_sync_vcpu_addr (nested_get_vpid02 (vcpu), operand.gla);else vpid_sync_context (nested_get_vpid02 (vcpu)); +put_cpu ();/* * Sync the shadow page tables if EPT is disabled, L1 is invalidating
Greg Kroah-Hartman
maintainerPATCH 297/556 KVM: x86/mmu: Use CMPXCHG when clearing Accessed bit in TDP MMU
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Sean Christopherson <[email protected]>
commit 3d679b7cb31f74bf2303123ce4ee3266eeee999a upstream.
Use LOCK CMPXCHG instead of LOCK AND to clear the Accessed bit when aging SPTEs in the TDP MMU, as doing a LOCK AND can corrupt a FROZEN SPTE and allow a third CPU to effectively overwrite the FROZEN SPTE. As pointed out by AI of some kind, because the magic FROZEN_SPTE value is a "full" SPTE, not a single bit, and includes the Accessed bit, clearing the Accessed bit in a FROZEN SPTE will result in is_frozen_spte() getting a false negative.
E.g. if CPU0 freezes an SPTE, and CPU1 clears the Accessed bit in the frozen SPTE, then CPU2 could come along and overwrite the frozen SPTE with a shadow-present SPTE.
Thankfully, the false negative is largely benign, because outside of TDX, which doesn't support aging, KVM only freezes leaf SPTEs when removing an upper level shadow page. So while KVM could clobber a frozen SPTE back to a shadow-present SPTE, and could even use the new SPTE, the subsequent TLB flush will make the orphaned, shadow-present SPTE unreachable. Failure to ever zap the orphaned leaf SPTE would show up in KVM's stats, but otherwise is benign (because KVM no longer keeps an elevated refcount for leaf SPTEs).
Opportunistically add a comment to warn future developers away from using kvm_tdp_mmu_write_spte_atomic() and tdp_mmu_clear_spte_bits_atomic(), as they are generally unsafe. Keep the helpers, e.g. instead of open-coding the atomic64_fetch_and() in tdp_mmu_clear_spte_bits(), as scary warnings usually are more effective deterrent against recidivism than removal of the dangerous code.
Alternatively, KVM could use different bits for the magic FROZEN_SPTE value, e.g. setting the Dirty bits (with effective IPAT and Global aliases) would likely be "ok", as IPAT/Global are extremely unlikely to be cleared without doing a full SPTE write, and KVM's clearing of Dirty bits shares logic with Write-Protection, which must do a full SPTE write (via cmpxchg64() in the TDP MMU) to ensure KVM isn't clobbering state. But there is zero reason to carry that risk (beyond stubbornness in wanting to preserve a "cute" idea), as the cost of LOCK CMPXCHG and LOCK AND are within 1-2 uops of each other on modern hardware.
--- arch/x86/kvm/mmu/tdp_iter.h | 7 +++++++ arch/x86/kvm/mmu/tdp_mmu.c | 20 +++++++++----------- 2 files changed, 16 insertions(+), 11 deletions(-)
arch/x86/kvm/mmu/tdp_iter.h +7 -0
@@ -19,6 +19,13 @@ static inline u64 kvm_tdp_mmu_read_spte(return READ_ONCE (*rcu_dereference (sptep)); } +/* +* WARNING! mmu_lock must be held for write when using the "write atomic" or +* "clear bits atomic" APIs, otherwise KVM could overwrite the "wrong" old SPTE +* value, i.e. clobber an update from a different CPU. The only exception is +* when KVM is freezing a leaf SPTE for removal, in which case KVM doesn't care +* about the exact old SPTE value (KVM will react to the actual old value). +*/ static inline u64 kvm_tdp_mmu_write_spte_atomic (tdp_ptep_t sptep,u64 new_spte) {KVM_MMU_WARN_ON (is_ept_ve_possible (new_spte));
arch/x86/kvm/mmu/tdp_mmu.c +9 -11
@@ -1334,19 +1334,17 @@ static void kvm_tdp_mmu_age_spte(structif (WARN_ON_ONCE (is_mirror_sptep (iter->sptep)))return ; -if (spte_ad_enabled (iter->old_spte)) { - iter->old_spte =tdp_mmu_clear_spte_bits_atomic (iter->sptep, - shadow_accessed_mask); +if (spte_ad_enabled (iter->old_spte)) new_spte = iter->old_spte & ~shadow_accessed_mask; - }else { +else new_spte =mark_spte_for_access_track (iter->old_spte); -/* -* It is safe for the following cmpxchg to fail. Leave the -* Accessed bit set, as the spte is most likely young anyway. -*/ -if (__tdp_mmu_set_spte_atomic (kvm, iter, new_spte)) -return ; - } + +/* +* Don't bother retrying if another CPU modified the SPTE, the SPTE is +* either being zapped or is likely still in-use, i.e. is still young. +*/ +if (__tdp_mmu_set_spte_atomic (kvm, iter, new_spte)) +return ;trace_kvm_tdp_mmu_spte_changed (iter->as_id, iter->gfn, iter->level, iter->old_spte, new_spte);
Greg Kroah-Hartman
maintainerPATCH 298/556 KVM: x86/mmu: Consume the locked rmap value in the lockless rmap walk
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Phil Rosenthal <[email protected]>
commit e428f9779a43737d830111238816f1928b07aefb upstream.
__kvm_rmap_lock() deliberately elides the rmap lock when it observes an empty rmap. In that case kvm_rmap_lock_readonly() also re-enables preemption and returns zero, so the caller holds neither the rmap lock nor a preemption reference. The elision documents the invariant it relies on:
* Elide the lock if the rmap is empty, as lockless walkers (read-only
* mode) don't need to (and can't) walk an empty rmap, nor can they add
* entries to the rmap. I.e. the only paths that process empty rmaps
* do so while holding mmu_lock for write, and are mutually exclusive.
kvm_rmap_age_gfn_range() ignores the returned value and unconditionally enters for_each_rmap_spte_lockless(). The iterator started with rmap_get_first(), which re-reads rmap_head->val rather than using the value returned by the lock. If a writer populates the rmap between the lock's read and the iterator's re-read, the aging path walks the newly installed rmap without holding its lock.
For a KVM_RMAP_MANY rmap this leaves the walker following a pte_list_desc chain that it never locked. A writer holding mmu_lock for write may free that chain (e.g. kvm_zap_all_rmap_sptes() on the recycle path, or any rmap zap) via kmem_cache_free() while the walk is in progress, giving a slab use-after-free. Nothing serialises the two: the aging path runs without mmu_lock when CONFIG_KVM_MMU_LOCKLESS_AGING=y, and the rmap lock that would otherwise exclude the writer was elided. Because the empty path re-enables preemption, the interval between the two reads can span an arbitrary scheduling delay.
Fix the class of bug by having the lockless walk consume the value returned by the lock instead of re-reading the rmap. Split rmap_get_first() into __rmap_get_first(), which starts an iterator from an already-read rmap value, and make for_each_rmap_spte_lockless() take that value and call __rmap_get_first() directly. kvm_rmap_age_gfn_range() passes the value returned by kvm_rmap_lock_readonly(): when the lock was elided the value is zero, __rmap_get_first() returns NULL, and the walk is skipped. No lockless walker re-reads the rmap, so the lock-elision invariant cannot be violated, and no lock()-without-paired-unlock() path is added to the aging code.
--- arch/x86/kvm/mmu/mmu.c | 33 +++++++++++++++++++-------------- 1 file changed, 19 insertions(+), 14 deletions(-)
arch/x86/kvm/mmu/mmu.c +19 -14
@@ -1245,18 +1245,9 @@ struct rmap_iterator {int pos;/* index of the sptep */ }; -/* -* Iteration must be started by this function. This should also be used after -* removing/dropping sptes from the rmap link because in such cases the -* information in the iterator may not be valid. -* -* Returns sptep if found, NULL otherwise. -*/ -static u64 *rmap_get_first (struct kvm_rmap_head *rmap_head, -struct rmap_iterator *iter) +static u64 *__rmap_get_first (unsigned long rmap_val, +struct rmap_iterator *iter) { -unsigned long rmap_val =kvm_rmap_get (rmap_head); -if (!rmap_val)return NULL ;
@@ -1271,6 +1262,19 @@ static u64 *rmap_get_first(struct kvm_rm }/* +* Iteration must be started by this function. This should also be used after +* removing/dropping sptes from the rmap link because in such cases the +* information in the iterator may not be valid. +* +* Returns sptep if found, NULL otherwise. +*/ +static u64 *rmap_get_first (struct kvm_rmap_head *rmap_head, +struct rmap_iterator *iter) +{ +return __rmap_get_first (kvm_rmap_get (rmap_head), iter); +} + +/* * Must be used with a valid iterator: e.g. after rmap_get_first(). * * Returns sptep if found, NULL otherwise.
@@ -1304,8 +1308,9 @@ static u64 *rmap_get_next(struct rmap_it__for_each_rmap_spte (_rmap_head_, _iter_, _sptep_) \ if (!WARN_ON_ONCE(!is_shadow_present_pte(*(_sptep_)))) \ -#define for_each_rmap_spte_lockless (_rmap_head_, _iter_, _sptep_, _spte_) \ - __for_each_rmap_spte(_rmap_head_, _iter_, _sptep_) \ +#define for_each_rmap_spte_lockless (_rmap_val_, _iter_, _sptep_, _spte_) \ + for (_sptep_ = __rmap_get_first(_rmap_val_, _iter_); \ + _sptep_; _sptep_ = rmap_get_next(_iter_)) \ if (is_shadow_present_pte(_spte_ = mmu_spte_get_lockless(sptep)))static void drop_spte (struct kvm *kvm,u64 *sptep)
@@ -1743,7 +1748,7 @@ static bool kvm_rmap_age_gfn_range(struc rmap_head =gfn_to_rmap (gfn, level, range->slot); rmap_val =kvm_rmap_lock_readonly (rmap_head); -for_each_rmap_spte_lockless (rmap_head, &iter, sptep, spte) { +for_each_rmap_spte_lockless (rmap_val, &iter, sptep, spte) {if (!is_accessed_spte (spte))continue ;
Greg Kroah-Hartman
maintainerPATCH 299/556 KVM: x86: hyper-v: Clamp stimer deadline to avoid livelock
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Carlos López <[email protected]>
commit 0ca49fbd2883cd53d32d85b50feef17fa04d0fbf upstream.
Fix an issue where userspace or the guest can program an Hyper-V synthetic timer to have a deadline in the past via integer overflow, preventing the CPU from making progress and triggering an RCU stall.
Hyper-V's SynIC exposes 4 per-vCPU synthetic timers to the guest, which are emulated by KVM. Each is programmed through the HV_X64_MSR_STIMERi_CONFIG and HV_X64_MSR_STIMERi_COUNT MSRs. Depending on CONFIG, COUNT represents either the absolute expiration time or the period of a periodic timer, both expressed in 100ns ticks. These timers may be set both by the guest (WRMSR) and the host (KVM_SET_MSRS).
When the timer is enabled, stimer_start() translates COUNT to an absolute monotonic deadline and arms an hrtimer. If COUNT is set to a value close to U64_MAX, the deadline calculation can overflow.
ktime_add_ns(ktime_now, 100 * (stimer->exp_time - time_now))
This can result in a CPU livelock. stimer_start() arms the timer via hrtimer_start() with a deadline in the past, which causes it to immediately fire. The stimer callback then raises KVM_RQ_HV_STIMER, with the intention of causing KVM to deliver a synthetic interrupt on the next vCPU guest enter.
Then, once userspace issues KVM_RUN, vcpu_enter_guest() consumes the request, calling kvm_hv_process_stimers(). This would normally disable the timer via stimer_expiration() once the deadline is in the past. However, the deadline comparison is done between the KVM reference counter and stime->exp_time, which is a big value close to U64_MAX, so this never happens for a few thousand years.
kvm_hv_process_timers() then re-arms the timer via stimer_start(), since it was not disabled, which again fires immediately. Before entering the guest, kvm_vcpu_exit_request() checks kvm_request_pending(), which returns true due to the newly raised KVM_REQ_HV_STIMER. Then vcpu_enter_guest() aborts the guest entry, returning early into vcpu_run(), which loops back again into vcpu_enter_guest(), restarting the cycle.
Since there are no manual yields in this loop, a task with SCHED_FIFO may starve RCU grace-period kthreads, which exposes the stalls found by syzcaller:
rcu: INFO: rcu_preempt detected stalls on CPUs/tasks:
rcu: (detected by 1, t=10502 jiffies, g=14269, q=1142 ncpus=2)
rcu: All QSes seen, last rcu_preempt kthread activity 10500 (4294965239-4294954739), jiffies_till_next_fqs=1, root ->qsmask 0x0
rcu: rcu_preempt kthread starved for 10500 jiffies! g14269 f0x2 RCU_GP_WAIT_FQS(5) ->state=0x0 ->cpu=0
rcu: Unless rcu_preempt kthread gets sufficient CPU time, OOM is now expected behavior.
( ... )
Call Trace:
<IRQ>
__run_hrtimer kernel/time/hrtimer.c:1773 [inline]
__hrtimer_run_queues+0x408/0xc30 kernel/time/hrtimer.c:1841
hrtimer_interrupt+0x45b/0xaa0 kernel/time/hrtimer.c:1903
local_apic_timer_interrupt arch/x86/kernel/apic/apic.c:1045 [inline]
__sysvec_apic_timer_interrupt+0x102/0x3e0 arch/x86/kernel/apic/apic.c:1062
instr_sysvec_apic_timer_interrupt arch/x86/kernel/apic/apic.c:1056 [inline]
sysvec_apic_timer_interrupt+0xa1/0xc0 arch/x86/kernel/apic/apic.c:1056
</IRQ>
<TASK>
asm_sysvec_apic_timer_interrupt+0x1a/0x20 arch/x86/include/asm/idtentry.h:697
RIP: 0010:__raw_spin_unlock_irqrestore include/linux/spinlock_api_smp.h:152 [inline]
RIP: 0010:_raw_spin_unlock_irqrestore+0xa8/0x110 kernel/locking/spinlock.c:194
Code: 74 05 e8 0b f4 5f f6 48 c7 44 24 20 00 00 00 00 9c 8f 44 24 20 f6 44 24 21 02 75 4f f7 c3 00 02 00 00 74 01 fb bf 01 00 00 00 <e8> 23 6b 27 f6 65 8b 05 7c 60 5a 07 85 c0 74 40 48 c7 04 24 0e 36
RSP: 0018:ffffc900040a7320 EFLAGS: 00000206
RAX: 5de15cb931505900 RBX: 0000000000000a06 RCX: 5de15cb931505900
RDX: 0000000000000007 RSI: ffffffff8daa9dc3 RDI: 0000000000000001
RBP: ffffc900040a73b0 R08: ffffffff8fc3d077 R09: 1ffffffff1f87a0e
R10: dffffc0000000000 R11: fffffbfff1f87a0f R12: dffffc0000000000
R13: 0000000000000000 R14: ffff8880b8628240 R15: 1ffff92000814e64
hrtimer_start include/linux/hrtimer.h:259 [inline]
stimer_start arch/x86/kvm/hyperv.c:682 [inline]
kvm_hv_process_stimers+0xd0a/0x16a0 arch/x86/kvm/hyperv.c:893
vcpu_enter_guest arch/x86/kvm/x86.c:11193 [inline]
vcpu_run+0x2240/0x76b0 arch/x86/kvm/x86.c:11639
kvm_arch_vcpu_ioctl_run+0x1148/0x1c90 arch/x86/kvm/x86.c:11984
kvm_vcpu_ioctl+0x99a/0xed0 virt/kvm/kvm_main.c:4492
vfs_ioctl fs/ioctl.c:51 [inline]
__do_sys_ioctl fs/ioctl.c:597 [inline]
__se_sys_ioctl+0xfc/0x170 fs/ioctl.c:583
do_syscall_x64 arch/x86/entry/syscall_64.c:63 [inline]
do_syscall_64+0xfa/0xf80 arch/x86/entry/syscall_64.c:94
entry_SYSCALL_64_after_hwframe+0x77/0x7f
RIP: 0033:0x7f635278f749
Code: ff ff c3 66 2e 0f 1f 84 00 00 00 00 00 0f 1f 40 00 48 89 f8 48 89 f7 48 89 d6 48 89 ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d 01 f0 ff ff 73 01 c3 48 c7 c1 a8 ff ff ff f7 d8 64 89 01 48
RSP: 002b:00007f635365c038 EFLAGS: 00000246 ORIG_RAX: 0000000000000010
RAX: ffffffffffffffda RBX: 00007f63529e5fa0 RCX: 00007f635278f749
RDX: 0000000000000000 RSI: 000000000000ae80 RDI: 0000000000000005
RBP: 00007f6352813f91 R08: 0000000000000000 R09: 0000000000000000
R10: 0000000000000000 R11: 0000000000000246 R12: 0000000000000000
R13: 00007f63529e6038 R14: 00007f63529e5fa0 R15: 00007ffd5b219358
</TASK>Fix this by clamping the deadline computation to KTIME_MAX, which preserves the intent of arming a timer very far in the future. ktime_add_safe() already does this type of clamping, so use it after checking that that multiplying by the 100ns time tick also does not overflow.
--- arch/x86/kvm/hyperv.c | 25 ++++++++++++++++++------- 1 file changed, 18 insertions(+), 7 deletions(-)
arch/x86/kvm/hyperv.c +18 -7
@@ -627,6 +627,18 @@ static enum hrtimer_restart stimer_timer }/* +* Translate a stimer expiry given in 100ns reference ticks into an +* an absolute deadline. Saturates on overflow. +*/ +static ktime_t stimer_add_delta (ktime_t now,u64 delta_100ns) +{ +if (delta_100ns >=KTIME_MAX /100 ) +return KTIME_MAX ; + +return ktime_add_safe (now,100 * delta_100ns); +} + +/* * stimer_start() assumptions: * a) stimer->count is not equal to 0 * b) stimer->config has HV_STIMER_ENABLE flag
@@ -635,6 +647,7 @@ static int stimer_start(struct kvm_vcpu_ {u64 time_now;ktime_t ktime_now; +ktime_t deadline; time_now =get_time_ref_counter (hv_stimer_to_vcpu (stimer)->kvm); ktime_now =ktime_get ();
@@ -657,10 +670,8 @@ static int stimer_start(struct kvm_vcpu_ stimer->index, time_now, stimer->exp_time); -hrtimer_start (&stimer->timer, -ktime_add_ns (ktime_now, -100 * (stimer->exp_time - time_now)), -HRTIMER_MODE_ABS ); + deadline =stimer_add_delta (ktime_now, stimer->exp_time - time_now); +hrtimer_start (&stimer->timer, deadline,HRTIMER_MODE_ABS );return 0 ; } stimer->exp_time = stimer->count;
@@ -679,9 +690,9 @@ static int stimer_start(struct kvm_vcpu_ stimer->index, time_now, stimer->count); -hrtimer_start (&stimer->timer, -ktime_add_ns (ktime_now,100 * (stimer->count - time_now)), -HRTIMER_MODE_ABS ); + deadline =stimer_add_delta (ktime_now, stimer->count - time_now); +hrtimer_start (&stimer->timer, deadline,HRTIMER_MODE_ABS ); +return 0 ; }
Greg Kroah-Hartman
maintainerPATCH 300/556 KVM: x86: Serialize writes to disabled_quirks using kvm->lock
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Sean Christopherson <[email protected]>
commit ba76b23ed36ab230fc2577aba24f65851114902f upstream.
Protect writes to disabled_quirks with kvm->lock to ensure KVM doesn't clobber state in the unlikely scenario that userspace disables disparate quirks from multiple tasks. More importantly, this will allow wrapping accesses with {READ,WRITE}_ONCE without "needing" to also guard the writer with a useless and confusing READ_ONCE (since the RMW wouldn't be atomic anyways).
Ideally, KVM would disallow disabling quirks once quirks are "live", but that would be a potentially breaking userspace ABI change, and while all existing quirks are fully live only after vCPUs have been created, several MMU-related quirks, IGNORE_GUEST_PAT and SLOT_ZAP_ALL, are partially live at all times. Because populating MMUs requires a vCPU, the guest-visible behavior of IGNORE_GUEST_PAT and SLOT_ZAP_ALL requires a vCPU, but for KVM itself, processing the quirk (or not) has functional impact, i.e. for all intents and purposes, KVM can't prevent those quirks from being disabled after they've been consumed.
--- arch/x86/kvm/x86.c | 2 ++ 1 file changed, 2 insertions(+)
arch/x86/kvm/x86.c +2 -0
@@ -6736,7 +6736,9 @@ int kvm_vm_ioctl_enable_cap(struct kvm *break ; fallthrough;case KVM_CAP_DISABLE_QUIRKS : +mutex_lock (&kvm->lock); kvm->arch.disabled_quirks |= cap->args[0 ] & kvm_caps.supported_quirks; +mutex_unlock (&kvm->lock); r =0 ;break ;case KVM_CAP_SPLIT_IRQCHIP : {
Greg Kroah-Hartman
maintainerPATCH 301/556 KVM: x86: Ensure runtime reads of disabled_quirks are resolved once
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Sean Christopherson <[email protected]>
commit ed15cb21999217e549414c128b4a0485debf6278 upstream.
Wrap the sole reader of disabled_quirks with READ_ONCE(), and wrap the post-VM-creation write to disabled_quirks with WRITE_ONCE(), to ensure checking the status of a quirk doesn't re-read disabled_quirks *if* the caller needs such a guarantee. This will allow splitting the "fast" MMU zap into front and back halves, without potentially skipping the back half if SLOT_ZAP_ALL were concurrently disabled (which would be "fine" in the current code base, but far from ideal).
--- arch/x86/kvm/x86.c | 3 ++- arch/x86/kvm/x86.h | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-)
arch/x86/kvm/x86.c +2 -1
@@ -6737,7 +6737,8 @@ int kvm_vm_ioctl_enable_cap(struct kvm * fallthrough;case KVM_CAP_DISABLE_QUIRKS :mutex_lock (&kvm->lock); - kvm->arch.disabled_quirks |= cap->args[0 ] & kvm_caps.supported_quirks; +WRITE_ONCE (kvm->arch.disabled_quirks, + kvm->arch.disabled_quirks | (cap->args[0 ] & kvm_caps.supported_quirks));mutex_unlock (&kvm->lock); r =0 ;break ;
arch/x86/kvm/x86.h +1 -1
@@ -367,7 +367,7 @@ static inline bool vcpu_match_mmio_gpa(sstatic inline bool kvm_check_has_quirk (struct kvm *kvm,u64 quirk) { -return !(kvm->arch.disabled_quirks & quirk); +return !(READ_ONCE (kvm->arch.disabled_quirks) & quirk); } static __always_inline void kvm_request_l1tf_flush_l1d(void)
Greg Kroah-Hartman
maintainerPATCH 302/556 KVM: x86: Move enabling EFER.SVME and EFER.LMSLE to generic EFER setup
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yosry Ahmed <[email protected]>
commit 6ccc19d4c1eb97a994180af8afcab58422cb409d upstream.
Move SVM-specific EFER bit enablement to generic x86 code, with the rest of EFER bit enablement. Unifying the code for EFER bit enablement allows for a later change to re-initialize EFER bits on module init.
No functional change intended.
--- arch/x86/kvm/svm/svm.c | 4 ---- arch/x86/kvm/x86.c | 6 ++++++ 2 files changed, 6 insertions(+), 4 deletions(-)
arch/x86/kvm/svm/svm.c +0 -4
@@ -5658,10 +5658,6 @@ static __init int svm_hardware_setup(voiif (nested) {pr_info ("Nested Virtualization enabled\n" ); -kvm_enable_efer_bits (EFER_SVME ); -if (!boot_cpu_has (X86_FEATURE_EFER_LMSLE_MBZ )) -kvm_enable_efer_bits (EFER_LMSLE ); - r =nested_svm_init_msrpm_merge_offsets ();if (r)return r;
arch/x86/kvm/x86.c +6 -0
@@ -10015,6 +10015,12 @@ static void kvm_setup_efer_caps(void)if (kvm_cpu_cap_has (X86_FEATURE_AUTOIBRS ))kvm_enable_efer_bits (EFER_AUTOIBRS ); + +if (kvm_cpu_cap_has (X86_FEATURE_SVM )) { +kvm_enable_efer_bits (EFER_SVME ); +if (!boot_cpu_has (X86_FEATURE_EFER_LMSLE_MBZ )) +kvm_enable_efer_bits (EFER_LMSLE ); + } }static inline void kvm_ops_update (struct kvm_x86_init_ops *ops)
Greg Kroah-Hartman
maintainerPATCH 303/556 KVM: s390: Fix length check __import_wp_info()
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Christian Borntraeger <[email protected]>
commit 4c07680a467e2f7697245bcd11691bffb2a6f0ed upstream.
struct kvm_hw_breakpoint::len is a __u64 that is fully controlled by user space. This is then assigned to wp_info->len, which is an int. The bounds check is done on the truncated value while the allocation uses the untruncated one:
wp_info->len = bp_data->len; [...] if (wp_info->len < 0 || wp_info->len > MAX_WP_SIZE) return -EINVAL; wp_info->old_data = kmalloc(bp_data->len, GFP_KERNEL_ACCOUNT);
Use the validated value for the allocation as intended. Without this fix userspace can trigger >4GB allocations which will fail and result in a WARN due to MAX_PAGE_ORDER.
Message-ID: <[email protected]>
--- arch/s390/kvm/guestdbg.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
arch/s390/kvm/guestdbg.c +1 -1
@@ -184,7 +184,7 @@ static int __import_wp_info(struct kvm_vif (wp_info->len <0 || wp_info->len >MAX_WP_SIZE )return -EINVAL ; - wp_info->old_data =kmalloc (bp_data->len,GFP_KERNEL_ACCOUNT ); + wp_info->old_data =kmalloc (wp_info->len,GFP_KERNEL_ACCOUNT );if (!wp_info->old_data)return -ENOMEM ;/* try to backup the original value */
Greg Kroah-Hartman
maintainerPATCH 304/556 KVM: s390: Fix memory leak in guest debug handling
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Christian Borntraeger <[email protected]>
commit 121ea1de927c8b9bfdf53c31cad27b86d5de0293 upstream.
bp_data is freed only for the error case by kfree(bp_data). Every successful KVM_SET_GUEST_DEBUG will leak bp_data.
Message-ID: <[email protected]>
--- arch/s390/kvm/guestdbg.c | 1 + 1 file changed, 1 insertion(+)
arch/s390/kvm/guestdbg.c +1 -0
@@ -267,6 +267,7 @@ int kvm_s390_import_bp_data(struct kvm_v vcpu->arch.guestdbg.hw_bp_info = bp_info; vcpu->arch.guestdbg.nr_hw_wp = nr_wp; vcpu->arch.guestdbg.hw_wp_info = wp_info; +kfree (bp_data);return 0 ; error:kfree (bp_data);
Greg Kroah-Hartman
maintainerPATCH 305/556 KVM: s390: Fix old_data leak in guest debug error path
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Christian Borntraeger <[email protected]>
commit aa9c8e8baf1e765fa65b93212522c636f25d846f upstream.
__import_wp_info() allocates a per-watchpoint old_data buffer to back up the original guest memory contents. If a later watchpoint of the same KVM_SET_GUEST_DEBUG request fails to import, kvm_s390_import_bp_data() jumps to the error label, which frees the wp_info array but not the old_data buffers of the entries that were imported successfully. Up to MAX_BP_COUNT - 1 buffers of up to MAX_WP_SIZE bytes are leaked per failed request, and the request can be repeated.
Create error handling for cleaning up all created old_data memory areas.
Message-ID: <[email protected]>
--- arch/s390/kvm/guestdbg.c | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-)
arch/s390/kvm/guestdbg.c +5 -1
@@ -252,7 +252,7 @@ int kvm_s390_import_bp_data(struct kvm_v ret =__import_wp_info (vcpu, &bp_data[i], &wp_info[nr_wp]);if (ret) - goto error; + goto error_wp; nr_wp++;break ;case KVM_HW_BP :
@@ -269,6 +269,10 @@ int kvm_s390_import_bp_data(struct kvm_v vcpu->arch.guestdbg.hw_wp_info = wp_info;kfree (bp_data);return 0 ; + +error_wp: +while (nr_wp--) +kfree (wp_info[nr_wp].old_data); error:kfree (bp_data);kfree (wp_info);
Greg Kroah-Hartman
maintainerPATCH 306/556 KVM: s390: Free guest debug data on vcpu destroy
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Christian Borntraeger <[email protected]>
commit e7f698b09d4a7c36b299acf680fc50fe868e2bcd upstream.
kvm_s390_clear_bp_data() is only called from kvm_arch_vcpu_ioctl_set_guest_debug(), i.e. when user space changes or disables debugging. A vCPU that is destroyed while hardware breakpoints are still armed - the normal case when the VMM just exits or crashes - leaks hw_bp_info, hw_wp_info and all old_data buffers, since generic KVM frees the vCPU right after kvm_arch_vcpu_destroy().
That is bounded by MAX_BP_COUNT entries, so roughly 8 KiB per vCPU, but it is unbounded over VM lifetimes. The allocations are GFP_KERNEL_ACCOUNT, so the charge also outlives the exiting process and pins dying memcgs.
Fix by clearing the debug data on vCPU destruction. Calling it unconditionally is fine: struct kvm_vcpu is zero allocated, so for a vCPU that never enabled debugging the counters are 0 and the pointers NULL.
Message-ID: <[email protected]>
--- arch/s390/kvm/kvm-s390.c | 1 + 1 file changed, 1 insertion(+)
arch/s390/kvm/kvm-s390.c +1 -0
@@ -3410,6 +3410,7 @@ void kvm_arch_vcpu_destroy(struct kvm_vctrace_kvm_s390_destroy_vcpu (vcpu->vcpu_id);kvm_s390_clear_local_irqs (vcpu);kvm_clear_async_pf_completion_queue (vcpu); +kvm_s390_clear_bp_data (vcpu);if (!kvm_is_ucontrol (vcpu->kvm))sca_del_vcpu (vcpu);kvm_s390_update_topology_change_report (vcpu->kvm,1 );
Greg Kroah-Hartman
maintainerPATCH 307/556 KVM: s390: Take srcu when importing watchpoint data
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Christian Borntraeger <[email protected]>
commit a4e482def8533ebace517d9f67f1465841b1f982 upstream.
__import_wp_info() backs up the original guest memory contents of a watchpoint with read_guest_abs(), which is kvm_read_guest() and therefore resolves the memslot via __kvm_memslots(). That requires kvm->srcu (or kvm->slots_lock) to be held, otherwise a concurrent memslot update can free the memslots array under us once its SRCU grace period has elapsed.
As this is not fast path, following lock ordering (mutex first, then srcu) take the big hammer and hold the srcu for the full import.
Message-ID: <[email protected]>
--- arch/s390/kvm/kvm-s390.c | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-)
arch/s390/kvm/kvm-s390.c +4 -2
@@ -4249,8 +4249,10 @@ int kvm_arch_vcpu_ioctl_set_guest_debug(/* enforce guest PER */ kvm_s390_set_cpuflags (vcpu,CPUSTAT_P ); -if (dbg->control &KVM_GUESTDBG_USE_HW_BP ) - rc =kvm_s390_import_bp_data (vcpu, dbg); +if (dbg->control &KVM_GUESTDBG_USE_HW_BP ) { +scoped_guard (srcu, &vcpu->kvm->srcu) + rc = kvm_s390_import_bp_data(vcpu, dbg); + } }else {kvm_s390_clear_cpuflags (vcpu,CPUSTAT_P ); vcpu->arch.guestdbg.last_bp =0 ;
Greg Kroah-Hartman
maintainerPATCH 308/556 KVM: s390: Zero initialize data structures for inject_pfault_token
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Christian Borntraeger <[email protected]>
commit 4e2c7f7cbc27418f9a290399b986c1b85ff93b90 upstream.
__kvm_inject_pfault_token() only sets .type and .u.ext.ext_params2 of the on-stack struct kvm_s390_irq but the full ext substructure is copied into the cpu local variable on inject. ext_params and pad contain stale stack values.
Interrupt delivery only uses ext_params2, so nothing leaks to the guest, but a host user can use the migration ioctls to get to the data.
Fix by zero-initializing the irq struct.
Do the same for the inti data structure.
Message-ID: <[email protected]>
--- arch/s390/kvm/kvm-s390.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
arch/s390/kvm/kvm-s390.c +2 -2
@@ -4477,8 +4477,8 @@ int kvm_s390_try_set_tod_clock(struct kvstatic void __kvm_inject_pfault_token (struct kvm_vcpu *vcpu,bool start_token,unsigned long token) { -struct kvm_s390_interrupt inti; -struct kvm_s390_irq irq; +struct kvm_s390_interrupt inti = {}; +struct kvm_s390_irq irq = {};struct kvm_s390_interrupt_info *inti_mem =NULL ;int ret =0 ;
Greg Kroah-Hartman
maintainerPATCH 309/556 KVM: s390: Zero initialize irq in reinject_machine_check
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Christian Borntraeger <[email protected]>
commit b239410c7653ff6781d4cf1d63cfc52a1bb71788 upstream.
kvm_s390_reinject_machine_check() fills cr14, mcic, ext_damage_code and failing_storage_address of the on-stack struct kvm_s390_irq, but struct kvm_s390_mchk_info also has a pad word and a 16 byte fixed_logout array. struct mcck_volatile_info carries no logout data, so there is nothing to copy there and both stay whatever was on the stack.
__inject_mchk() then memcpy()s fixed_logout into the vcpu local interrupt state unconditionally. This will reach the guest during deliver and userspace during migration.
Reflecting zeroes is the correct behaviour here, as KVM has no logout data for a reinjected machine check.
This needs a host machine check while the cpu is in SIE so not trivial to trigger.
Message-ID: <[email protected]>
--- arch/s390/kvm/interrupt.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
arch/s390/kvm/interrupt.c +1 -1
@@ -3109,7 +3109,7 @@ void kvm_s390_reinject_machine_check(str struct mcck_volatile_info *mcck_info) {struct kvm_s390_interrupt_info inti; -struct kvm_s390_irq irq; +struct kvm_s390_irq irq = {};struct kvm_s390_mchk_info *mchk;union mci mci;__u64 cr14 =0 ;/* upper bits are not used */
Greg Kroah-Hartman
maintainerPATCH 310/556 KVM: s390: Fix memory corruption by not reinjecting CK machine checks
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Christian Borntraeger <[email protected]>
commit 546dde823a36d7283dcf46127c2f3d093443860f upstream.
Channel-subsystem damage machine checks are for the host channel subsystem. The guest channel subsystem is emulated in the userspace VMM. There is no point in forwarding such machine checks into the guest.
This also simplifies the machine check reinjection and avoids kfree of a stack variable as reported by sashiko. There might be still machine checks that have the ck bit set with another bit (like instruction damage), mask out the CK bit in s390_backup_mcck_info(), like the CP and ED bits already are.
Message-ID: <[email protected]>
--- arch/s390/include/asm/nmi.h | 3 +++ arch/s390/kernel/nmi.c | 5 +---- arch/s390/kvm/interrupt.c | 24 ++++++++---------------- 3 files changed, 12 insertions(+), 20 deletions(-)
arch/s390/include/asm/nmi.h +3 -0
@@ -22,6 +22,7 @@#define MCCK_CODE_SYSTEM_DAMAGE BIT(63)#define MCCK_CODE_EXT_DAMAGE BIT(63 - 5)#define MCCK_CODE_CP BIT(63 - 9) +#define MCCK_CODE_CK BIT(63 - 11)#define MCCK_CODE_STG_ERROR BIT(63 - 16)#define MCCK_CODE_STG_KEY_ERROR BIT(63 - 18)#define MCCK_CODE_STG_DEGRAD BIT(63 - 19)
@@ -33,6 +34,8 @@#define MCCK_CODE_FC_VALID BIT(63 - 43)#define MCCK_CODE_CPU_TIMER_VALID BIT(63 - 46) +#define MCCK_CODE_NO_GUEST (MCCK_CODE_CP | MCCK_CODE_EXT_DAMAGE | MCCK_CODE_CK) +#ifndef __ASSEMBLER__ union mci {
arch/s390/kernel/nmi.c +1 -4
@@ -344,8 +344,7 @@ static void notrace s390_backup_mcck_inf sie_page = container_of(sie_block, struct sie_page, sie_block); mcck_backup = &sie_page->mcck_info; - mcck_backup->mcic =get_lowcore ()->mcck_interruption_code & - ~(MCCK_CODE_CP |MCCK_CODE_EXT_DAMAGE ); + mcck_backup->mcic =get_lowcore ()->mcck_interruption_code & ~MCCK_CODE_NO_GUEST ; mcck_backup->ext_damage_code =get_lowcore ()->external_damage_code; mcck_backup->failing_storage_address =get_lowcore ()->failing_storage_address; }
@@ -357,8 +356,6 @@ NOKPROBE_SYMBOL(s390_backup_mcck_info);#define ED_STP_ISLAND 6/* External damage STP island check */ #define ED_STP_SYNC 7/* External damage STP sync check */ -#define MCCK_CODE_NO_GUEST (MCCK_CODE_CP | MCCK_CODE_EXT_DAMAGE) -/* * machine check handler. */
arch/s390/kvm/interrupt.c +8 -16
@@ -3108,9 +3108,7 @@ static int set_adapter_int(struct kvm_kevoid kvm_s390_reinject_machine_check (struct kvm_vcpu *vcpu,struct mcck_volatile_info *mcck_info) { -struct kvm_s390_interrupt_info inti;struct kvm_s390_irq irq = {}; -struct kvm_s390_mchk_info *mchk;union mci mci;__u64 cr14 =0 ;/* upper bits are not used */ int rc;
@@ -3129,20 +3127,14 @@ void kvm_s390_reinject_machine_check(strif (mci.w) cr14 |=CR14_WARNING_SUBMASK ; - mchk = mci.ck ? &inti.mchk : &irq.u.mchk; - mchk->cr14 = cr14; - mchk->mcic = mcck_info->mcic; - mchk->ext_damage_code = mcck_info->ext_damage_code; - mchk->failing_storage_address = mcck_info->failing_storage_address; -if (mci.ck) { -/* Inject the floating machine check */ - inti.type =KVM_S390_MCHK ; - rc =__inject_vm (vcpu->kvm, &inti); - }else { -/* Inject the machine check to specified vcpu */ - irq.type =KVM_S390_MCHK ; - rc =kvm_s390_inject_vcpu (vcpu, &irq); - } + irq.u.mchk.cr14 = cr14; + irq.u.mchk.mcic = mcck_info->mcic; + irq.u.mchk.ext_damage_code = mcck_info->ext_damage_code; + irq.u.mchk.failing_storage_address = mcck_info->failing_storage_address; + +/* Inject the machine check to specified vcpu */ + irq.type =KVM_S390_MCHK ; + rc =kvm_s390_inject_vcpu (vcpu, &irq);WARN_ON_ONCE (rc); }
Greg Kroah-Hartman
maintainerPATCH 311/556 KVM: s390: keyop: use mmu_lock to read gmap->asce
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Christian Borntraeger <[email protected]>
commit da07a751efa4583385f9f0f47113549fe8871242 upstream.
Every other dat_* consumer in this file (kvm_s390_get_skeys, set_skeys, get_cmma_bits, set_cmma_bits, MEM_CLR_CMMA, kvm_s390_fixup_prefix, kvm_test_age_gfn, kvm_age_gfn) reads kvm->arch.gmap->asce *inside* the mmu_lock read-side. keyop is the only outlier.
gmap->asce is mutated under write_lock(mmu_lock) by gmap_set_limit() and keyop might use a stale asce value for walking as KVM_S390_KEYOP and KVM_S390_VM_MEM_LIMIT_SIZE can run concurrently. This can result in memory corruption.
Message-ID: <[email protected]>
--- arch/s390/kvm/kvm-s390.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
arch/s390/kvm/kvm-s390.c +2 -1
@@ -562,11 +562,12 @@ static void __kvm_s390_exit(void)static int kvm_s390_keyop (struct kvm_s390_mmu_cache *mc,struct kvm *kvm,int op,unsigned long addr,union skey skey) { -union asce asce = kvm->arch.gmap->asce;gfn_t gfn =gpa_to_gfn (addr); +union asce asce;int r;guard (read_lock)(&kvm->mmu_lock); + asce = kvm->arch.gmap->asce;switch (op) {case KVM_S390_KEYOP_SSKE :
Greg Kroah-Hartman
maintainerPATCH 312/556 KVM: s390: pv: Fix rc/rrc offset for PVM_DUMP
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Christian Borntraeger <[email protected]>
commit 1e3c8e7b3465fb8a49d3623d2d0f449c0b5b48f3 upstream.
The rc/rrc value is copied to the cmd location of the cmd in the kvm_pv_cmd structure. Fix the offset.
Message-ID: <[email protected]>
--- arch/s390/kvm/kvm-s390.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
arch/s390/kvm/kvm-s390.c +1 -1
@@ -5736,7 +5736,7 @@ long kvm_arch_vcpu_ioctl(struct file *fi r =kvm_s390_handle_pv_vcpu_dump (vcpu, &cmd);/* Always copy over UV rc / rrc data */ -if (copy_to_user ((__u8 __user *)argp, &cmd.rc, +if (copy_to_user (argp + offsetof(struct kvm_pv_cmd , rc), &cmd.rc,sizeof (cmd.rc) +sizeof (cmd.rrc))) r = -EFAULT ;break ;
Greg Kroah-Hartman
maintainerPATCH 313/556 KVM: s390: Restore sigset on error path
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Christian Borntraeger <[email protected]>
commit c44d36d8e6501c4934412d9014e5e02da9efdb8f upstream.
kvm_sigset_activate() installs vcpu->sigset via sigprocmask() and stashes the caller's mask in current->real_blocked; only kvm_sigset_deactivate() restores it.
For KVM_RUN on a STOPPED vcpu the error path will not restore the userspace mask. Re-arrange the error handling to also restore the signal mask.
Message-ID: <[email protected]>
--- arch/s390/kvm/kvm-s390.c | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-)
arch/s390/kvm/kvm-s390.c +4 -2
@@ -5073,7 +5073,7 @@ int kvm_arch_vcpu_ioctl_run(struct kvm_vpr_err_ratelimited ("can't run stopped vcpu %d\n" , vcpu->vcpu_id); rc = -EINVAL ; - goto out; + goto out_sigset; }kernel_fpu_begin (&fpu,KERNEL_FPC |KERNEL_VXR );
@@ -5103,9 +5103,11 @@ int kvm_arch_vcpu_ioctl_run(struct kvm_vstore_regs (vcpu);kernel_fpu_end (&fpu,KERNEL_FPC |KERNEL_VXR ); + vcpu->stat.exit_userspace++; + +out_sigset:kvm_sigset_deactivate (vcpu); - vcpu->stat.exit_userspace++; out:vcpu_put (vcpu);return rc;
Greg Kroah-Hartman
maintainerPATCH 314/556 KVM: arm64: Consider SCTLR_EL2.M when mapping the L1 VNCR page
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Marc Zyngier <[email protected]>
commit 8c774604b6ecaca495fa3d27c21593269627f48f upstream.
We record a VNCR TLB even when SCTLR_EL2.M is 0 in order to make our life easier. But this is not something that the architecture anticipate.
As a consequence, a hypervisor is free to set VNCR_EL2 to some PA when SCTLR_EL2.M==0, use it to run a guest which indirectly accesses the VNCR page, then eventually set SCTLR_EL2.M==1 with the same VA. Yes, this is odd, but apparently legal.
A common trick in HW is to invalidate the TLBs on SCTLR_ELx.M being flipped. But doing this is a not a good idea for us (we'd need to trap SCTLR accesses), and wouldn't scale as we nest deeper.
Instead, use the fact that the S1 MMU being off at the point of translation is cached in our TLB, and if it doesn't match the current MMU state, leave the VNCR unmapped.
--- arch/arm64/include/asm/kvm_nested.h | 7 +++++++ arch/arm64/kvm/at.c | 2 -- arch/arm64/kvm/nested.c | 4 ++++ 3 files changed, 11 insertions(+), 2 deletions(-)
arch/arm64/include/asm/kvm_nested.h +7 -0
@@ -388,6 +388,8 @@ struct s1_walk_result {bool failed; }; +#define S1_MMU_DISABLED (-127) +static inline void fail_s1_walk (struct s1_walk_result *wr,u8 fst,bool s1ptw) { wr->fst = fst;
@@ -396,6 +398,11 @@ static inline void fail_s1_walk(struct s wr->failed = true; } +static inline bool s1_walk_translated (struct s1_walk_result *wr) +{ +return wr->level !=S1_MMU_DISABLED ; +} +int __kvm_translate_va (struct kvm_vcpu *vcpu,struct s1_walk_info *wi,struct s1_walk_result *wr,u64 va); int __kvm_find_s1_desc_level(struct kvm_vcpu *vcpu, u64 va, u64 ipa,
arch/arm64/kvm/at.c +0 -2
@@ -11,8 +11,6 @@#include <asm/kvm_mmu.h> #include <asm/lsui.h> -#define S1_MMU_DISABLED (-127) -static int get_ia_size (struct s1_walk_info *wi) {return 64 - wi->txsz;
arch/arm64/kvm/nested.c +4 -0
@@ -1568,6 +1568,10 @@ static void kvm_map_l1_vncr(struct kvm_vif (!vt->valid)return ; +/* We cache the MMU state in the TLB. Check that it matches. */ +if (!!(vcpu_read_sys_reg (vcpu,SCTLR_EL2 ) & SCTLR_ELx_M) !=s1_walk_translated (&vt->wr)) +return ; +if (read_vncr_el2 (vcpu) != vt->gva)return ;
Greg Kroah-Hartman
maintainerPATCH 315/556 KVM: arm64: Handle negative S1 walk levels in VNCR TLB size evaluation
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Marc Zyngier <[email protected]>
commit 8053393680d4fa3eb962667d2be95dd39f0940e5 upstream.
Computing the effects of a TLB invalidation involves looking at the size of the mapping cached by the TLB. For S1 mappings such as VNCR, this is deducted from the combination of the base granule size and the mapping level.
However, this implies that the S1 MMU is *on*. When the MMU is off, we indicate this with the level being set to a "creative" value of -127 (S1_MMU_DISABLED).
This ends-up being misinterpreted by pgshift_level_to_ttl() as it doesn't handle negative levels at all (the level is immediately cast to a u8 and only the bottom two bits considered), leading to an invalidation size of 0. Not helpful.
Tidy-up pgshift_level_to_ttl() to handle these negative levels, and ttl_to_size() to always return SZ_1G when no valid TTL is present. This allows the removal of open-coded checks for similar situations.
Note that the check for a negative value not explicitely checking for S1_MMU_DISABLED is deliberate, so that actual negative levels introduced with LVA2 and D128 can take the same path if we ever support them.
--- arch/arm64/kvm/nested.c | 26 +++++++++++++++++++------- 1 file changed, 19 insertions(+), 7 deletions(-)
arch/arm64/kvm/nested.c +19 -7
@@ -506,7 +506,7 @@ int kvm_walk_nested_s2(struct kvm_vcpu *return ret; } -static unsigned int ttl_to_size (u8 ttl) +static unsigned int __ttl_to_size (u8 ttl) {int level = ttl &3 ;int gran = (ttl >>2 ) &3 ;
@@ -562,10 +562,22 @@ static unsigned int ttl_to_size(u8 ttl)return max_size; } -static u8 pgshift_level_to_ttl (u16 shift,u8 level) +static unsigned int ttl_to_size (u8 ttl) +{ +return __ttl_to_size (ttl) ?:SZ_1G ; +} + +static u8 pgshift_level_to_ttl (u16 shift,s8 level) {u8 ttl; +/* +* If we don't have a proper level, fallback to the maximum +* size. +*/ +if (level <0 ) +return 0 ; +switch (shift) {case 12 : ttl =TLBI_TTL_TG_4K ;
@@ -676,7 +688,11 @@ unsigned long compute_tlb_inval_range(st ttl =get_guest_mapping_ttl (mmu, addr); } - max_size =ttl_to_size (ttl); +/* +* Don't use the default 1GB fallback, as we can adapt to the +* max mapping size we allow at S2. +*/ + max_size =__ttl_to_size (ttl);if (!max_size) {/* Compute the maximum extent of the invalidation */
@@ -1126,8 +1142,6 @@ static void compute_s1_tlbi_range(structcase OP_TLBI_VALE1OSNXS : scope->type =TLBI_VA ; scope->size =ttl_to_size (FIELD_GET (TLBI_TTL_MASK , val)); -if (!scope->size) - scope->size =SZ_1G ; scope->va =tlbi_va_s1_to_va (val) & ~(scope->size -1 ); scope->asid =FIELD_GET (TLBIR_ASID_MASK , val);break ;
@@ -1154,8 +1168,6 @@ static void compute_s1_tlbi_range(structcase OP_TLBI_VAALE1OSNXS : scope->type =TLBI_VAA ; scope->size =ttl_to_size (FIELD_GET (TLBI_TTL_MASK , val)); -if (!scope->size) - scope->size =SZ_1G ; scope->va =tlbi_va_s1_to_va (val) & ~(scope->size -1 );break ;case OP_TLBI_RVAE2 :
Greg Kroah-Hartman
maintainerPATCH 316/556 KVM: arm64: Correctly handle end of VA space TLBI invalidation
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Marc Zyngier <[email protected]>
commit 34af2c3e31f91a739dc175459fdbd99ed952b457 upstream.
Our TLB invalidation by VA code is based on comparing two ranges, one defined by the TLB, and one defined by the TLBI instruction.
Each range is defined by a start and a size. However, the way the comparison is done doesn't account for address rollover, as it compares an address with (base + size). This works nicely until this expression represent the last page/block in the TTBR1 VA space, as the result is a big fat 0. And a failed TLB invalidation.
Rewrite the comparison in a way that is immune to the address rollover (making the end address inclusive instead of exclusive), and move this into a common helper that is used by both VA and IPA invalidations, as suggested by Hyunwoo Kim (although the IPA version didn't suffer from this particular problem, obviously).
--- arch/arm64/kvm/nested.c | 43 +++++++++++++++++++------------------------ 1 file changed, 19 insertions(+), 24 deletions(-)
arch/arm64/kvm/nested.c +19 -24
@@ -1001,6 +1001,20 @@ static void invalidate_vncr(struct vncr_clear_fixmap (vncr_fixmap (vt->cpu)); } +static bool vncr_tlb_intersects (struct vncr_tlb *vt,u64 addr, +u64 scope_start,u64 scope_size) +{ +u64 tlb_size, tlb_start, tlb_end, scope_end; + + tlb_size =ttl_to_size (pgshift_level_to_ttl (vt->wi.pgshift, vt->wr.level)); + + tlb_start = addr & ~(tlb_size -1 ); + tlb_end = tlb_start + tlb_size -1 ; + scope_end = scope_start + scope_size -1 ; + +return !(tlb_end < scope_start || tlb_start > scope_end); +} +/* * VNCR TLB invalidation occurs from MMU notifiers or TLBI instructions, and * either can race against a vcpu not being onlined yet (no pseudo-TLB
@@ -1023,19 +1037,9 @@ static void kvm_invalidate_vncr_ipa(struif (!kvm_has_feat (kvm,ID_AA64MMFR4_EL1 , NV_frac,NV2_ONLY ))return ; -kvm_for_each_vncr_tlb (i, vcpu, vt, kvm) { -u64 ipa_start, ipa_end, ipa_size; - - ipa_size =ttl_to_size (pgshift_level_to_ttl (vt->wi.pgshift, - vt->wr.level)); - ipa_start = vt->wr.pa & ~(ipa_size -1 ); - ipa_end = ipa_start + ipa_size; - -if (ipa_end <= start || ipa_start >= end) -continue ; - -invalidate_vncr (vt); - } +kvm_for_each_vncr_tlb (i, vcpu, vt, kvm) +if (vncr_tlb_intersects (vt, vt->wr.pa, start, end - start)) +invalidate_vncr (vt); }struct s1e2_tlbi_scope {
@@ -1061,28 +1065,19 @@ static void invalidate_vncr_va(struct kvlockdep_assert_held_write (&kvm->mmu_lock);kvm_for_each_vncr_tlb (i, vcpu, vt, kvm) { -u64 va_start, va_end, va_size; - - va_size =ttl_to_size (pgshift_level_to_ttl (vt->wi.pgshift, - vt->wr.level)); - va_start = vt->gva & ~(va_size -1 ); - va_end = va_start + va_size; -switch (scope->type) {case TLBI_ALL :break ;case TLBI_VA : -if (va_end <= scope->va || - va_start >= (scope->va + scope->size)) +if (!vncr_tlb_intersects (vt, vt->gva, scope->va, scope->size))continue ;if (vt->wr.nG && vt->wr.asid != scope->asid)continue ;break ;case TLBI_VAA : -if (va_end <= scope->va || - va_start >= (scope->va + scope->size)) +if (!vncr_tlb_intersects (vt, vt->gva, scope->va, scope->size))continue ;break ;
Greg Kroah-Hartman
maintainerPATCH 317/556 KVM: arm64: Handle VNCR TLB invalidation race with vcpu_put() VNCR unmapping
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Marc Zyngier <[email protected]>
commit 38640bc32be3fcf9526d477155bc19d3f146231f upstream.
While VNCR TLB invalidation always occurs under the MMU lock, vcpu_put() doesn't, while it unmaps the VNCR page.
The problem is that the invalidation evaluates vncr_tlb::cpu to decide whether an unmapping needs to take place (cpu != -1) before performing it. On the other hand, this_cpu_reset_vncr_fixmap() unconditionally unmaps if L1_VNCR_MAPPED is set.
These two obviously can race, with a TOCTOU pattern on the TLBI path, and a BUG_ON() on the vcpu_put() path. And the two can end-up calling vncr_fixmap(-1), with extra lethal effects.
Move the reset of vncr_tlb::cpu to -1 to a common function, and make this update atomic so that only a single thread can reset the field and perform the corresponding unmap. The vcpu_put() still need to unconditionally unmap the current VNCR to close another ugly race.
Finally, the assignment of vncr_tlb::cpu is moved to be kept in sync with the actual mapping, similar to L1_VNCR_MAPPED being set.
--- arch/arm64/kvm/nested.c | 42 ++++++++++++++++++++++++++++++++---------- 1 file changed, 32 insertions(+), 10 deletions(-)
arch/arm64/kvm/nested.c +32 -10
@@ -27,7 +27,7 @@ struct vncr_tlb {bool hpa_writable;/* -1 when not mapped on a CPU */ -int cpu; +atomic_t cpu;/* * true if the TLB is valid. Can only be changed with the
@@ -895,16 +895,40 @@ void kvm_vcpu_load_hw_mmu(struct kvm_vcp } } +/* +* Unmapping an L1 VNCR can happen concurrently without the mmu lock being +* effective (vcpu_put() vs TLBI handling). The atomic_xchg below ensures +* that only one CPU sets it to -1 while getting a valid CPU number back. +*/ +static int unmap_l1_vncr (struct vncr_tlb *vt) +{ +int cpu =atomic_xchg_relaxed (&vt->cpu,-1 ); + +if (cpu !=-1 ) +clear_fixmap (vncr_fixmap (cpu)); + +return cpu; +} +static void this_cpu_reset_vncr_fixmap (struct kvm_vcpu *vcpu) {if (!host_data_test_flag (L1_VNCR_MAPPED ))return ; -BUG_ON (vcpu->arch.vncr_tlb->cpu !=smp_processor_id ());BUG_ON (is_hyp_ctxt (vcpu)); -clear_fixmap (vncr_fixmap (vcpu->arch.vncr_tlb->cpu)); - vcpu->arch.vncr_tlb->cpu =-1 ; +/* +* Unconditionally unmap the local VNCR if we have lost the race +* against a concurrent TLBI. Otherwise we could end-up running +* another vcpu with VNCR still mapped if the TLBI thread is +* preempted between the exchange and the clear_fixmap(). +* +* Note that we do not care about the TLBI nuking the fixmap behind +* the back of an running vcpu. This will only generate a fault and +* possibly a retranslation. +*/ +if (unmap_l1_vncr (vcpu->arch.vncr_tlb) ==-1 ) +clear_fixmap (vncr_fixmap (smp_processor_id ()));host_data_clear_flag (L1_VNCR_MAPPED );atomic_dec (&vcpu->kvm->arch.vncr_map_count); }
@@ -997,8 +1021,7 @@ u16 get_asid_by_regime(struct kvm_vcpu *static void invalidate_vncr (struct vncr_tlb *vt) { vt->valid = false; -if (vt->cpu !=-1 ) -clear_fixmap (vncr_fixmap (vt->cpu)); +unmap_l1_vncr (vt); } static bool vncr_tlb_intersects(struct vncr_tlb *vt, u64 addr,
@@ -1454,7 +1477,7 @@ static int kvm_translate_vncr(struct kvm vt->hpa = pfn <<PAGE_SHIFT ; vt->hpa_writable = writable; vt->valid = true; - vt->cpu =-1 ; +atomic_set (&vt->cpu,-1 );kvm_make_request (KVM_REQ_MAP_L1_VNCR_EL2 , vcpu);kvm_release_faultin_page (vcpu->kvm, page, false, vt->wr.pw && vt->hpa_writable);
@@ -1585,8 +1608,6 @@ static void kvm_map_l1_vncr(struct kvm_vif (vt->wr.nG &&get_asid_by_regime (vcpu,TR_EL20 ) != vt->wr.asid)return ; - vt->cpu =smp_processor_id (); -if (vt->hpa_writable && vt->wr.pw && vt->wr.pr) prot =PAGE_KERNEL ;else if (vt->wr.pr)
@@ -1601,7 +1622,8 @@ static void kvm_map_l1_vncr(struct kvm_v* FIXME: WO doesn't work at all, need POE support in the kernel. */ if (pgprot_val (prot) !=pgprot_val (PAGE_NONE )) { -__set_fixmap (vncr_fixmap (vt->cpu), vt->hpa, prot); +atomic_set (&vt->cpu,smp_processor_id ()); +__set_fixmap (vncr_fixmap (atomic_read (&vt->cpu)), vt->hpa, prot);host_data_set_flag (L1_VNCR_MAPPED );atomic_inc (&vcpu->kvm->arch.vncr_map_count); }
Greg Kroah-Hartman
maintainerPATCH 318/556 KVM: arm64: Make VNCR invalidation participate in MMU invalidation retry
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Marc Zyngier <[email protected]>
commit 2b7324f3a0c1072b9d578b8d42f199506753f26e upstream.
A VNCR TLB invalidation can occur on one vcpu while another vcpu is faulting in this same page. Without correctly handling this, we can end up with the following scenario:
- vcpu A walks the PTs to translate VNCR
- before vcpu A is able to grab the MMU lock to insert the TLB, vcpu B updates the S1 PTs with an invalid entry, and issues a TLBI S1E2 for this VA
- vcpu A inserts the TLB for something that is now invalid
This isn't a new problem, and we manage S2 by having the MMU notifier to bump up mmu_invalidate_seq on invalidation so that the fault can be replayed.
We can perform something similar here, and extend invalidate_vncr_va() to update the same counter, clearly indicating that the context has changed under our feet. This is safe as the invalidation always happen while holding the MMU lock for write, and that we sample the sequence number before walking S1.
--- arch/arm64/kvm/nested.c | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-)
arch/arm64/kvm/nested.c +18 -3
@@ -1060,6 +1060,12 @@ static void kvm_invalidate_vncr_ipa(struif (!kvm_has_feat (kvm,ID_AA64MMFR4_EL1 , NV_frac,NV2_ONLY ))return ; +/* +* Note that invalidating the VNCR on the back of an MMU notifier +* doesn't require messing with the invalidation counter for a +* parallel walk. The notifier itself will have bumped the counter, +* making sure we rewalk. +*/ kvm_for_each_vncr_tlb (i, vcpu, vt, kvm)if (vncr_tlb_intersects (vt, vt->wr.pa, start, end - start))invalidate_vncr (vt);
@@ -1087,6 +1093,15 @@ static void invalidate_vncr_va(struct kvlockdep_assert_held_write (&kvm->mmu_lock); +/* +* We might be performing a parallel S1 walk, so bump up the +* invalidation counter even in the absence of an actual VNCR TLB +* invalidation, as this could indicate that the guest has gone +* through a BBM sequence. +*/ + kvm->mmu_invalidate_seq++; +smp_wmb (); +kvm_for_each_vncr_tlb (i, vcpu, vt, kvm) {switch (scope->type) {case TLBI_ALL :
@@ -1421,15 +1436,15 @@ static int kvm_translate_vncr(struct kvm va =read_vncr_el2 (vcpu); + mmu_seq = vcpu->kvm->mmu_invalidate_seq; +smp_rmb (); + ret =__kvm_translate_va (vcpu, &vt->wi, &vt->wr, va);if (ret)return ret; write_fault =kvm_is_write_fault (vcpu); - mmu_seq = vcpu->kvm->mmu_invalidate_seq; -smp_rmb (); - gfn = vt->wr.pa >>PAGE_SHIFT ; memslot =gfn_to_memslot (vcpu->kvm, gfn);if (!memslot) {
Greg Kroah-Hartman
maintainerPATCH 319/556 KVM: arm64: Remove VM-wide VNCR mapping counter
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Marc Zyngier <[email protected]>
commit c55bc773b6e814406658fae7dc5c15f639ed816e upstream.
The global VNCR mapping counter is used to decide whether an L1 provided VNCR page is mapped in L0 on any CPU at the point of dealing with a TLB invalidation. It is incremented when a mapping is made in the fixmap, and decremented when unmapped.
As it turns out, this tracking has several flaws:
- we are trying to invalidate TLBs, and the mapping is only an opportunistic consequence of the TLB. Checking this counter to decide whether a TLB needs to be invalidated may result in missed invalidations.
- an L1 vcpu invalidating its own TLB (a very likely case) will not succeed in invalidating the VNCR pseudo TLB because that page is not mapped in L0 at this stage.
Given that this tracking fails at delivering the minimum guarantees that are required and is only a performance optimisation, remove it completely.
--- arch/arm64/include/asm/kvm_host.h | 3 --- arch/arm64/kvm/hyp/vhe/switch.c | 3 +-- arch/arm64/kvm/nested.c | 3 --- 3 files changed, 1 insertion(+), 8 deletions(-)
arch/arm64/include/asm/kvm_host.h +0 -3
@@ -411,9 +411,6 @@ struct kvm_arch {/* Masks for VNCR-backed and general EL2 sysregs */ struct kvm_sysreg_masks *sysreg_masks; -/* Count the number of VNCR_EL2 currently mapped */ -atomic_t vncr_map_count; -/* * For an untrusted host VM, 'pkvm.handle' is used to lookup * the associated pKVM instance in the hypervisor.
arch/arm64/kvm/hyp/vhe/switch.c +1 -2
@@ -427,8 +427,7 @@ static bool kvm_hyp_handle_tlbi_el2(stru* If we have to check for any VNCR mapping being invalidated, * go back to the slow path for further processing. */ -if (vcpu_el2_e2h_is_set (vcpu) &&vcpu_el2_tge_is_set (vcpu) && -atomic_read (&vcpu->kvm->arch.vncr_map_count)) +if (vcpu_el2_e2h_is_set (vcpu) &&vcpu_el2_tge_is_set (vcpu))return false;__kvm_skip_instr (vcpu);
arch/arm64/kvm/nested.c +0 -3
@@ -48,7 +48,6 @@ void kvm_init_nested(struct kvm *kvm) { kvm->arch.nested_mmus =NULL ; kvm->arch.nested_mmus_size =0 ; -atomic_set (&kvm->arch.vncr_map_count,0 ); }static int init_nested_s2_mmu (struct kvm *kvm,struct kvm_s2_mmu *mmu)
@@ -930,7 +929,6 @@ static void this_cpu_reset_vncr_fixmap(sif (unmap_l1_vncr (vcpu->arch.vncr_tlb) ==-1 )clear_fixmap (vncr_fixmap (smp_processor_id ()));host_data_clear_flag (L1_VNCR_MAPPED ); -atomic_dec (&vcpu->kvm->arch.vncr_map_count); }void kvm_vcpu_put_hw_mmu (struct kvm_vcpu *vcpu)
@@ -1640,7 +1638,6 @@ static void kvm_map_l1_vncr(struct kvm_vatomic_set (&vt->cpu,smp_processor_id ());__set_fixmap (vncr_fixmap (atomic_read (&vt->cpu)), vt->hpa, prot);host_data_set_flag (L1_VNCR_MAPPED ); -atomic_inc (&vcpu->kvm->arch.vncr_map_count); } }
Greg Kroah-Hartman
maintainerPATCH 320/556 KVM: arm64: Sign-extend VA for range-based TLBI invalidation
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Marc Zyngier <[email protected]>
commit 2393470085649f0b973ecceb26fe8fc71edde0c1 upstream.
When the decode_range_tlbi() helper was moved to be used for S1 TLBIs, the required sign extension was omitted. Add it.
As a result, special care must be taken to not overflow PA bits when this is used for S2 invalidation.
--- arch/arm64/include/asm/kvm_nested.h | 7 +++++++ arch/arm64/kvm/sys_regs.c | 11 +++++++++++ 2 files changed, 18 insertions(+)
arch/arm64/include/asm/kvm_nested.h +7 -0
@@ -291,6 +291,13 @@ static inline u64 decode_range_tlbi(u64 base = (val &GENMASK (36 ,0 )) << shift; +/* +* We only deal with at most 48bit VA/IPA, so 48 is where we +* sign-extend from. Should we support FEAT_L{VP}A* at some point, +* this will need to be revisited. +*/ + base = (u64 )sign_extend64 (base,48 ); +if (asid) *asid =FIELD_GET (TLBIR_ASID_MASK , val);
arch/arm64/kvm/sys_regs.c +11 -0
@@ -4057,6 +4057,7 @@ static bool handle_ripas2e1is(struct kvmu32 sys_encoding =sys_insn (p->Op0, p->Op1, p->CRn, p->CRm, p->Op2);u64 vttbr =vcpu_read_sys_reg (vcpu,VTTBR_EL2 );u64 base, range; +int pa_bits;if (!kvm_supported_tlbi_ipas2_op (vcpu, sys_encoding))return undef_access (vcpu, p, r);
@@ -4068,6 +4069,16 @@ static bool handle_ripas2e1is(struct kvm*/ base =decode_range_tlbi (p->regval, &range,NULL ); +/* +* Ignore TLBIs that start out of PA_bits range, and cap the +* invalidation to the [base:bit(PA_bits)] interval. +*/ + pa_bits =kvm_get_pa_bits (vcpu->kvm); +if (fls64 (base) > pa_bits) +return true; + + range =min (range,BIT_ULL (pa_bits) - base); + kvm_s2_mmu_iterate_by_vmid(vcpu->kvm, get_vmid(vttbr), &(union tlbi_info) { .range = {
Greg Kroah-Hartman
maintainerPATCH 321/556 KVM: arm64: vgic-v3: take an LPI reference in vgic_v3_save_pending_tables
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Qihang <[email protected]>
commit f5b8f203bfc07a5a257dff859e66d2c500f9f509 upstream.
vgic_v3_save_pending_tables() iterates dist->lpi_xa using xa_for_each() and dereferences the returned struct vgic_irq in the loop body without holding a reference on the LPI.
The xarray iterator only provides temporary RCU coverage while looking up the current entry. That is not sufficient for this loop body, which reads fields from struct vgic_irq and performs guest memory accesses before the iteration completes.
A concurrent path can trigger this race: the irqfd cached injection path (vgic_its_inject_cached_translation) obtains a transient LPI reference via vgic_its_check_cache() without holding kvm->lock, vcpu->mutex, config_lock, or its_lock. If guest ITS DISCARD then drops the cache and ITE references under its_lock, the transient inject reference may become the final one. When vgic_put_irq() drops it, the LPI is erased from lpi_xa and freed via kfree_rcu(). Meanwhile, vgic_v3_save_pending_tables() may still hold a stale pointer obtained from the xarray iterator and dereference it after the RCU grace period completes.
Fix this by re-fetching each iterated LPI via vgic_get_irq(), which takes a stable reference, and dropping it with vgic_put_irq() on all paths. This matches the pattern already used by other lpi_xa iterators in the vgic ITS code.
--- arch/arm64/kvm/vgic/vgic-v3.c | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-)
arch/arm64/kvm/vgic/vgic-v3.c +9 -3
@@ -617,9 +617,13 @@ int vgic_v3_save_pending_tables(struct kbool is_pending;bool stored; + irq =vgic_get_irq (kvm, index); +if (!irq) +continue ; + vcpu = irq->target_vcpu;if (!vcpu) -continue ; + goto put_irq; pendbase =GICR_PENDBASER_ADDRESS (vcpu->arch.vgic_cpu.pendbaser);
@@ -630,7 +634,7 @@ int vgic_v3_save_pending_tables(struct kif (ptr != last_ptr) { ret =kvm_read_guest_lock (kvm, ptr, &val,1 );if (ret) - goto out; + goto put_irq; last_ptr = ptr; }
@@ -642,7 +646,7 @@ int vgic_v3_save_pending_tables(struct kvgic_v4_get_vlpi_state (irq, &is_pending);if (stored == is_pending) -continue ; + goto put_irq;if (is_pending) val |=1 << bit_nr;
@@ -650,6 +654,8 @@ int vgic_v3_save_pending_tables(struct k val &= ~(1 << bit_nr); ret =vgic_write_guest_lock (kvm, ptr, &val,1 ); +put_irq: +vgic_put_irq (kvm, irq);if (ret) goto out; }
Greg Kroah-Hartman
maintainerPATCH 322/556 KVM: arm64: vgic: Fix detection of MI on no pending LR
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Kajetan Puchalski <[email protected]>
commit a342faadc5acbd5d9fd894fd4499d4fd614dfcf6 upstream.
As per the ARM GICv3 spec, the maintenance interrupt identified by ICH_MISR_EL2.NP is asserted when it is enabled and no List register is in pending state. This is further described in the document as "no List registers with the State field set to 0b01 (pending)". By checking only the pending bit of the LR (bit 62), KVM currently asserts the MI when there are no LRs in "pending" or "pending and active" states. Fix the detection logic to consider only the "pending" state.
--- arch/arm64/kvm/vgic/vgic-v3-nested.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
arch/arm64/kvm/vgic/vgic-v3-nested.c +1 -1
@@ -152,7 +152,7 @@ static void vgic_compute_mi_state(struct eisr |=BIT (i);if (!(lr &ICH_LR_STATE )) elrsr |=BIT (i); - pend |= (lr &ICH_LR_PENDING_BIT ); + pend |= (lr &ICH_LR_STATE ) ==ICH_LR_PENDING_BIT ; } mi_state->eisr = eisr;
Greg Kroah-Hartman
maintainerPATCH 323/556 KVM: arm64: vgic: Reset in_kernel on private IRQ allocation failure
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Fuad Tabba <[email protected]>
commit 43347154e7ab642474c886bc54ad090166c0d9c9 upstream.
kvm_vgic_create() sets vgic.in_kernel before allocating the per-vCPU private IRQs, but the allocation-failure path resets only vgic_model and leaves in_kernel set. As irqchip_in_kernel() is !!in_kernel, the VM is left with an in-kernel irqchip but no model, and the -EEXIST guard at the top of kvm_vgic_create() rejects every retry, so userspace cannot recover from a transient -ENOMEM.
Reset in_kernel alongside vgic_model on the failure path.
--- arch/arm64/kvm/vgic/vgic-init.c | 1 + 1 file changed, 1 insertion(+)
arch/arm64/kvm/vgic/vgic-init.c +1 -0
@@ -176,6 +176,7 @@ int kvm_vgic_create(struct kvm *kvm, u32 } kvm->arch.vgic.vgic_model =0 ; + kvm->arch.vgic.in_kernel = false; goto out_unlock; }
Greg Kroah-Hartman
maintainerPATCH 324/556 KVM: arm64: vgic-its: Dont dereference a NULL collection on ITT save
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Fuad Tabba <[email protected]>
commit c6c156d931c33b92362383cf76f6d6e1291dcbfe upstream.
MAPC with V=0 drops ite->collection but leaves the ITE on the device's ITT list, and vgic_its_save_ite() dereferences it unconditionally. A guest that issues MAPD, MAPTI and then MAPC(V=0) therefore oopses the host when the VMM issues KVM_DEV_ARM_ITS_SAVE_TABLES to migrate it. That sequence is UNPREDICTABLE per the architecture, but KVM already handles the resulting state in the translate, MOVI and DISCARD paths.
Save a zeroed entry, which vgic_its_restore_ite() reads back as invalid. Skipping the ITE instead would leave the ITT slot holding whatever is in guest memory, and restore rejects an entry naming a collection the restored collection table does not have.
--- arch/arm64/kvm/vgic/vgic-its.c | 8 ++++++++ 1 file changed, 8 insertions(+)
arch/arm64/kvm/vgic/vgic-its.c +8 -0
@@ -2119,6 +2119,14 @@ static int vgic_its_save_ite(struct vgicu32 next_offset;u64 val; +/* +* MAPC with V=0 keeps the ITEs mapped but drops their collection, +* and with it the ICID. Save a zeroed entry, which the restore path +* reads back as invalid. +*/ +if (!ite->collection) +return vgic_its_write_entry_lock (its, gpa,0ULL , ite); + next_offset =compute_next_eventid_offset (&dev->itt_head, ite); val = ((u64 )next_offset <<KVM_ITS_ITE_NEXT_SHIFT ) | ((u64)ite->irq->intid << KVM_ITS_ITE_PINTID_SHIFT) |
Greg Kroah-Hartman
maintainerPATCH 325/556 KVM: arm64: Correctly cap TLBI Range to the architural limit
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Marc Zyngier <[email protected]>
commit 69a598288195947a1662b53de702eb6976af96b7 upstream.
TLB Invalidation by Range has a fairly powerful way of encoding pretty large ranges in a small number of bits. This range can be based on an arbitrary VA, which means it is pretty easy for a guest to generate an overflow should the hypervisor be naive enough to add the range to the base...
Make sure the range is capped to the limit dictated by the address bit that determines the VA range. For an IPA invalidation, this is further corrected down the line to ignore the upper range.
--- arch/arm64/include/asm/kvm_nested.h | 6 ++++++ 1 file changed, 6 insertions(+)
arch/arm64/include/asm/kvm_nested.h +6 -0
@@ -305,6 +305,12 @@ static inline u64 decode_range_tlbi(u64 num =FIELD_GET (GENMASK (43 ,39 ), val); *range =__TLBI_RANGE_PAGES (num, scale) << shift; +/* Cap the range to the correct half of the address space */ +if (!(base &BIT (48 ))) + *range =min (*range, (BIT (48 ) - base)); +else + *range =min (*range, ~base +1 ); +return base; }
Greg Kroah-Hartman
maintainerPATCH 326/556 LoongArch: KVM: Set vcpu->cpu before IN_GUEST_MODE is set
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Bibo Mao <[email protected]>
commit 32d05564a6128d59ea876cf9078fe6866a809e14 upstream.
In function kvm_make_vcpu_request(), it will send IPI to physical CPU when vCPU is in IN_GUEST_MODE mode. And physical CPU is set in function kvm_check_vpid(), thus it should be called before IN_GUEST_MODE is set. Otherwise IPI will send to wrong old physical CPU where vCPU is running.
--- arch/loongarch/kvm/vcpu.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
arch/loongarch/kvm/vcpu.c +1 -1
@@ -300,10 +300,10 @@ static int kvm_pre_enter_guest(struct kv*/ local_irq_disable ();kvm_deliver_exception (vcpu); +kvm_check_vpid (vcpu);/* Make sure the vcpu mode has been written */ smp_store_mb (vcpu->mode,IN_GUEST_MODE );kvm_deliver_intr (vcpu); -kvm_check_vpid (vcpu);/* * Called after function kvm_check_vpid()
Greg Kroah-Hartman
maintainerPATCH 327/556 LoongArch: KVM: Fix uninitialized stack variable issue with dmsintc
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Bibo Mao <[email protected]>
commit 81aa3a58b542ed88819115c80a17acd86eacb89d upstream.
Variable vector[] is declared on stack in function dmsintc_inject_irq() and sometimes it is used without initialized. Here fix this issue.
--- arch/loongarch/kvm/intc/dmsintc.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-)
arch/loongarch/kvm/intc/dmsintc.c +1 -2
@@ -19,8 +19,7 @@ void dmsintc_inject_irq(struct kvm_vcpufor (i =0 ; i <4 ; i++) { old =atomic64_read (&(ds->vector_map[i])); -if (old) - vector[i] =atomic64_xchg (&(ds->vector_map[i]),0 ); + vector[i] = old ?atomic64_xchg (&(ds->vector_map[i]),0 ) :0 ; }if (vector[0 ]) {
Greg Kroah-Hartman
maintainerPATCH 328/556 LoongArch: KVM: Fix PC double advance in kernel MMIO read fast path
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Zeng Chi <[email protected]>
commit fd4021529faa931818186b6e83bd46f5de7517eb upstream.
In the in-kernel MMIO read fast path of kvm_emu_mmio_read(), kvm_complete_mmio_read() already advances the guest PC via update_pc(). The explicit update_pc() call right after it advances the PC a second time, so PC moves forward by 8 bytes instead of 4, and the instruction following the MMIO read is silently skipped.
The user space MMIO read completion path in kvm_arch_vcpu_ioctl_run() calls kvm_complete_mmio_read() only once, and the MMIO write fast path advances the PC exactly once as well.
Here remove the redundant update_pc() so the kernel MMIO read fast path advances the PC by a single instruction.
--- arch/loongarch/kvm/exit.c | 1 - 1 file changed, 1 deletion(-)
arch/loongarch/kvm/exit.c +0 -1
@@ -481,7 +481,6 @@ int kvm_emu_mmio_read(struct kvm_vcpu *vsrcu_read_unlock (&vcpu->kvm->srcu, idx);if (!ret) {kvm_complete_mmio_read (vcpu, run); -update_pc (&vcpu->arch); vcpu->mmio_needed =0 ;return EMULATE_DONE ; }
Greg Kroah-Hartman
maintainerPATCH 329/556 LoongArch: KVM: Add unregister helpers for the KVM interrupt devices
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chaithanya Lagisetty <[email protected]>
commit 4af22177032ab2357bf551fbfcdebc8fd9f2502d upstream.
The IPI/EIOINTC/PCH-PIC/DMSINTC KVM devices each have a helper that registers their kvm_device_ops, but there is no counterpart to remove them, so a caller that needs to undo a registration has to open-code kvm_unregister_device_ops() with the matching device type.
Add kvm_loongarch_unregister_{ipi,eiointc,pch_pic,dmsintc}_device() next to the existing register helpers. kvm_unregister_device_ops() is a no-op when the corresponding device type is not currently registered.
No functional change, as there are no callers yet.
--- arch/loongarch/include/asm/kvm_dmsintc.h | 1 + arch/loongarch/include/asm/kvm_eiointc.h | 1 + arch/loongarch/include/asm/kvm_ipi.h | 1 + arch/loongarch/include/asm/kvm_pch_pic.h | 1 + arch/loongarch/kvm/intc/dmsintc.c | 5 +++++ arch/loongarch/kvm/intc/eiointc.c | 5 +++++ arch/loongarch/kvm/intc/ipi.c | 5 +++++ arch/loongarch/kvm/intc/pch_pic.c | 5 +++++ 8 files changed, 24 insertions(+)
arch/loongarch/include/asm/kvm_dmsintc.h +1 -0
@@ -20,6 +20,7 @@ struct dmsintc_state { };int kvm_loongarch_register_dmsintc_device (void ); +void kvm_loongarch_unregister_dmsintc_device (void );void dmsintc_inject_irq (struct kvm_vcpu *vcpu);int dmsintc_set_irq (struct kvm *kvm,u64 addr,int data,int level);int dmsintc_deliver_msi_to_vcpu (struct kvm *kvm,struct kvm_vcpu *vcpu,u32 vector,int level);
arch/loongarch/include/asm/kvm_eiointc.h +1 -0
@@ -79,6 +79,7 @@ struct loongarch_eiointc { };int kvm_loongarch_register_eiointc_device (void ); +void kvm_loongarch_unregister_eiointc_device (void );void eiointc_set_irq (struct loongarch_eiointc *s,int irq,int level);#endif /* __ASM_KVM_EIOINTC_H */
arch/loongarch/include/asm/kvm_ipi.h +1 -0
@@ -41,5 +41,6 @@ struct ipi_state {#define IOCSR_ANY_SEND 0x158int kvm_loongarch_register_ipi_device (void ); +void kvm_loongarch_unregister_ipi_device (void );#endif
arch/loongarch/include/asm/kvm_pch_pic.h +1 -0
@@ -70,6 +70,7 @@ struct loongarch_pch_pic {struct kvm_kernel_irq_routing_entry ;int kvm_loongarch_register_pch_pic_device (void ); +void kvm_loongarch_unregister_pch_pic_device (void );void pch_pic_set_irq (struct loongarch_pch_pic *s,int irq,int level);int pch_msi_set_irq (struct kvm *kvm,struct kvm_kernel_irq_routing_entry *e,int level);
arch/loongarch/kvm/intc/dmsintc.c +5 -0
@@ -179,3 +179,8 @@ int kvm_loongarch_register_dmsintc_devic {return kvm_register_device_ops (&kvm_dmsintc_dev_ops,KVM_DEV_TYPE_LOONGARCH_DMSINTC ); } + +void kvm_loongarch_unregister_dmsintc_device (void ) +{ +kvm_unregister_device_ops (KVM_DEV_TYPE_LOONGARCH_DMSINTC ); +}
arch/loongarch/kvm/intc/eiointc.c +5 -0
@@ -691,3 +691,8 @@ int kvm_loongarch_register_eiointc_devic {return kvm_register_device_ops (&kvm_eiointc_dev_ops,KVM_DEV_TYPE_LOONGARCH_EIOINTC ); } + +void kvm_loongarch_unregister_eiointc_device (void ) +{ +kvm_unregister_device_ops (KVM_DEV_TYPE_LOONGARCH_EIOINTC ); +}
arch/loongarch/kvm/intc/ipi.c +5 -0
@@ -466,3 +466,8 @@ int kvm_loongarch_register_ipi_device(vo {return kvm_register_device_ops (&kvm_ipi_dev_ops,KVM_DEV_TYPE_LOONGARCH_IPI ); } + +void kvm_loongarch_unregister_ipi_device (void ) +{ +kvm_unregister_device_ops (KVM_DEV_TYPE_LOONGARCH_IPI ); +}
arch/loongarch/kvm/intc/pch_pic.c +5 -0
@@ -500,3 +500,8 @@ int kvm_loongarch_register_pch_pic_devic {return kvm_register_device_ops (&kvm_pch_pic_dev_ops,KVM_DEV_TYPE_LOONGARCH_PCHPIC ); } + +void kvm_loongarch_unregister_pch_pic_device (void ) +{ +kvm_unregister_device_ops (KVM_DEV_TYPE_LOONGARCH_PCHPIC ); +}
Greg Kroah-Hartman
maintainerPATCH 330/556 LoongArch: KVM: Fix resource leak in kvm_loongarch_env_init() error path
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chaithanya Lagisetty <[email protected]>
commit 910132bc7d72f26a8b288c2a38c32445a48d5be0 upstream.
kvm_loongarch_env_init() allocates the per-CPU kvm_context (vmcs) and kvm_loongarch_ops, registers the perf callbacks, and then registers the IPI/EIOINTC/PCH-PIC/DMSINTC KVM devices. If any of those device registrations fails, the function returned the error directly, leaving everything acquired so far in place: vmcs and kvm_loongarch_ops are never freed, the perf callbacks stay registered, and all previously registered KVM device operations remain registered. kvm_loongarch_init() propagates the errors without calling kvm_loongarch_env_exit(), so nothing else cleans up either.
Unwind the error path in reverse order of registration, so that each failure only undoes what had actually been set up. Use the same helpers in kvm_loongarch_env_exit() to remove the device registrations during normal teardown as well.
--- arch/loongarch/kvm/main.c | 33 +++++++++++++++++++++++++++++---- 1 file changed, 29 insertions(+), 4 deletions(-)
arch/loongarch/kvm/main.c +29 -4
@@ -385,27 +385,52 @@ static int kvm_loongarch_env_init(void)/* Register LoongArch IPI interrupt controller interface. */ ret =kvm_loongarch_register_ipi_device ();if (ret) -return ret; + goto err_env;/* Register LoongArch EIOINTC interrupt controller interface. */ ret =kvm_loongarch_register_eiointc_device ();if (ret) -return ret; + goto err_ipi;/* Register LoongArch PCH-PIC interrupt controller interface. */ ret =kvm_loongarch_register_pch_pic_device ();if (ret) -return ret; + goto err_eiointc;/* Register LoongArch DMSINTC interrupt contrroller interface */ -if (cpu_has_msgint) +if (cpu_has_msgint) { ret =kvm_loongarch_register_dmsintc_device (); +if (ret) + goto err_pch_pic; + } + +return 0 ; + +err_pch_pic: +kvm_loongarch_unregister_pch_pic_device (); +err_eiointc: +kvm_loongarch_unregister_eiointc_device (); +err_ipi: +kvm_loongarch_unregister_ipi_device (); +err_env: +kvm_unregister_perf_callbacks (); +kfree (kvm_loongarch_ops); + kvm_loongarch_ops =NULL ; +free_percpu (vmcs); + vmcs =NULL ;return ret; }static void kvm_loongarch_env_exit (void ) { +if (cpu_has_msgint) +kvm_loongarch_unregister_dmsintc_device (); + +kvm_loongarch_unregister_pch_pic_device (); +kvm_loongarch_unregister_eiointc_device (); +kvm_loongarch_unregister_ipi_device (); +if (vmcs)free_percpu (vmcs);
Greg Kroah-Hartman
maintainerPATCH 331/556 LoongArch: KVM: Fix TOCTOU race on pv_features
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Tao Cui <[email protected]>
commit 9296375902579f9b0e456bbb76e5cf179e5a4e0b upstream.
In kvm_loongarch_cpucfg_set_attr() the check-then-set on kvm->arch.pv_features is lockless, so two vCPUs can race past the validation and set different values. Add a spinlock to protect it.
--- arch/loongarch/include/asm/kvm_host.h | 1 + arch/loongarch/kvm/vcpu.c | 6 +++++- arch/loongarch/kvm/vm.c | 1 + 3 files changed, 7 insertions(+), 1 deletion(-)
arch/loongarch/include/asm/kvm_host.h +1 -0
@@ -125,6 +125,7 @@ struct kvm_arch {unsigned int pte_shifts[MAX_PGTABLE_LEVELS ];unsigned int root_level;spinlock_t phyid_map_lock; +spinlock_t pv_setting_lock;struct kvm_phyid_map *phyid_map;/* Enabled PV features */ unsigned long pv_features;
arch/loongarch/kvm/vcpu.c +5 -1
@@ -1165,10 +1165,14 @@ static int kvm_loongarch_cpucfg_set_attrreturn -EINVAL ;/* All vCPUs need set the same PV features */ +spin_lock (&kvm->arch.pv_setting_lock);if ((kvm->arch.pv_features &LOONGARCH_PV_FEAT_UPDATED ) - && ((kvm->arch.pv_features & valid) != val)) + && ((kvm->arch.pv_features & valid) != val)) { +spin_unlock (&kvm->arch.pv_setting_lock);return -EINVAL ; + } kvm->arch.pv_features = val |LOONGARCH_PV_FEAT_UPDATED ; +spin_unlock (&kvm->arch.pv_setting_lock);return 0 ;default :return -ENXIO ;
arch/loongarch/kvm/vm.c +1 -0
@@ -76,6 +76,7 @@ int kvm_arch_init_vm(struct kvm *kvm, unreturn -ENOMEM ; }spin_lock_init (&kvm->arch.phyid_map_lock); +spin_lock_init (&kvm->arch.pv_setting_lock);kvm_init_vmcs (kvm);kvm_vm_init_features (kvm);
Greg Kroah-Hartman
maintainerPATCH 332/556 LoongArch: KVM: Free init resources if kvm_init() fails
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Chaithanya Lagisetty <[email protected]>
commit f7a1064cce3b100b54780c68529176232d8eb01e upstream.
kvm_loongarch_init() calls kvm_loongarch_env_init() to allocate the per-CPU kvm_context (vmcs) and kvm_loongarch_ops and to register the perf callbacks, and then calls kvm_init(). If kvm_init() fails its result is returned directly, but since module_init() does not run the module_exit() stuff on failure, so kvm_loongarch_env_exit() is never called and those resources are leaked.
So call kvm_loongarch_env_exit() when kvm_init() fails, matching the teardown-on-failure pattern used by riscv_kvm_init().
--- arch/loongarch/kvm/main.c | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-)
arch/loongarch/kvm/main.c +5 -1
@@ -453,7 +453,11 @@ static int kvm_loongarch_init(void)if (r)return r; -return kvm_init (sizeof (struct kvm_vcpu ),0 ,THIS_MODULE ); + r =kvm_init (sizeof (struct kvm_vcpu ),0 ,THIS_MODULE ); +if (r) +kvm_loongarch_env_exit (); + +return r; }static void kvm_loongarch_exit (void )
Greg Kroah-Hartman
maintainerPATCH 333/556 LoongArch: KVM: Preserve memslot arch flags on KVM_MR_FLAGS_ONLY
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Zeng Chi <[email protected]>
commit 27a9bfee3bbcb3cabb77797354f07e0e44e49831 upstream.
kvm_arch_prepare_memory_region() computes new->arch.flags, i.e. whether a memslot is KVM_MEM_HUGEPAGE_CAPABLE or KVM_MEM_HUGEPAGE_INCAPABLE, only for KVM_MR_CREATE and KVM_MR_MOVE, and returns early for every other change. But the generic code allocates a zeroed memslot for every change and never copies old->arch, so after a KVM_MR_FLAGS_ONLY update, e.g. toggling KVM_MEM_LOG_DIRTY_PAGES for live migration, the active memslot has arch.flags == 0.
With both flags clear, fault_supports_huge_mapping() falls through to the alignment check on the HVA range alone, which no longer verifies that the GPA and HVA have the same offset within a PMD. A memslot that was marked KVM_MEM_HUGEPAGE_INCAPABLE because of a GPA/HVA offset mismatch can then be mapped with PMD entries on read faults, and since kvm_map_page() aligns the gfn and the pfn independently, the guest ends up accessing the wrong host pages, exactly the "d -> f, e -> g" case described in the comment above the check.
Carry the arch flags over from the old memslot for KVM_MR_FLAGS_ONLY, as the GPA, HVA and size are guaranteed to be unchanged for that case.
--- arch/loongarch/kvm/mmu.c | 10 ++++++++++ 1 file changed, 10 insertions(+)
arch/loongarch/kvm/mmu.c +10 -0
@@ -383,6 +383,16 @@ int kvm_arch_prepare_memory_region(struchva_t hva_start;size_t size, gpa_offset, hva_offset; +/* +* The generic code allocates a fresh, zeroed memslot for every change, +* so the arch flags computed below must be carried over when only the +* userspace flags change, e.g. when dirty logging is toggled. +*/ +if (change ==KVM_MR_FLAGS_ONLY ) { + new->arch = old->arch; +return 0 ; + } +if ((change !=KVM_MR_MOVE ) && (change !=KVM_MR_CREATE ))return 0 ;/*
Greg Kroah-Hartman
maintainerPATCH 334/556 LoongArch: KVM: Validate MSI data before routing it to EIOINTC
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Zeng Chi <[email protected]>
commit 501514d6ebd2111c353a1296f25dbe22fbd64657 upstream.
pch_msi_set_irq() passes e->msi.data straight into eiointc_set_irq() as the irq number. The MSI data comes from userspace, that either via a KVM_IRQ_ROUTING_MSI entry set with KVM_SET_GSI_ROUTING (used by irqfd and KVM_IRQ_LINE) or directly via KVM_SIGNAL_MSI, and is never checked against EIOINTC_IRQS.
eiointc_set_irq() uses the value with __set_bit()/__clear_bit() on the 256-bit isr bitmap, eiointc_update_irq() then indexes sw_coremap[] and the per-cpu coreisr/sw_coreisr bitmaps with it. Therefore a data value
Quoted 1 line
= 256 reads and writes memory past the end of those arrays, i.e. any
process holding a VM fd can corrupt kernel memory beyond the allocation of loongarch_eiointc.
Reject MSI data that doesn't fit in the EIOINTC irq space. The DMSINTC path is unaffected as it decodes the vector from the address and masks it.
--- arch/loongarch/kvm/intc/pch_pic.c | 3 +++ 1 file changed, 3 insertions(+)
arch/loongarch/kvm/intc/pch_pic.c +3 -0
@@ -78,6 +78,9 @@ int pch_msi_set_irq(struct kvm *kvm, strreturn dmsintc_set_irq (kvm, msg_addr, e->msi.data, level); } +if (e->msi.data >=EIOINTC_IRQS ) +return -EINVAL ; +eiointc_set_irq (kvm->arch.eiointc, e->msi.data, level);return 0 ;
Greg Kroah-Hartman
maintainerPATCH 335/556 LoongArch: Add DIRECT_MAP_PHYSMEM_END definition
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Han Gao <[email protected]>
commit 2677f97a67fdbc62a82ce1faa67791f54451d36f upstream.
get_free_mem_region() and mhp_get_pluggable_range() bound their search to DIRECT_MAP_PHYSMEM_END. LoongArch does not define it, so the fallback in include/linux/mm.h applies: under CONFIG_SPARSEMEM_VMEMMAP it is (1ULL << MAX_PHYSMEM_BITS) - 1, a compile-time constant that does not adapt to the CPU's physical address space bits (cpu_pabits, probed from CPUCFG1).
The vmemmap window only covers physical space below 2^(cpu_pabits+1) (i.e. VMEMMAP_SIZE), so on CPUs with fewer physical address bits than MAX_PHYSMEM_BITS the fallback allows get_free_mem_region() to return a ZONE_DEVICE region outside the vmemmap window; vmemmap_populate() then wraps the memmap range around and maps it into low memory, silently corrupting the page tables. The same search also picked the top-of- address-space region that crashed memmap_init_zone_device() with amdkfd on Loongson-3C6000 in 6.16 [1]; the commit 2969b42c8f99 ("LoongArch/mm:
align vmemmap to maximal folio size") keeps that region in bounds on current Loongson-3C6000 configs, but CPUs with smaller cpu_pabits (e.g. the Loongson-2K series) are still affected.
Define DIRECT_MAP_PHYSMEM_END as the vmemmap-covered physical range, (1ULL << (cpu_pabits + 1)) - 1, capped at (1ULL << MAX_PHYSMEM_BITS) - 1 under CONFIG_SPARSEMEM, similar to the commit f3336b48cf9d ("riscv: mm:
Define DIRECT_MAP_PHYSMEM_END").
[1] https://lore.kernel.org/amd-gfx/[email protected]/
--- arch/loongarch/include/asm/pgtable.h | 7 +++++++ 1 file changed, 7 insertions(+)
arch/loongarch/include/asm/pgtable.h +7 -0
@@ -125,6 +125,13 @@ struct vm_area_struct;#endif +/* Needed to limit get_free_mem_region() */ +#ifndef CONFIG_SPARSEMEM +#define DIRECT_MAP_PHYSMEM_END ((1ULL << (cpu_pabits + 1)) - 1) +#else +#define DIRECT_MAP_PHYSMEM_END min((1ULL << (cpu_pabits + 1)) - 1, (1ULL << MAX_PHYSMEM_BITS) - 1) +#endif +#define ptep_get (ptep) READ_ONCE(*(ptep))#define pmdp_get (pmdp) READ_ONCE(*(pmdp))
Greg Kroah-Hartman
maintainerPATCH 336/556 LoongArch: BPF: Optimize redundant TCC loads in epilogue
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Tiezhu Yang <[email protected]>
commit fd3cb1bfeb9d98618bd709bfee9c1133e9f189e6 upstream.
The legacy epilogue implementation pops the tail call counter (TCC) context via a redundant double-load pattern. It first decrements the load_offset by 2 slots to fetch 'tcc_ptr', and then immediately bumps it back up by 1 slot to load the original 'tcc' value into REG_TCC, unnecessarily overwriting the register.
Optimize this sequence by adjusting the load_offset by only 1 slot. This aligns the offset directly with the higher stack slot containing the entry TCC counter (or caller state), allowing us to restore the REG_TCC register safely with a single load.
This removes one redundant instruction from the epilogue hot path, improves code readability, and ensures the correct TCC register context is handed back cleanly upon normal return.
--- arch/loongarch/net/bpf_jit.c | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-)
arch/loongarch/net/bpf_jit.c +2 -8
@@ -246,14 +246,8 @@ static void __build_epilogue(struct jit_emit_insn (ctx, ldd,REG_ARENA ,LOONGARCH_GPR_SP , load_offset); } -/* -* When push into the stack, follow the order of tcc then tcc_ptr. -* When pop from the stack, first pop tcc_ptr then followed by tcc. -*/ - load_offset -=2 *sizeof (long ); -emit_insn (ctx, ldd,REG_TCC ,LOONGARCH_GPR_SP , load_offset); - - load_offset +=sizeof (long ); +/* Only restore the TCC state into REG_TCC from the higher slot */ + load_offset -=sizeof (long );emit_insn (ctx, ldd,REG_TCC ,LOONGARCH_GPR_SP , load_offset);emit_insn (ctx, addid,LOONGARCH_GPR_SP ,LOONGARCH_GPR_SP , stack_adjust);
Greg Kroah-Hartman
maintainerPATCH 337/556 LoongArch: BPF: Refactor jump offset calculation in tail call
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Tiezhu Yang <[email protected]>
commit 37d545d12f21c4d50612ecaebd7ae1e5bf91b2d8 upstream.
The old macro-based jmp_offset calculation derives the jump distance from a stale prior-pass code stride, which can lead to wrong branch offsets and soft lockups under extra JIT passes.
Fix this by calculating the offset directly on the absolute target:
"ctx->offset[insn + 1] - ctx->idx".
To avoid a false 16-bit range check abort during size estimation, add a "ctx->image == NULL" guard to inject a safe dummy offset.
--- arch/loongarch/net/bpf_jit.c | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-)
arch/loongarch/net/bpf_jit.c +4 -8
@@ -284,17 +284,13 @@ bool bpf_jit_supports_far_kfunc_call(voistatic int emit_bpf_tail_call (struct jit_ctx *ctx,int insn) { -int off, tc_ninsn =0 ; +int off, jmp_offset;int tcc_ptr_off =BPF_TAIL_CALL_CNT_PTR_STACK_OFF (ctx->stack_size);u8 a1 =LOONGARCH_GPR_A1 ;u8 a2 =LOONGARCH_GPR_A2 ;u8 t1 =LOONGARCH_GPR_T1 ;u8 t2 =LOONGARCH_GPR_T2 ;u8 t3 =LOONGARCH_GPR_T3 ; -const int idx0 = ctx->idx; - -#define cur_offset (ctx->idx - idx0) -#define jmp_offset (tc_ninsn - (cur_offset))/* * a0: &ctx
@@ -304,12 +300,12 @@ static int emit_bpf_tail_call(struct jit* if (index >= array->map.max_entries) * goto out; */ - tc_ninsn = insn ? ctx->offset[insn+1 ] - ctx->offset[insn] : ctx->offset[0 ];emit_zext_32 (ctx, a2, true); off = offsetof(struct bpf_array, map.max_entries);emit_insn (ctx, ldwu, t1, a1, off);/* bgeu $a2, $t1, jmp_offset */ + jmp_offset = ctx->image ? (ctx->offset[insn +1 ] - ctx->idx) :0 ;if (emit_tailcall_jmp (ctx,BPF_JGE , a2, t1, jmp_offset) <0 ) goto toofar;
@@ -320,6 +316,7 @@ static int emit_bpf_tail_call(struct jitemit_insn (ctx, ldd,REG_TCC ,LOONGARCH_GPR_SP , tcc_ptr_off);emit_insn (ctx, ldd, t3,REG_TCC ,0 );emit_insn (ctx, addid, t2,LOONGARCH_GPR_ZERO ,MAX_TAIL_CALL_CNT ); + jmp_offset = ctx->image ? (ctx->offset[insn +1 ] - ctx->idx) :0 ;if (emit_tailcall_jmp (ctx,BPF_JSGE , t3, t2, jmp_offset) <0 ) goto toofar;
@@ -334,6 +331,7 @@ static int emit_bpf_tail_call(struct jit off = offsetof(struct bpf_array , ptrs);emit_insn (ctx, ldd, t2, t2, off);/* beq $t2, $zero, jmp_offset */ + jmp_offset = ctx->image ? (ctx->offset[insn +1 ] - ctx->idx) :0 ;if (emit_tailcall_jmp (ctx,BPF_JEQ , t2,LOONGARCH_GPR_ZERO , jmp_offset) <0 ) goto toofar;
@@ -349,8 +347,6 @@ static int emit_bpf_tail_call(struct jit toofar:pr_info_once ("tail_call: jump too far\n" );return -1 ; -#undef cur_offset -#undef jmp_offset }static void emit_store_stack_imm64 (struct jit_ctx *ctx,int reg,int stack_off,u64 imm64)
Greg Kroah-Hartman
maintainerPATCH 338/556 LoongArch: Expand module virtual address space to 2GB
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Tiezhu Yang <[email protected]>
commit 18210a104bb97e28c26dc31fd9fc7b5c381fec62 upstream.
The current 256MB module virtual address space is easily exhausted when loading massive graphics drivers such as amdgpu along with the large unstripped symbol tables, resulting in allocation failures of "execmem:
unable to allocate memory".
Thus, expand the module virtual address space to 2GB while keeping the current normal code model '-mcmodel=normal', rather than using the medium code model '-mcmodel=medium'. This approach avoids the extra performance overhead and larger binary size of forcing every function call into a 2-instruction sequence of 'pcaddu18i + jirl'.
Given that individual module code segments rarely exceed 128MB, most jumps remain fast direct calls by using the bl instruction. For the long-distance jumps exceeding the +/-128MB limit, apply_r_larch_b26() emits PLT entries, while signed_imm_check() guarantees the run-time safety by rejecting any out-of-bound instruction offsets.
There is still a risk that the distance between .init.text and .text of the same module exceeds 128MB. So we divide the 2GB virtual space to be two sub-regions: the first 256MB is for module text, and the rest is for module data.
--- arch/loongarch/include/asm/pgtable.h | 2 +- arch/loongarch/mm/init.c | 17 ++++++++++++++--- 2 files changed, 15 insertions(+), 4 deletions(-)
arch/loongarch/include/asm/pgtable.h +1 -1
@@ -96,7 +96,7 @@ struct vm_area_struct;#ifdef CONFIG_64BIT #define MODULES_VADDR (vm_map_base + PCI_IOSIZE + (2 * PAGE_SIZE)) -#define MODULES_END (MODULES_VADDR + SZ_256M) +#define MODULES_END (MODULES_VADDR + SZ_2G)/* 256MB for text, rest for data */ #ifdef CONFIG_KFENCE #define KFENCE_AREA_SIZE (((CONFIG_KFENCE_NUM_OBJECTS + 1) * 2 + 2) * PAGE_SIZE)
arch/loongarch/mm/init.c +14 -3
@@ -237,15 +237,26 @@ pte_t invalid_pte_table[PTRS_PER_PTE] __EXPORT_SYMBOL (invalid_pte_table);#if defined(CONFIG_EXECMEM ) && defined(MODULES_VADDR ) +#define MODULES_TEXT_START (MODULES_VADDR) +#define MODULES_TEXT_END (MODULES_VADDR + SZ_256M) +#define MODULES_DATA_START (MODULES_VADDR + SZ_256M) +#define MODULES_DATA_END (MODULES_END) +static struct execmem_info execmem_info__ro_after_init ;struct execmem_info __init *execmem_arch_setup (void ) { execmem_info = (struct execmem_info ){ .ranges = { - [EXECMEM_DEFAULT ] = { - .start =MODULES_VADDR , - .end =MODULES_END , + [EXECMEM_MODULE_TEXT ] = { + .start =MODULES_TEXT_START , + .end =MODULES_TEXT_END , + .pgprot =PAGE_KERNEL , + .alignment =1 , + }, + [EXECMEM_MODULE_DATA ] = { + .start =MODULES_DATA_START , + .end =MODULES_DATA_END , .pgprot =PAGE_KERNEL , .alignment =1 , },
Greg Kroah-Hartman
maintainerPATCH 339/556 LoongArch: BPF: Move arena register slot below TCC context
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Tiezhu Yang <[email protected]>
commit cd7e356b07a27e91394838cf3fb655862b519294 upstream.
Currently, the stack layout places the optional arena register slot above the tail call counter context. When arena_vm_start is dynamically enabled, it shifts the relative offset of the tcc_ptr slot within the stack frame, causing hardcoded tracking macros to mismatch and leading to memory misalignment or corruption potentially.
To fix this, move the arena register save and restore sequences below the tail call counter context slots in both build_prologue() and the epilogue.
Update __build_epilogue() to insert a proper offset decrement to safely skip the unneeded tcc_ptr reading block while accurately aligning with the relocated arena slot at the very bottom.
With this patch, the tcc_ptr slot is always positioned at a fixed distance directly underneath the base callee-saved registers that is independent of whether the arena features are on.
--- arch/loongarch/net/bpf_jit.c | 20 +++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-)
arch/loongarch/net/bpf_jit.c +13 -7
@@ -124,6 +124,9 @@ static void prepare_bpf_tail_call_cnt(struct jit_ctx *ctx, int *store_offset)* | tcc | * +-------------------------+ * | tcc_ptr | +* +-------------------------+ +* | arena | +* | (optional) | * +-------------------------+ <--BPF_REG_FP * | prog->aux->stack_depth | * | (optional) |
@@ -145,7 +148,7 @@ static void build_prologue(struct jit_ctx *ctx) stack_adjust +=sizeof (long ) *2 ;if (ctx->arena_vm_start) - stack_adjust +=8 ; + stack_adjust +=sizeof (long ); stack_adjust =round_up (stack_adjust,16 ); stack_adjust += bpf_stack_adjust;
@@ -194,13 +197,13 @@ static void build_prologue(struct jit_ctx *ctx) store_offset -=sizeof (long );emit_insn (ctx, std,LOONGARCH_GPR_S5 ,LOONGARCH_GPR_SP , store_offset); +prepare_bpf_tail_call_cnt (ctx, &store_offset); +if (ctx->arena_vm_start) { store_offset -=sizeof (long );emit_insn (ctx, std,REG_ARENA ,LOONGARCH_GPR_SP , store_offset); } -prepare_bpf_tail_call_cnt (ctx, &store_offset); -emit_insn (ctx, addid,LOONGARCH_GPR_FP ,LOONGARCH_GPR_SP , stack_adjust);if (bpf_stack_adjust)
@@ -241,15 +244,18 @@ static void __build_epilogue(struct jit_ctx *ctx, bool is_tail_call) load_offset -=sizeof (long );emit_insn (ctx, ldd,LOONGARCH_GPR_S5 ,LOONGARCH_GPR_SP , load_offset); +/* Only restore the TCC state into REG_TCC from the higher slot */ + load_offset -=sizeof (long ); +emit_insn (ctx, ldd,REG_TCC ,LOONGARCH_GPR_SP , load_offset); + +/* Skip the unused local 'tcc_ptr' slot to align with arena */ + load_offset -=sizeof (long ); +if (ctx->arena_vm_start) { load_offset -=sizeof (long );emit_insn (ctx, ldd,REG_ARENA ,LOONGARCH_GPR_SP , load_offset); } -/* Only restore the TCC state into REG_TCC from the higher slot */ - load_offset -=sizeof (long ); -emit_insn (ctx, ldd,REG_TCC ,LOONGARCH_GPR_SP , load_offset); -emit_insn (ctx, addid,LOONGARCH_GPR_SP ,LOONGARCH_GPR_SP , stack_adjust);if (!is_tail_call) {
Signature · 1 line
2.55.0
Greg Kroah-Hartman
maintainerPATCH 340/556 LoongArch: BPF: Fix off-by-one error for insn_is_cast_user()
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Tiezhu Yang <[email protected]>
commit 30419a0aa128135a81be917eaa3bd2f1a10c9ca3 upstream.
In the LoongArch BPF JIT code, the branch offset represents the number of instructions. An offset of 1 means the target of the "beq" is the current PC plus 1 instruction (PC + 4 bytes). This matches the exact same path as the sequential non-branch execution, the "or" instruction is always executed for the cast_user JIT arm in build_insn().
If the pointer is not NULL, there is no side effect. But if the pointer is NULL, it is incorrectly combined with the base address and turns into a non-zero address, meaning a zero arena offset no longer casts to NULL.
Fix this by changing the branch offset from 1 to 2, which properly skips the "or" instruction and jumps directly to the "move_reg" instruction if the pointer is NULL, ensuring the destination register is safely cleared to 0.
--- arch/loongarch/net/bpf_jit.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
arch/loongarch/net/bpf_jit.c +1 -1
@@ -734,7 +734,7 @@ static int build_insn(const struct bpf_imove_reg (ctx, t1, src);emit_zext_32 (ctx, t1, true);move_imm (ctx, dst, (ctx->user_vm_start >>32 ) <<32 , false); -emit_insn (ctx, beq, t1,LOONGARCH_GPR_ZERO ,1 ); +emit_insn (ctx, beq, t1,LOONGARCH_GPR_ZERO ,2 );emit_insn (ctx, or, t1, dst, t1);move_reg (ctx, dst, t1);break ;
Greg Kroah-Hartman
maintainerPATCH 341/556 LoongArch: Fix acpi_package_ids[] array overflow
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Bibo Mao <[email protected]>
commit 2a2367d46d7a4ee4122b7a86e57125542dbbe963 upstream.
With LoongArch virt machine, a typical setting is one core per socket, there will max 256 sockets (packages) on one VM. With PPTT acpi table, array acpi_package_ids[] will be overflowed.
Here change the array size of acpi_package_ids[] with the max value of MAX_PACKAGES and KVM_MAX_VCPUS.
--- arch/loongarch/kernel/acpi.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
arch/loongarch/kernel/acpi.c +2 -1
@@ -13,6 +13,7 @@#include <linux/export.h> #include <linux/irq.h> #include <linux/irqdomain.h> +#include <linux/kvm_host.h> #include <linux/memblock.h> #include <linux/of_fdt.h> #include <linux/serial_core.h>
@@ -202,7 +203,7 @@ static void __init acpi_process_madt(voiint pptt_enabled;static int acpi_nr_packages; -static int acpi_package_ids[MAX_PACKAGES ]; +static int acpi_package_ids[MAX (MAX_PACKAGES ,KVM_MAX_VCPUS )];int __init parse_acpi_topology (void ) {
Greg Kroah-Hartman
maintainerPATCH 342/556 LoongArch: Do not select HAVE_RUST when KASAN is enabled
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Nathan Chancellor <[email protected]>
commit 63b6a48c951d63bf39d44603ada48a987ccf66eb upstream.
After commit 2625480a1bf7 ("hardening: Default randstruct off with rust for better allmodconfig support"), which allows Rust to be enabled for allmodconfig, ARCH=loongarch allmodconfig starts failing with:
error: kernel-address sanitizer is not supported for this target
error: aborting due to 1 previous error
make[4]: *** [rust/Makefile:741: rust/core.o] Error 1
For the same reason as the commit 84a0f7caafc679f7 ("ARM: Do not select HAVE_RUST when KASAN is enabled"), do not select HAVE_RUST when KASAN is enabled until the loongarch64-unknown-none-softfloat target in rustc supports KASAN.
--- arch/loongarch/Kconfig | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
arch/loongarch/Kconfig +1 -1
@@ -175,7 +175,7 @@ config LOONGARCH select HAVE_RELIABLE_STACKTRACE if UNWINDER_ORC select HAVE_RETHOOK select HAVE_RSEQ - select HAVE_RUST + select HAVE_RUST if !KASAN select HAVE_SAMPLE_FTRACE_DIRECT select HAVE_SAMPLE_FTRACE_DIRECT_MULTI select HAVE_SETUP_PER_CPU_AREA if NUMA
Greg Kroah-Hartman
maintainerPATCH 343/556 LoongArch: Do not save/restore percpu base register in rethook trampoline
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Wentao Guan <[email protected]>
commit c3f2feace5e4f4b01b68b9f947b19adb4155c32e upstream.
The rethook trampoline saves $r21 ($u0), the percpu base, into its frame at entry and restores it at exit. Inbetween rethook_trampoline_handler() may schedule via preempt_enable_notrace().
If the task migrates to another CPU, the frame's $r21 holds the old CPU's percpu base, and restoring it poisons $r21 on the new CPU. Until the next user->kernel transition heals $r21, all this_cpu_*() accesses (runqueues, RCU per-CPU data, timer tick programming, FPU ownership) hit the wrong CPU's percpu area.
Under kretprobe-heavy preemptible load this can corrupt scheduler and timer state: scheduling-while-atomic splats, wrong-CPU RCU warnings, WARN_ON_ONCE(rq != this_rq()) in nohz_balance_exit_idle(), and CPUs parking in the idle loop with the constant timer never re-armed (hard lockup). Reproduces on a Loongson-3A6000 with kretprobes on VFS paths plus heavy file churn (OS install / unsquashfs).
By convention $r21 always holds the current CPU's percpu base in kernel
mode: SAVE_SOME() at exception entry reloads it only when coming from user mode, and RESTORE_SOME() restores it only when returning to user mode; the context-switch path never writes it. Therefore the live $r21 at trampoline exit is already correct, and nothing inbetween can change it legitimately (kernel C code cannot write a global register variable). The same flaw existed even in the pre-rethook kretprobe trampoline since v6.3; it was carried over when rethook replaced it. Drop both the save and the restore here. Drop the restore is enough to solve the issue, and drop the save is to keep the code tidy and no need to clear it.
--- arch/loongarch/kernel/rethook_trampoline.S | 2 -- 1 file changed, 2 deletions(-)
arch/loongarch/kernel/rethook_trampoline.S +0 -2
@@ -24,7 +24,6 @@ cfi_st t6, PT_R18 cfi_st t7, PT_R19 cfi_st t8, PT_R20 - cfi_st u0, PT_R21 cfi_st fp, PT_R22 cfi_st s0, PT_R23 cfi_st s1, PT_R24
@@ -59,7 +58,6 @@ cfi_ld t6, PT_R18 cfi_ld t7, PT_R19 cfi_ld t8, PT_R20 - cfi_ld u0, PT_R21 cfi_ld fp, PT_R22 cfi_ld s0, PT_R23 cfi_ld s1, PT_R24
Greg Kroah-Hartman
maintainerPATCH 344/556 LoongArch: Avoid preempt count underflow without probe
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jérémy Jean <[email protected]>
commit 72ce4b24676e8b3b75376c4c559dd81c1ac52d5a upstream.
LoongArch uses break 11 for the breakpoint placed after an instruction that Kprobes executes out of line. Since userspace can issue the same break instruction, do_bp() can reach kprobe_singlestep_handler() when there is no current probe.
The handler actually returns false in this case, but it first calls preempt_enable_no_resched(). The corresponding preempt_disable() is done by kprobe_breakpoint_handler() on a real Kprobe hit, so it has not run here. As a result, an ordinary userspace breakpoint (code 11) underflows the current task's preempt count.
This also makes in_interrupt() return true until the task schedules. One visible consequence is the socket cgroup attribution: cgroup_sk_alloc() treats the allocation as interrupt context and assigns the socket to the root cgroup. A socket opened from the SIGTRAP handler can then avoid a BPF_CGROUP_INET_SOCK_CREATE policy attached to the task's own cgroup.
Return as soon as kprobe_running() reports no active probe.
The same check has appeared in [PATCH v10 2/4] of the original LoongArch Kprobes series, but was dropped before the feature reached mainline.
--- arch/loongarch/kernel/kprobes.c | 3 +++ 1 file changed, 3 insertions(+)
arch/loongarch/kernel/kprobes.c +3 -0
@@ -275,6 +275,9 @@ bool kprobe_singlestep_handler(struct ptstruct kprobe_ctlblk *kcb =get_kprobe_ctlblk ();unsigned long addr =instruction_pointer (regs); +if (!cur) +return false; +if (cur && (kcb->kprobe_status & (KPROBE_HIT_SS |KPROBE_REENTER )) && ((unsigned long )&cur->ainsn.insn[1 ] == addr)) {restore_local_irqflag (kcb, regs);
Greg Kroah-Hartman
maintainerPATCH 345/556 rust: drm: ioctl: fix unbounded lifetimes in ioctl handler arguments
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Danilo Krummrich <[email protected]>
commit 68b151bc6145dea3db5598ebaf4b776cd205e395 upstream.
References to dev, data, and file in the declare_drm_ioctls! macro are created via unsafe pointer dereferences, producing unbounded lifetimes. If an ioctl handler explicitly annotates its parameters with 'static, the compiler accepts this, allowing the handler to stash references that outlive the ioctl call.
Fix this by adding a higher-ranked function pointer coercion that enforces the handler accepts universally quantified lifetimes:
let _: for<'a> fn(&'a _, &'a mut _, &'a _) -> _ = $func;
Since the handler must be coercible to a function pointer accepting any lifetime 'a, it can no longer demand 'static on any parameter.
--- rust/kernel/drm/ioctl.rs | 6 ++++++ 1 file changed, 6 insertions(+)
rust/kernel/drm/ioctl.rs +6 -0
@@ -135,6 +135,12 @@ macro_rules! declare_drm_ioctls {// dev/file match the current driver these ioctls are being declared // for, and it's not clear how to enforce this within the type system. let dev = $crate::drm::device::Device ::from_raw (raw_dev); + +// Enforce that the handler accepts higher-ranked +// lifetimes, preventing it from requiring 'static +// references that could escape this scope. +let _:for <'a>fn (&'a_ , &'amut _ , &'a_ ) ->_ = $func; +// SAFETY: The ioctl argument has size `_IOC_SIZE(cmd)`, which we // asserted above matches the size of this type, and all bit patterns of // UAPI structs must be valid.
Greg Kroah-Hartman
maintainerPATCH 346/556 media: airspy: use vb2_video_unregister_device() on disconnect to fix NULL deref
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Valery Borovsky <[email protected]>
commit 2f378dc45e685fc825d2dd08e7864666d6fcc009 upstream.
airspy_disconnect() clears s->udev under v4l2_lock, but airspy_stop_streaming() unconditionally calls airspy_ctrl_msg() and airspy_free_stream_bufs() afterwards. If a streaming user closes the device after disconnect, stop_streaming() runs and dereferences the NULL s->udev:
airspy_stop_streaming()
airspy_ctrl_msg(s, CMD_RECEIVER_MODE, 0, 0, NULL, 0)
usb_sndctrlpipe(s->udev, 0) /* NULL deref */
airspy_free_stream_bufs(s)
usb_free_coherent(s->udev, ...) /* NULL deref */The airspy driver uses vb2_fop_release() in its file_operations, so replace video_unregister_device(&s->vdev) with vb2_video_unregister_device(&s->vdev) and move it before clearing s->udev. vb2_video_unregister_device() releases the vb2 queue, which synchronously runs airspy_stop_streaming() if streaming is active, so the URBs, coherent DMA stream buffers and the hardware stop control message all execute while s->udev is still valid.
vb2_video_unregister_device() locks vdev->queue->lock (vb_queue_lock) internally, and stop_streaming() locks v4l2_lock, so the previous outer mutex_lock(&s->vb_queue_lock) / mutex_lock(&s->v4l2_lock) pair around the unregister sequence would self-deadlock and has been removed. A short v4l2_lock critical section around s->udev = NULL remains so any ioctl path that still holds the file descriptor sees coherent state.
Issue identified by automated review of the INV-003 series at
https://sashiko.dev/
--- drivers/media/usb/airspy/airspy.c | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-)
drivers/media/usb/airspy/airspy.c +12 -5
@@ -464,14 +464,21 @@ static void airspy_disconnect(struct usbdev_dbg (s->dev,"\n" ); -mutex_lock (&s->vb_queue_lock); +/* +* vb2_video_unregister_device() releases the vb2 queue, which +* triggers airspy_stop_streaming() if streaming is active. +* stop_streaming() dereferences s->udev via airspy_ctrl_msg() and +* airspy_free_stream_bufs(), so it must run before s->udev is +* cleared. vb2_video_unregister_device() locks vb_queue_lock +* internally and stop_streaming() locks v4l2_lock, so neither may +* be held by the caller. +*/ +v4l2_device_disconnect (&s->v4l2_dev); +vb2_video_unregister_device (&s->vdev); +mutex_lock (&s->v4l2_lock); -/* No need to keep the urbs around after disconnection */ s->udev =NULL ; -v4l2_device_disconnect (&s->v4l2_dev); -video_unregister_device (&s->vdev);mutex_unlock (&s->v4l2_lock); -mutex_unlock (&s->vb_queue_lock);v4l2_device_put (&s->v4l2_dev); }
Greg Kroah-Hartman
maintainerPATCH 347/556 media: amphion: Remove obsolete frame_count check in venc_start_session
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Ming Qian <[email protected]>
commit 2be6ee86385badab95b1bace984735bde6e0fec0 upstream.
The dev_err() log warning about no input when starting was originally meaningful when min_queued_buffers was set, as it indicated an abnormal condition. However, since commit 5633ec763a2a ("media: amphion: Drop min_queued_buffers assignment") removed the min_queued_buffers assignment, having frame_count == 0 at start is a normal condition.
Remove this misleading log that no longer serves any purpose.
--- drivers/media/platform/amphion/venc.c | 2 -- 1 file changed, 2 deletions(-)
drivers/media/platform/amphion/venc.c +0 -2
@@ -973,8 +973,6 @@ static int venc_start_session(struct vpu venc->ready_count =0 ; venc->stopped = false;vpu_process_output_buffer (inst); -if (venc->frame_count ==0 ) -dev_err (inst->dev,"[%d] there is no input when starting\n" , inst->id);return 0 ; error:
Greg Kroah-Hartman
maintainerPATCH 348/556 media: bcm2835-unicam: Fix pipeline wrong validation for unpacked formats
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Eugen Hristev <[email protected]>
commit 4f26c8345dbfa92f19078c788be1b9bfd425ed60 upstream.
The commit08f9794d9b79 ("media: bcm2835-unicam: Fix RGB format / mbus code association") introduced a check to see whether the format requested is the same as the fourcc in the format list.
However, this breaks the case when userspace requested an unpacked fourcc, e.g. RG10.
Unicam can work with or without unpacking pixels, e.g. pRAA or RG10, depending on what userspace requests.
In the unpacking case, a dedicated register is being set.
If the userspace requests pRAA, this works, because the check validates the pipeline:
v4l2-ctl -d /dev/video0 --set-fmt-video=width=3280,height=2464,pixelformat=pRAA \
--stream-mmap --stream-count=1 --stream-to=frame.raw
but, with
v4l2-ctl -d /dev/video0 --set-fmt-video=width=3280,height=2464,pixelformat=RG10 \
--stream-mmap --stream-count=1 --stream-to=frame.raw
unicam complains at validation level:
image: format mismatch: 0x300f <=> RG10 little-endian (0x30314752)
This should work, because MEDIA_BUS_FMT_SRGGB10_1X10 can be packed into either RG10 or pRAA depending on the packing register.
To fix this, modified the condition check to also allow in the case when requested format (fmt->pixelformat) is equal to fmtinfo->unpacked_fourcc.
--- drivers/media/platform/broadcom/bcm2835-unicam.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/media/platform/broadcom/bcm2835-unicam.c +2 -1
@@ -2158,7 +2158,8 @@ static int unicam_video_link_validate(st* In order to allow the applications using the old behaviour to * run, let's accept the old combination, but warn about it. */ -if (fmtinfo->fourcc != fmt->pixelformat) { +if (fmt->pixelformat != fmtinfo->fourcc && + fmt->pixelformat != fmtinfo->unpacked_fourcc) { if ((fmt->pixelformat == V4L2_PIX_FMT_BGR24 && format->code == MEDIA_BUS_FMT_BGR888_1X24) || (fmt->pixelformat == V4L2_PIX_FMT_RGB24 &&
Greg Kroah-Hartman
maintainerPATCH 349/556 media: cec: core: Fix kmemleak due to missed rc_free_device() call
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jonas Karlman <[email protected]>
commit a24ba0653f7154e671dc8d2bf64682ab2d042792 upstream.
The commit dccc0c3ddf8f ("media: rc: fix race between unregister and urb/irq callbacks") removed the implicit call to rc_free_device() from rc_unregister_device(). However, the commit missed to remove the NULL assignment of adap->rc that is now causing rc_free_device() to never be called on an allocated rc device.
kmemleak reports following after e.g. dw-hdmi unbind:
unreferenced object 0xffff00010ac10000 (size 4096):
comm "kworker/u16:1", pid 39, jiffies 4294897739 hex dump (first 32 bytes):
20 23 4b 0a 01 00 ff ff 08 00 c1 0a 01 00 ff ff #K.............
08 00 c1 0a 01 00 ff ff 00 00 00 00 00 00 00 00 ................
backtrace (crc e11baccc):
kmemleak_alloc+0x38/0x44
__kmalloc_cache_noprof+0x4a8/0x5e0
rc_allocate_device+0x48/0x2a0
cec_allocate_adapter+0x3ac/0x800
dw_hdmi_cec_probe+0x264/0x634
platform_probe+0xc0/0x188
really_probe+0x4a4/0x8e0
__driver_probe_device+0x2f8/0x440
driver_probe_device+0x60/0x160
__device_attach_driver+0x1a0/0x2a0
bus_for_each_drv+0x100/0x1a0
__device_attach+0x174/0x350
device_initial_probe+0x90/0xb0
bus_probe_device+0x4c/0x120
device_add+0xdec/0x116c
platform_device_add+0x354/0x598Remove the assignment of adap->rc to NULL to let cec_delete_adapter() free the allocated rc device after last user of the cec device exits to fix the kmemleak.
--- drivers/media/cec/core/cec-core.c | 2 -- 1 file changed, 2 deletions(-)
drivers/media/cec/core/cec-core.c +0 -2
@@ -371,9 +371,7 @@ void cec_unregister_adapter(struct cec_areturn ;#ifdef CONFIG_MEDIA_CEC_RC -/* Note: rc_unregister also calls rc_free */ rc_unregister_device (adap->rc); - adap->rc =NULL ;#endif debugfs_remove_recursive (adap->cec_dir);#ifdef CONFIG_CEC_NOTIFIER
Greg Kroah-Hartman
maintainerPATCH 350/556 media: cec: disable delayed work before freeing an interrupted transmit
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Biren Pandya <[email protected]>
commit 0fbd5c2327020858c45b2d1c65775d64cdeca523 upstream.
cec_transmit_msg_fh() drops adap->lock to wait for a blocking transmit in wait_for_completion_killable(). If that wait is interrupted by a signal, cancel_delayed_work_sync() can run before the CEC kthread arms the reply timeout via schedule_delayed_work(&data->work) in cec_transmit_done_ts(). The work is then armed after the cancel, and the data is freed with its delayed_work still pending:
ODEBUG: free active (active state 0) object: ... hint: cec_wait_timeout
Use disable_delayed_work_sync(): it cancels the work and disables it, so the later schedule_delayed_work() becomes a no-op and the work cannot be re-armed. The data is freed right after, so it need not be re-enabled.
--- drivers/media/cec/core/cec-adap.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/media/cec/core/cec-adap.c +1 -1
@@ -965,7 +965,7 @@ int cec_transmit_msg_fh(struct cec_adapt*/ mutex_unlock (&adap->lock); err =wait_for_completion_killable (&data->c); -cancel_delayed_work_sync (&data->work); +disable_delayed_work_sync (&data->work);mutex_lock (&adap->lock);if (err)
Greg Kroah-Hartman
maintainerPATCH 351/556 media: cec: extron-da-hd-4k-plus: add sanity check
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Hans Verkuil <[email protected]>
commit abac9820b26b5cfcb01eb79efe2abdd0ac7e07c3 upstream.
Add check to prevent overflowing msg.msg[] in case the incoming data is malformed.
--- drivers/media/cec/usb/extron-da-hd-4k-plus/extron-da-hd-4k-plus.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/media/cec/usb/extron-da-hd-4k-plus/extron-da-hd-4k-plus.c +2 -1
@@ -657,7 +657,8 @@ static void extron_process_received(struif (!port || port->disconnected)return ; -if (len <5 || (len -2 ) %3 || data[len -2 ] !='*' ) +if (len <5 || ((len -2 ) /3 >sizeof (msg.msg)) || + (len -2 ) %3 || data[len -2 ] !='*' ) goto malformed;while (*data !='*' ) {
Greg Kroah-Hartman
maintainerPATCH 352/556 media: cec: meson: ao-cec-g12a: name the CEC core regmap to avoid debugfs clash
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Yi Ding <[email protected]>
commit 172c5a7d81deb922ddedd1bc920751c7fed6c43c upstream.
The driver registers two regmaps on the same platform device: an MMIO regmap for the AO CEC registers, and an indirect regmap (using reg_read()/reg_write() callbacks) for the CEC controller core registers. Neither regmap_config sets a .name, so both default their debugfs directory to the device name and collide:
debugfs: 'ff800280.cec' already exists in 'regmap'
Because of the clash the second regmap's debugfs directory fails to register, so its registers can no longer be inspected via debugfs.
Give the indirect CEC core regmap a distinct name. The two debugfs directories then become "<dev>.cec" and "<dev>.cec-core". This only affects debugfs naming; register access is unchanged.
Tested on an ODROID-N2 (Amlogic S922X): the warning is gone and both /sys/kernel/debug/regmap/ff800280.cec and ff800280.cec-core are present.
--- drivers/media/cec/platform/meson/ao-cec-g12a.c | 1 + 1 file changed, 1 insertion(+)
drivers/media/cec/platform/meson/ao-cec-g12a.c +1 -0
@@ -405,6 +405,7 @@ static int meson_ao_cec_g12a_write(void }static const struct regmap_config meson_ao_cec_g12a_cec_regmap_conf = { + .name ="core" , .reg_bits =8 , .val_bits =8 , .reg_read = meson_ao_cec_g12a_read,
Greg Kroah-Hartman
maintainerPATCH 353/556 media: cec: Serialize exclusive follower delivery
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Ruoyu Wang <[email protected]>
commit 1924d0788caa6c66fd320dd4704fae99487fd2c7 upstream.
cec_receive_notify() reads the exclusive follower pointer without the adapter lock. Serialize the no-follower check and message delivery against mode changes and release.
--- drivers/media/cec/core/cec-adap.c | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-)
drivers/media/cec/core/cec-adap.c +7 -1
@@ -2219,9 +2219,13 @@ static int cec_receive_notify(struct cec* Unprocessed messages are aborted if userspace isn't doing * any processing either. */ +mutex_lock (&adap->lock);if (!is_broadcast && !is_reply && !adap->follower_cnt && - !adap->cec_follower && msg->msg[1 ] !=CEC_MSG_FEATURE_ABORT ) + !adap->cec_follower && msg->msg[1 ] !=CEC_MSG_FEATURE_ABORT ) { +mutex_unlock (&adap->lock);return cec_feature_abort (adap, msg); + } +mutex_unlock (&adap->lock);break ; }
@@ -2234,10 +2238,12 @@ skip_processing:* Send to the exclusive follower if there is one, otherwise send * to all followers. */ +mutex_lock (&adap->lock);if (adap->cec_follower)cec_queue_msg_fh (adap->cec_follower, msg);else cec_queue_msg_followers (adap, msg); +mutex_unlock (&adap->lock);return 0 ; }
Greg Kroah-Hartman
maintainerPATCH 354/556 media: cedrus: fix memory leak in cedrus_init_ctrls()
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Dawei Feng <[email protected]>
commit 9df2fbe563194da1967a5db083442186c1323efe upstream.
In cedrus_init_ctrls(), the V4L2 control handler is initialized before allocating memory for ctx->ctrls. If this allocation fails, the function returns -ENOMEM without freeing the previously allocated handler resources, leading to a memory leak.
Fix this by calling v4l2_ctrl_handler_free() on the ctx->ctrls allocation failure path.
The bug was first flagged by an experimental analysis tool we are developing for kernel memory-management bugs while analyzing v6.13-rc1. The tool is still under development and is not yet publicly available. Manual inspection confirms that the bug is still present in v7.1.1.
An x86_64 allyesconfig build showed no new warnings. As we do not have an Allwinner SoC or board with a Cedrus VPU available to test with, no runtime testing was able to be performed.
--- drivers/staging/media/sunxi/cedrus/cedrus.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-)
drivers/staging/media/sunxi/cedrus/cedrus.c +3 -1
@@ -285,8 +285,10 @@ static int cedrus_init_ctrls(struct cedr ctrl_size =sizeof (ctrl) *CEDRUS_CONTROLS_COUNT +1 ; ctx->ctrls =kzalloc (ctrl_size,GFP_KERNEL ); -if (!ctx->ctrls) +if (!ctx->ctrls) { +v4l2_ctrl_handler_free (hdl);return -ENOMEM ; + } j =0 ;for (i =0 ; i <CEDRUS_CONTROLS_COUNT ; i++) {
Greg Kroah-Hartman
maintainerPATCH 355/556 media: cobalt: Avoid freeing ALSA private data twice
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Ruoyu Wang <[email protected]>
commit 3a7d6b9c4cb5ac18cbd3f1c7f8c7b159c42ba0b1 upstream.
snd_cobalt_card_create() stores cobsc in sc->private_data and installs snd_cobalt_card_private_free() as sc->private_free. From that point, snd_card_free(sc) releases cobsc through the ALSA card cleanup path.
If cobalt_alsa_init() fails after snd_cobalt_card_create(), the err_exit_free path calls snd_card_free(sc) and then kfree(cobsc). That second free releases the same object again.
Remove the explicit kfree(cobsc) and leave ownership with the ALSA card.
This issue was found by a static analysis checker and confirmed by manual source review.
--- drivers/media/pci/cobalt/cobalt-alsa-main.c | 1 - 1 file changed, 1 deletion(-)
drivers/media/pci/cobalt/cobalt-alsa-main.c +0 -1
@@ -135,7 +135,6 @@ int cobalt_alsa_init(struct cobalt_strea err_exit_free:if (sc !=NULL )snd_card_free (sc); -kfree (cobsc); err_exit:return ret; }
Greg Kroah-Hartman
maintainerPATCH 356/556 media: cx231xx: reject geometry changes while the VBI queue is busy
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Bryam Vargas <[email protected]>
commit 627a121c15fe05a541f44d86016294b80bada75d upstream.
vidioc_s_fmt_vid_cap() and vidioc_s_std() change the device-wide dev->width / dev->norm but only refuse the change when the *video* queue (dev->vidq) is busy. The VBI queue (dev->vbiq) shares that same geometry:cx231xx_init_vbi_isoc() latches dma_q->lines_per_field from dev->norm, the VBI videobuf2 plane is sized from dev->width / dev->norm in vbi_queue_setup() and vbi_buf_prepare(), and cx231xx_do_vbi_copy() then recomputes the destination offset from the *live* dev->width and the latched lines_per_field on every URB completion:
offset = lines_completed * (dev->width << 1) + ...; if (dma_q->current_field == 2) offset += dev->width * 2 * dma_q->lines_per_field; memcpy(plane + offset, p_buffer, lencopy);
Because the VBI node shares video_ioctl_ops with the video node, an application can size a small VBI plane (REQBUFS/QBUF with a small width, or with the NTSC standard), then enlarge dev->width (or switch dev->norm to PAL) through the video node while the VBI stream is running -- the change is allowed because only dev->vidq is checked -- and let the device deliver a field-2 VBI payload. cx231xx_do_vbi_copy() now computes the offset with the larger geometry and memcpy()s past the end of the smaller plane that was already allocated, a heap out-of-bounds write whose offset is attacker-chosen and whose contents come from the device. The per-field guard in cx231xx_copy_vbi_line() does not help: it bounds the copy against the latched lines_per_field, not the plane's real capacity, and vb2 does not re-run buf_prepare() for an already prepared buffer.
Refuse the format/standard change when the VBI queue is busy as well, so the geometry cannot change underneath an allocated VBI buffer.
--- drivers/media/usb/cx231xx/cx231xx-video.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
drivers/media/usb/cx231xx/cx231xx-video.c +2 -2
@@ -898,7 +898,7 @@ static int vidioc_s_fmt_vid_cap(struct fif (rc)return rc; -if (vb2_is_busy (&dev->vidq)) { +if (vb2_is_busy (&dev->vidq) ||vb2_is_busy (&dev->vbiq)) {dev_err (dev->dev,"%s: queue busy\n" , __func__);return -EBUSY ; }
@@ -933,7 +933,7 @@ static int vidioc_s_std(struct file *filif (dev->norm == norm)return 0 ; -if (vb2_is_busy (&dev->vidq)) +if (vb2_is_busy (&dev->vidq) ||vb2_is_busy (&dev->vbiq))return -EBUSY ; dev->norm = norm;
Greg Kroah-Hartman
maintainerPATCH 357/556 media: cx23885: cancel NetUP CI work before teardown
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Fan Wu <[email protected]>
commit 4e143d662ca94888b494b2427fc9e34494eb933a upstream.
netup_ci_exit() frees a netup_ci_state while its work item, netup_read_ci_status(), may still be pending or running on the system workqueue. The worker obtains the state with container_of() and dereferences it, so it must not outlive the state.
netup_ci_init() queues the initial status read, and CI GPIO interrupts subsequently queue the same work from netup_ci_slot_status(). During remove, cx23885_finidev() calls free_irq() before the CI device is unregistered. free_irq() prevents further IRQ handlers from running, but does not drain work queued previously, so the worker can run after netup_ci_exit() frees the state.
Call cancel_work_sync() before dvb_ca_en50221_release() and kfree().
This issue was found by an in-house static analysis tool.
--- drivers/media/pci/cx23885/cimax2.c | 1 + 1 file changed, 1 insertion(+)
drivers/media/pci/cx23885/cimax2.c +1 -0
@@ -528,6 +528,7 @@ void netup_ci_exit(struct cx23885_tsportif (NULL == state->ca.data)return ; +cancel_work_sync (&state->work);dvb_ca_en50221_release (&state->ca);kfree (state); }
Greg Kroah-Hartman
maintainerPATCH 358/556 media: dt-bindings: nxp,imx8-isi: Drop fsl,blk-ctrl requirement for i.MX8ULP
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Guoniu Zhou <[email protected]>
commit fc312f830d8df6c082bd6f7250aa5c0ff063eea4 upstream.
The i.MX8ULP variant does not require the fsl,blk-ctrl property. Add fsl,imx8ulp-isi to the exception list alongside fsl,imx91-isi.
--- Documentation/devicetree/bindings/media/nxp,imx8-isi.yaml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-)
Documentation/devicetree/bindings/media/nxp,imx8-isi.yaml +3 -1
@@ -117,7 +117,9 @@ allOf: compatible: not: contains: - const: fsl,imx91-isi + enum: + - fsl,imx8ulp-isi + - fsl,imx91-isi then: required: - fsl,blk-ctrl
Greg Kroah-Hartman
maintainerPATCH 359/556 media: em28xx: defer audio-only extension registration
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Diego Fernando Mancera Gomez <[email protected]>
commit 95f76f51937fdfb0fc1e14cae606b1ef574a56f3 upstream.
The audio-only path registers extensions while probing the primary device. For a dual-TS board, this happens before dev_next is created. The duplicate device inherits is_audio_only and is then independently inserted into em28xx_devlist.
The list is intended to contain only primary devices: extension operations reach the secondary device through dev_next. The independently linked secondary can be freed during disconnect while its list node remains reachable, resulting in a use-after-free.
Defer audio-only extension registration to the module-request work item. It runs only after probing has completed construction of the optional secondary device, so only the primary is registered and extension callbacks reach the secondary through dev_next.
--- drivers/media/usb/em28xx/em28xx-cards.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-)
drivers/media/usb/em28xx/em28xx-cards.c +1 -2
@@ -3651,6 +3651,7 @@ static void request_module_async(struct* intf. Don't register extensions twice on those devices. */ if (dev->is_audio_only) { +em28xx_init_extension (dev);#if defined(CONFIG_MODULES ) && defined(MODULE )request_module ("em28xx-alsa" );#endif
@@ -3884,8 +3885,6 @@ static int em28xx_init_dev(struct em28xx retval = -ENODEV ; goto err_deinit_media; } -em28xx_init_extension (dev); -return 0 ; }
Greg Kroah-Hartman
maintainerPATCH 360/556 media: em28xx: fix use-after-free of dev_next->devlist on disconnect
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jiangong.Han <[email protected]>
commit 826915b6b65e2d3251e7248ea54289a22d748c84 upstream.
When a device with has_dual_ts=1 is probed and the is_audio_only path is taken, both dev and dev->dev_next are added to the global em28xx_devlist via em28xx_init_extension(). However, during disconnect, em28xx_close_extension(dev) only calls list_del(&dev->devlist), leaving dev->dev_next->devlist still linked in the global list. When dev_next is subsequently freed via kref_put(), its devlist entry becomes a dangling pointer in em28xx_devlist. The next device probe that calls em28xx_init_extension() triggers a list corruption BUG when list_add_tail detects the freed node.
This bug was exposed by commit a368ecde8a50 ("USB: core: Fix duplicate endpoint bug by clearing reserved bits in the descriptor") which clears reserved bits in bEndpointAddress during endpoint parsing. This causes fuzzed endpoint addresses like 0xf3 to be normalized to 0x83, which em28xx interprets as a vendor audio endpoint, enabling the is_audio_only + has_dual_ts code path that was previously unreachable with such descriptors.
Fix this by removing dev->dev_next->devlist from the global list in em28xx_close_extension() before the device is freed.
--- drivers/media/usb/em28xx/em28xx-core.c | 2 ++ 1 file changed, 2 insertions(+)
drivers/media/usb/em28xx/em28xx-core.c +2 -0
@@ -1265,6 +1265,8 @@ void em28xx_close_extension(struct em28x ops->fini (dev); } } +if (dev->dev_next) +list_del (&dev->dev_next->devlist);list_del (&dev->devlist);mutex_unlock (&em28xx_devlist_mutex); }
Greg Kroah-Hartman
maintainerPATCH 361/556 media: go7007: defer the ALSA v4l2 put until card release
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Shuangpeng Bai <[email protected]>
commit 1bd456afeb8a515137e567967069fce6f8fcd23e upstream.
go7007_snd_init() already takes a v4l2_device reference for the ALSA side, but go7007_snd_remove() drops it immediately after calling snd_card_free_when_closed().
That is too early when a userspace process still has the capture PCM open. The ALSA card and its PCM callbacks remain alive until the last file is closed, so the release path can still reach struct go7007 through pcm->private_data and call go7007_snd_hw_free() after the V4L2 release path has freed the object.
Move the matching v4l2_device_put() to the ALSA card private_free callback so the existing ALSA reference covers the whole deferred card lifetime.
--- drivers/media/usb/go7007/snd-go7007.c | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-)
drivers/media/usb/go7007/snd-go7007.c +9 -1
@@ -195,6 +195,13 @@ static const struct snd_device_ops go700 .dev_free = go7007_snd_free, }; +static void go7007_snd_card_free (struct snd_card *card) +{ +struct go7007 *go = card->private_data; + +v4l2_device_put (&go->v4l2_dev); +} +int go7007_snd_init (struct go7007 *go) {static int dev;
@@ -245,6 +252,8 @@ int go7007_snd_init(struct go7007 *go) gosnd->substream =NULL ; go->snd_context = gosnd;v4l2_device_get (&go->v4l2_dev); + gosnd->card->private_data = go; + gosnd->card->private_free = go7007_snd_card_free; ++dev;return 0 ;
@@ -263,7 +272,6 @@ int go7007_snd_remove(struct go7007 *go)snd_card_disconnect (gosnd->card);snd_card_free_when_closed (gosnd->card); -v4l2_device_put (&go->v4l2_dev);return 0 ; }EXPORT_SYMBOL (go7007_snd_remove);
Greg Kroah-Hartman
maintainerPATCH 362/556 media: i2c: alvium: Fix: Correct name of register in alvium_set_ctrl_auto_exposure
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Martin Hecht <[email protected]>
commit 58ca8a0bff9e78841a39863474b96e59ef60da19 upstream.
Write value for auto-exposure into correct register REG_BCRM_EXPOSURE_AUTO_RW instead of wrong register REG_BCRM_WHITE_BALANCE_AUTO_RW.
--- drivers/media/i2c/alvium-csi2.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/media/i2c/alvium-csi2.c +1 -1
@@ -1290,7 +1290,7 @@ static int alvium_set_ctrl_auto_exposurestruct device *dev = &alvium->i2c_client->dev;int ret; - ret =alvium_write_hshake (alvium,REG_BCRM_WHITE_BALANCE_AUTO_RW , + ret =alvium_write_hshake (alvium,REG_BCRM_EXPOSURE_AUTO_RW , on ?0x02 :0x00 );if (ret) {dev_err (dev,"Fail to set autoexposure reg\n" );
Greg Kroah-Hartman
maintainerPATCH 363/556 media: i2c: imx415: Release runtime PM reference on VBLANK error
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Narasimharao Vadlamudi <[email protected]>
commit bea3001e0f32527a291444e527e84a7ea9b546d4 upstream.
The VBLANK path returned immediately when programming VMAX failed after pm_runtime_get_if_in_use() had taken a runtime PM reference. Break out of the switch instead so the common pm_runtime_put() path is used.
--- drivers/media/i2c/imx415.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/media/i2c/imx415.c +1 -1
@@ -720,7 +720,7 @@ static int imx415_s_ctrl(struct v4l2_ctr ret =cci_write (sensor->regmap,IMX415_VMAX , format->height + ctrl->val,NULL );if (ret) -return ret; +break ;/* * Exposure is set based on VMAX which has just changed, so * program exposure register as well
Greg Kroah-Hartman
maintainerPATCH 364/556 media: i2c: imx415: Return test pattern write errors
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Narasimharao Vadlamudi <[email protected]>
commit 8cd5735b88d76dda80b089031747b6f18ee0bca2 upstream.
imx415_set_testpattern() accumulates failures from cci_write(), but drops the value and always returns success. Return the accumulated error so V4L2 reports failures to userspace.
--- drivers/media/i2c/imx415.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/media/i2c/imx415.c +1 -1
@@ -686,7 +686,7 @@ static int imx415_set_testpattern(structcci_write (sensor->regmap,IMX415_DIG_CLP_MODE ,0x01 , &ret);cci_write (sensor->regmap,IMX415_WRJ_OPEN ,0x01 , &ret); } -return 0 ; +return ret; }static int imx415_s_ctrl (struct v4l2_ctrl *ctrl)
Greg Kroah-Hartman
maintainerPATCH 365/556 media: i2c: ov02a10: fix endpoint parsing use-after-free
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Biren Pandya <[email protected]>
commit 94971ba0592ca77ec99b292226a4b398763315b8 upstream.
The ov02a10_check_hwcfg() function calls fwnode_handle_put(ep) immediately after allocating and parsing the endpoint. However, it subsequently calls fwnode_property_read_u32() using the same 'ep' handle, leading to a potential use-after-free.
Additionally, reading the optional 'ovti,mipi-clock-voltage' property used to overwrite the 'ret' variable. If the property was missing, 'ret' would become negative, and this failure code would be incorrectly returned at the end of the function, causing probe to fail entirely.
Fix the use-after-free by moving fwnode_property_read_u32() before the endpoint is parsed and freed. Avoid the error leak by not assigning the result of fwnode_property_read_u32() to 'ret'.
--- drivers/media/i2c/ov02a10.c | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-)
drivers/media/i2c/ov02a10.c +5 -7
@@ -820,18 +820,16 @@ static int ov02a10_check_hwcfg(struct deif (!ep)return -ENXIO ; +/* Optional indication of MIPI clock voltage unit */ +if (!fwnode_property_read_u32 (ep,"ovti,mipi-clock-voltage" , + &clk_volt)) + ov02a10->mipi_clock_voltage = clk_volt; + ret =v4l2_fwnode_endpoint_alloc_parse (ep, &bus_cfg);fwnode_handle_put (ep);if (ret)return ret; -/* Optional indication of MIPI clock voltage unit */ - ret =fwnode_property_read_u32 (ep,"ovti,mipi-clock-voltage" , - &clk_volt); - -if (!ret) - ov02a10->mipi_clock_voltage = clk_volt; -for (i =0 ; i <ARRAY_SIZE (link_freq_menu_items); i++) {for (j =0 ; j < bus_cfg.nr_of_link_frequencies; j++) { if (link_freq_menu_items[i] ==
Greg Kroah-Hartman
maintainerPATCH 366/556 media: i2c: ov7740: fix use-after-destroy in remove
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Biren Pandya <[email protected]>
commit 5d1b3dea5a44124bab6c14a2d71b977dabed54e7 upstream.
The ov7740_remove() function had a severe teardown order bug where it destroyed the driver's mutex before freeing the V4L2 control handler which relies on that mutex, leading to a use-after-destroy kernel panic. Furthermore, the driver explicitly called v4l2_ctrl_handler_free() and mutex_destroy() sequentially, but then called ov7740_free_controls() which invokes both of them a second time, resulting in a double-free.
This patch fixes the issue by unregistering the subdevice first, and relying exclusively on ov7740_free_controls() to safely tear down the mutex and control handler in the correct order.
--- drivers/media/i2c/ov7740.c | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-)
drivers/media/i2c/ov7740.c +1 -3
@@ -1116,10 +1116,8 @@ static void ov7740_remove(struct i2c_clistruct v4l2_subdev *sd =i2c_get_clientdata (client); struct ov7740 *ov7740 = container_of(sd, struct ov7740, subdev); -mutex_destroy (&ov7740->mutex); -v4l2_ctrl_handler_free (ov7740->subdev.ctrl_handler); -media_entity_cleanup (&ov7740->subdev.entity);v4l2_async_unregister_subdev (sd); +media_entity_cleanup (&ov7740->subdev.entity);ov7740_free_controls (ov7740);pm_runtime_get_sync (&client->dev);
Greg Kroah-Hartman
maintainerPATCH 367/556 media: i2c: ov9282: restore flash duration calculation
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Richard Leitner <[email protected]>
commit d836f57e8ab971c1cd3b607d9e466513f654e644 upstream.
The migration to CCI helpers made V4L2_CID_FLASH_DURATION write the requested duration directly to OV9282_REG_STROBE_FRAME_SPAN, dropping the conversion from microseconds to the register value.
This made flash strobes too long and produced overly bright frames. Restore the missing calculation so flash duration is programmed correctly again.
--- drivers/media/i2c/ov9282.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/media/i2c/ov9282.c +2 -1
@@ -648,7 +648,8 @@ static int ov9282_set_ctrl(struct v4l2_c ctrl->val ? OV9282_OUTPUT_ENABLE6_STROBE : 0, NULL);break ;case V4L2_CID_FLASH_DURATION : - ret =cci_write (ov9282->regmap,OV9282_REG_STROBE_FRAME_SPAN , ctrl->val,NULL ); + ret =cci_write (ov9282->regmap,OV9282_REG_STROBE_FRAME_SPAN , +ov9282_us_to_flash_duration (ov9282, ctrl->val),NULL );break ;default :dev_err (ov9282->dev,"Invalid control %d" , ctrl->id);
Greg Kroah-Hartman
maintainerPATCH 368/556 media: i2c: vd55g1: Fix manual digital gain on color variant
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Benjamin Mugnier <[email protected]>
commit 113a84d6ba739d333eef2a595e3ccd4f97a306c2 upstream.
Apply digital gain to all channels, each channel representing a color.
--- drivers/media/i2c/vd55g1.c | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-)
drivers/media/i2c/vd55g1.c +13 -3
@@ -60,7 +60,10 @@#define VD55G1_PATGEN_ENABLE BIT(0)#define VD55G1_REG_MANUAL_ANALOG_GAIN CCI_REG8(0x0501)#define VD55G1_REG_MANUAL_COARSE_EXPOSURE CCI_REG16_LE(0x0502) -#define VD55G1_REG_MANUAL_DIGITAL_GAIN CCI_REG16_LE(0x0504) +#define VD55G1_REG_MANUAL_DIGITAL_GAIN_CH0 CCI_REG16_LE(0x0504) +#define VD55G1_REG_MANUAL_DIGITAL_GAIN_CH1 CCI_REG16_LE(0x0506) +#define VD55G1_REG_MANUAL_DIGITAL_GAIN_CH2 CCI_REG16_LE(0x0508) +#define VD55G1_REG_MANUAL_DIGITAL_GAIN_CH3 CCI_REG16_LE(0x050a)#define VD55G1_REG_APPLIED_COARSE_EXPOSURE CCI_REG16_LE(0x00e8)#define VD55G1_REG_APPLIED_ANALOG_GAIN CCI_REG16_LE(0x00ea)#define VD55G1_REG_APPLIED_DIGITAL_GAIN CCI_REG16_LE(0x00ec)
@@ -850,9 +853,16 @@ static int vd55g1_update_expo_cluster(stvd55g1_write (sensor,VD55G1_REG_MANUAL_ANALOG_GAIN , sensor->again_ctrl->val, &ret); -if (!is_auto && sensor->dgain_ctrl->is_new) -vd55g1_write (sensor,VD55G1_REG_MANUAL_DIGITAL_GAIN , +if (!is_auto && sensor->dgain_ctrl->is_new) { +vd55g1_write (sensor,VD55G1_REG_MANUAL_DIGITAL_GAIN_CH0 , sensor->dgain_ctrl->val, &ret); +vd55g1_write (sensor,VD55G1_REG_MANUAL_DIGITAL_GAIN_CH1 , + sensor->dgain_ctrl->val, &ret); +vd55g1_write (sensor,VD55G1_REG_MANUAL_DIGITAL_GAIN_CH2 , + sensor->dgain_ctrl->val, &ret); +vd55g1_write (sensor,VD55G1_REG_MANUAL_DIGITAL_GAIN_CH3 , + sensor->dgain_ctrl->val, &ret); + }return ret; }
Greg Kroah-Hartman
maintainerPATCH 369/556 media: i2c: vd55g1: Fix media bus code initialization
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Benjamin Mugnier <[email protected]>
commit e4a4f2e3b9bc65e0b82ae8c3a2945955870df36f upstream.
In the driver initialization, the index of the default media bus code from the supported media bus code array is passed directly to the vd55g1_get_fmt_code() function instead of the proper media bus code.
This works correctly as a proper media bus code is set after initialization but could not have been the case. This also resulted in mutliple "Unsupported mbus format" error messages.
Retrieve the media bus code from the media bus code array, and pass this media bus code to vd55g1_get_fmt_code() instead of the code index.
Rename VD55G1_MBUS_CODE_DEF to VD55G1_MBUS_CODE_IDX_DEF and VD55G1_MODE_DEF to VD55G1_MODE_IDX_DEF while at it to avoid future confusions. Display the guilty error code in warning message.
--- drivers/media/i2c/vd55g1.c | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-)
drivers/media/i2c/vd55g1.c +10 -6
@@ -117,9 +117,8 @@#define VD55G1_WIDTH 804#define VD55G1_HEIGHT 704 -#define VD55G1_MODE_DEF 0 +#define VD55G1_MODE_IDX_DEF 0#define VD55G1_NB_GPIOS 4 -#define VD55G1_MBUS_CODE_DEF 0#define VD55G1_DGAIN_DEF 256#define VD55G1_AGAIN_DEF 19#define VD55G1_EXPO_MAX_TERM 64
@@ -637,7 +636,7 @@ static u32 vd55g1_get_fmt_code(struct vd goto adapt_bayer_pattern; } } -dev_warn (sensor->dev,"Unsupported mbus format\n" ); +dev_warn (sensor->dev,"Unsupported mbus format: 0x%x\n" , code);return code;
@@ -1357,6 +1356,7 @@ static int vd55g1_init_state(struct v4l2 {struct vd55g1 *sensor =to_vd55g1 (sd);struct v4l2_subdev_format fmt = {0 }; +int code;struct v4l2_subdev_route routes[] = { { .flags =V4L2_SUBDEV_ROUTE_FL_ACTIVE } };
@@ -1371,9 +1371,13 @@ static int vd55g1_init_state(struct v4l2if (ret)return ret; -vd55g1_update_pad_fmt (sensor, &vd55g1_supported_modes[VD55G1_MODE_DEF ], -vd55g1_get_fmt_code (sensor,VD55G1_MBUS_CODE_DEF ), - &fmt.format); +if (sensor->id ==VD55G1_MODEL_ID_VD55G1 ) + code = vd55g1_mbus_formats_mono[0 ]; +else + code = vd55g1_mbus_formats_bayer[0 ][0 ]; +vd55g1_update_pad_fmt (sensor, + &vd55g1_supported_modes[VD55G1_MODE_IDX_DEF ], +vd55g1_get_fmt_code (sensor, code), &fmt.format);return vd55g1_set_pad_fmt (sd, sd_state, &fmt); }
Greg Kroah-Hartman
maintainerPATCH 370/556 media: imx355: Avoid calling imx355_power_off twice in error path
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Dave Stevenson <[email protected]>
commit ee737bc3ccae7dc713ccaa83ffa46080c6031b3e upstream.
If v4l2_async_register_subdev_sensor failed, then the sensor had already been powered down by pm_runtime_idle, but the error path then also explicitly called imx355_power_off as well. That left an imbalance in the regulator and clock calls.
Call pm_runtime_idle only after v4l2_async_register_subdev_sensor succeeds to avoid this.
--- drivers/media/i2c/imx355.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/media/i2c/imx355.c +2 -1
@@ -1822,12 +1822,13 @@ static int imx355_probe(struct i2c_clien*/ pm_runtime_set_active (imx355->dev);pm_runtime_enable (imx355->dev); -pm_runtime_idle (imx355->dev); ret =v4l2_async_register_subdev_sensor (&imx355->sd);if (ret <0 ) goto error_media_entity_runtime_pm; +pm_runtime_idle (imx355->dev); +return 0 ; error_media_entity_runtime_pm:
Greg Kroah-Hartman
maintainerPATCH 371/556 media: intel/ipu6: fix async notifier cleanup leak on parse error
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Cong Nguyen <[email protected]>
commit abb1f808ceab5a3275f8a6b4e37cff17f9f781c1 upstream.
isys_notifier_init() calls v4l2_async_nf_init() and then adds fwnode remote subdevs in a loop with v4l2_async_nf_add_fwnode_remote(). If an endpoint parse or add fails partway through the loop, it jumps to err_parse and returns without calling v4l2_async_nf_cleanup(), leaking every v4l2_async_connection already added to the notifier's waiting list.
The register-failure path just below already cleans up correctly, and the caller only tears the notifier down (isys_notifier_cleanup()) once isys_notifier_init() has returned success. Clean up the notifier on the parse error path too.
--- drivers/media/pci/intel/ipu6/ipu6-isys.c | 1 + 1 file changed, 1 insertion(+)
drivers/media/pci/intel/ipu6/ipu6-isys.c +1 -0
@@ -761,6 +761,7 @@ static int isys_notifier_init(struct ipu err_parse:fwnode_handle_put (ep); +v4l2_async_nf_cleanup (&isys->notifier);return ret; }
Greg Kroah-Hartman
maintainerPATCH 372/556 media: ipu-bridge: check all DMI entries when overriding sensor rotation
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: José María Martín <[email protected]>
commit 4900cad020c0580dfb1be27776ff10a4ef110cfa upstream.
A machine can have more than one sensor whose rotation needs to be overridden, which takes one upside_down_sensor_dmi_ids[] entry per sensor, all sharing the same DMI match but with different ACPI HIDs in driver_data.
ipu_bridge_parse_rotation() uses dmi_first_match(), which always stops at the first entry matching the running machine, so any further entry for the same machine is unreachable and only one sensor per machine can ever be corrected.
Walk the whole table and match every entry for the running machine against the sensor's ACPI HID instead.
--- drivers/media/pci/intel/ipu-bridge.c | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-)
drivers/media/pci/intel/ipu-bridge.c +5 -3
@@ -298,9 +298,11 @@ static u32 ipu_bridge_parse_rotation(str {const struct dmi_system_id *dmi_id; - dmi_id =dmi_first_match (upside_down_sensor_dmi_ids); -if (dmi_id &&acpi_dev_hid_match (adev, dmi_id->driver_data)) -return 180 ; +/* A machine may have one entry per sensor, so check all matches. */ +for (dmi_id =dmi_first_match (upside_down_sensor_dmi_ids); dmi_id; + dmi_id =dmi_first_match (dmi_id +1 )) +if (acpi_dev_hid_match (adev, dmi_id->driver_data)) +return 180 ;switch (ssdb->degree) {case IPU_SENSOR_ROTATION_NORMAL :
Greg Kroah-Hartman
maintainerPATCH 373/556 media: iris: Enumerate cap->bus_info to differentiate between encoder and decoder
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Bryan O'Donoghue <[email protected]>
commit 94ef75095d5e76df848a2e5508d71a4532a6ce23 upstream.
commit 66c744e28b69 ("media: venus: assign unique bus_info strings for encoder and decoder") introduced the naming convention plat:node-addr:video-codec{enc|dec}. Right now Iris does not replicate this naming convention.
When we do v4l2-ctrl --list -devices we see:
Iris Decoder (platform:aa00000.video-codec):
/dev/video0 /dev/video1
Enumerate the bus_info field of the capabilities structure for namespace parity and appropriate differentiation:
Iris Decoder (plat:aa00000.video-codec:dec):
/dev/video0
Iris Encoder (plat:aa00000.video-codec:enc):
/dev/video1
--- drivers/media/platform/qcom/iris/iris_vidc.c | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-)
drivers/media/platform/qcom/iris/iris_vidc.c +9 -2
@@ -449,14 +449,21 @@ static int iris_enum_frameintervals(strustatic int iris_querycap (struct file *filp,void *fh,struct v4l2_capability *cap) { +struct iris_core *core =video_drvdata (filp);struct iris_inst *inst =iris_get_inst (filp); +char *info;strscpy (cap->driver,IRIS_DRV_NAME ,sizeof (cap->driver)); -if (inst->domain ==DECODER ) +if (inst->domain ==DECODER ) {strscpy (cap->card,"Iris Decoder" ,sizeof (cap->card)); -else + info ="dec" ; + }else {strscpy (cap->card,"Iris Encoder" ,sizeof (cap->card)); + info ="enc" ; + } +snprintf (cap->bus_info,sizeof (cap->bus_info), +"plat:%s:%s" ,dev_name (core->dev), info);return 0 ; }
Greg Kroah-Hartman
maintainerPATCH 374/556 media: meson: vdec: fix NULL pointer deref in vdec_try_fmt_common
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Christian Hewitt <[email protected]>
commit 20aa934ace6917262ff579a73ec018d06a7bad1c upstream.
When VIDIOC_TRY_FMT is called with an unsupported pixel format on the OUTPUT queue, vdec_try_fmt_common() falls back to V4L2_PIX_FMT_MPEG2. However, if a distro has locally patched MPEG2 support out (as it has been broken for some time) the platform format table does not contain MPEG2 so find_format() returns NULL and the subsequent dereference of fmt_out->max_width triggers a NULL pointer dereference.
Fix this by falling back to the first format in the platform's format array instead of hardcoding V4L2_PIX_FMT_MPEG2. This is always valid since every platform defines at least one format.
--- drivers/staging/media/meson/vdec/vdec.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
drivers/staging/media/meson/vdec/vdec.c +2 -2
@@ -504,8 +504,8 @@ vdec_try_fmt_common(struct amvdec_sessiocase V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE : fmt_out =find_format (fmts, size, pixmp->pixelformat);if (!fmt_out) { - pixmp->pixelformat =V4L2_PIX_FMT_MPEG2 ; - fmt_out =find_format (fmts, size, pixmp->pixelformat); + pixmp->pixelformat = fmts[0 ].pixfmt; + fmt_out = &fmts[0 ]; }break ;case V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE :
Greg Kroah-Hartman
maintainerPATCH 375/556 media: platform: mtk-mdp3: Fix SCP device refcounting
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Guangshuo Li <[email protected]>
commit 55793e4665b7f15151e6f5ab51ca980e73abed5d upstream.
mdp_probe() first tries to get the SCP handle with scp_get(). When that fails, it falls back to looking up the SCP platform device with __get_pdev_by_id() and then reads its driver data.
The fallback lookup returns the platform device with a reference, just like scp_get() does. However, the fallback path currently drops that reference immediately after platform_get_drvdata(). The driver later still calls scp_put(mdp->scp) unconditionally from the probe error path and from mdp_video_device_release(), which drops the SCP device reference again.
Keep the fallback reference until the existing scp_put() call, so that the fallback path follows the same ownership rules as the scp_get() path.
--- drivers/media/platform/mediatek/mdp3/mtk-mdp3-core.c | 1 - 1 file changed, 1 deletion(-)
drivers/media/platform/mediatek/mdp3/mtk-mdp3-core.c +0 -1
@@ -294,7 +294,6 @@ static int mdp_probe(struct platform_dev goto err_destroy_clock_wq; } mdp->scp =platform_get_drvdata (mm_pdev); -put_device (&mm_pdev->dev); } mdp->rproc_handle =scp_get_rproc (mdp->scp);
Greg Kroah-Hartman
maintainerPATCH 376/556 media: platform: mtk-mdp3: fix NULL deref on failed SCP lookup
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Johan Hovold <[email protected]>
commit 90368323fb244da0504e3da37a182f8e89bcc3b9 upstream.
Add the missing sanity check after looking up the SCP to avoid dereferencing a NULL-pointer in case its driver has not yet been bound.
--- drivers/media/platform/mediatek/mdp3/mtk-mdp3-core.c | 5 +++++ 1 file changed, 5 insertions(+)
drivers/media/platform/mediatek/mdp3/mtk-mdp3-core.c +5 -0
@@ -296,6 +296,11 @@ static int mdp_probe(struct platform_dev mdp->scp =platform_get_drvdata (mm_pdev); } +if (!mdp->scp) { + ret = -EPROBE_DEFER ; + goto err_destroy_clock_wq; + } + mdp->rproc_handle =scp_get_rproc (mdp->scp);dev_dbg (&pdev->dev,"MDP rproc_handle: %p" , mdp->rproc_handle);
Greg Kroah-Hartman
maintainerPATCH 377/556 media: nxp: imx8-isi: Fix stream ID validation bypass in crossbar routing
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Guoniu Zhou <[email protected]>
commit 795bd2863591f2fee33fab8f10cf9c383c94342e upstream.
The crossbar routing validation has a critical bug where it validates the wrong routing table, allowing userspace to bypass validation entirely.
The __mxc_isi_crossbar_set_routing() function is called to validate and apply a new routing table from userspace. However, the validation loop iterates over state->routing (the currently active routing table) instead of the routing parameter (the new table being validated):
for_each_active_route(&state->routing, route) {This means userspace can submit any invalid routing configuration and it will pass validation as long as the currently active routing is valid. This is a security issue as it allows userspace to configure routes that violate hardware constraints, potentially causing undefined hardware behavior.
Fix by validating the routing table that will actually be applied.
--- drivers/media/platform/nxp/imx8-isi/imx8-isi-crossbar.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/media/platform/nxp/imx8-isi/imx8-isi-crossbar.c +1 -1
@@ -107,7 +107,7 @@ static int __mxc_isi_crossbar_set_routinreturn ret;/* The memory input can be routed to the first pipeline only. */ -for_each_active_route (&state->routing, route) { +for_each_active_route (routing, route) {if (route->sink_pad == xbar->num_sinks -1 && route->source_pad != xbar->num_sinks) { dev_dbg(xbar->isi->dev,
Greg Kroah-Hartman
maintainerPATCH 378/556 media: nxp: imx8-isi: Correct color map between V4L2 and ISI
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Guoniu Zhou <[email protected]>
commit 4640ec1cb0121473867e7a6850c7449340dcd428 upstream.
Fix the ISI input format for the color map V4L2_PIX_FMT_XBGR32 in memory-to-memory mode.
--- drivers/media/platform/nxp/imx8-isi/imx8-isi-video.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/media/platform/nxp/imx8-isi/imx8-isi-video.c +1 -1
@@ -151,7 +151,7 @@ static const struct mxc_isi_format_info .fourcc = V4L2_PIX_FMT_XBGR32, .type =MXC_ISI_VIDEO_CAP |MXC_ISI_VIDEO_M2M_OUT | MXC_ISI_VIDEO_M2M_CAP, - .isi_in_format = CHNL_MEM_RD_CTRL_IMG_TYPE_XBGR8, + .isi_in_format = CHNL_MEM_RD_CTRL_IMG_TYPE_XRGB8, .isi_out_format = CHNL_IMG_CTRL_FORMAT_XRGB888, .mem_planes = 1, .color_planes = 1,
Greg Kroah-Hartman
maintainerPATCH 379/556 media: nxp: imx8-isi: Use BIT_ULL() for 64-bit stream masks
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Guoniu Zhou <[email protected]>
commit 77e60a2c5d824ad2d493f53dc17137ae065753fe upstream.
Use BIT_ULL() instead of BIT() for u64 stream masks to avoid incorrect results on 32-bit architectures when stream IDs are 32 or greater.
--- drivers/media/platform/nxp/imx8-isi/imx8-isi-crossbar.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
drivers/media/platform/nxp/imx8-isi/imx8-isi-crossbar.c +2 -2
@@ -145,10 +145,10 @@ mxc_isi_crossbar_xlate_streams(struct mx*/ for_each_active_route (&state->routing, route) {if (route->source_pad != source_pad || - !(source_streams &BIT (route->source_stream))) + !(source_streams &BIT_ULL (route->source_stream)))continue ; - sink_streams |=BIT (route->sink_stream); + sink_streams |=BIT_ULL (route->sink_stream); sink_pad = route->sink_pad; }
Greg Kroah-Hartman
maintainerPATCH 380/556 media: mali-c55: fix dropped last AEC histogram zone weight
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: David Carlier <[email protected]>
commit fb9b87145624eedaf3d50edac9b11d707494cb5b upstream.
The 15x15 AEC histogram metering grid has 225 per-zone weights, packed by userspace as a u8 array. The driver writes the first 56 registers (zones 0 through 223) in a loop, then handles the final register on its own to keep static analysers from flagging the array access.
That separate path computes the address and value for the 225th weight (the bottom-right zone) but never issues the register write, so the zone keeps its stale or default weight. Any non-default weight userspace sets for the last zone is silently ignored, skewing auto-exposure metering. Both the AEXP_HIST_WEIGHTS and AEXP_IHIST_WEIGHTS blocks are affected as they share this handler.
Issue the missing write, masking the value as the loop does.
--- drivers/media/platform/arm/mali-c55/mali-c55-params.c | 1 + 1 file changed, 1 insertion(+)
drivers/media/platform/arm/mali-c55/mali-c55-params.c +1 -0
@@ -212,6 +212,7 @@ mali_c55_params_aexp_hist_weights(struct mali_c55 *mali_c55, val = params->zone_weights[MALI_C55_MAX_ZONES -1 ]; addr = base +MALI_C55_AEXP_HIST_ZONE_WEIGHTS_OFFSET + (4 *56 ); +mali_c55_ctx_write (mali_c55, addr, val &MALI_C55_AEXP_HIST_ZONE_WEIGHT_MASK ); } static void mali_c55_params_digital_gain(struct mali_c55 *mali_c55,
Signature · 1 line
2.55.0
Greg Kroah-Hartman
maintainerPATCH 381/556 media: mali-c55: Fix clock leak on reset deassert failure
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: David Carlier <[email protected]>
commit f499befeb668436b67bdb2b610b34db57732703f upstream.
__mali_c55_power_on() enables the clocks before deasserting the resets, but bails out on a deassert failure without disabling them again. Both callers treat a failed power-on as already cleaned up, so the clocks are left enabled.
Disable them on the error path.
--- drivers/media/platform/arm/mali-c55/mali-c55-core.c | 2 ++ 1 file changed, 2 insertions(+)
drivers/media/platform/arm/mali-c55/mali-c55-core.c +2 -0
@@ -698,6 +698,8 @@ static int __mali_c55_power_on(struct ma mali_c55->resets);if (ret) {dev_err (mali_c55->dev,"failed to deassert resets\n" ); +clk_bulk_disable_unprepare (ARRAY_SIZE (mali_c55->clks), + mali_c55->clks);return ret; }
Greg Kroah-Hartman
maintainerPATCH 382/556 media: mali-c55: Fix AEXP IHIST disable bit shift
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: David Carlier <[email protected]>
commit 9a2925b823d541a23b8330f80056e6cca78c7677 upstream.
The post-Iridix auto-exposure histogram disable bit in MALI_C55_REG_METERING_CONFIG is bit 16, but MALI_C55_AEXP_IHIST_DISABLE was defined with a shift of 12, copied from the AEXP_HIST definition above it. As the value is masked with the BIT(16) disable mask when it is programmed, the result is always zero and the disable bit is never set. The IHIST can therefore never be disabled, neither at ISP init nor via a parameters block flagged V4L2_ISP_PARAMS_FL_BLOCK_DISABLE, and the hardware keeps producing histogram statistics that userspace believes are switched off.
Use a shift of 16 so the disable request takes effect.
--- drivers/media/platform/arm/mali-c55/mali-c55-registers.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/media/platform/arm/mali-c55/mali-c55-registers.h +1 -1
@@ -173,7 +173,7 @@ enum mali_c55_interrupts {#define MALI_C55_AEXP_HIST_SWITCH_MASK GENMASK(14, 13)#define MALI_C55_AEXP_HIST_SWITCH (x) ((x) << 13)#define MALI_C55_AEXP_IHIST_DISABLE_MASK BIT(16) -#define MALI_C55_AEXP_IHIST_DISABLE (0x01 << 12) +#define MALI_C55_AEXP_IHIST_DISABLE (0x01 << 16)#define MALI_C55_AEXP_SRC_MASK BIT(24)#define MALI_C55_REG_TPG_CH0 0x18ed8
Signature · 1 line
2.55.0
Greg Kroah-Hartman
maintainerPATCH 383/556 media: mali-c55: Fix scaler factor overflow for large crop sizes
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: David Carlier <[email protected]>
commit 2447c768cb5dfb9f52630b82d419e2b24fee27a3 upstream.
The horizontal and vertical scaling factors multiply the crop dimensions by MALI_C55_RSZ_SCALER_FACTOR, a Q4.20 factor of (1 << 20). Both operands are 32-bit, so the multiplication wraps before the result is stored in the u64 scale variables. For any crop dimension of 4096 or more (the maximum is 8192) the value overflows; an 8192 to 4096 downscale yields a TINC of zero, so the scaler never advances and the output is corrupted.
Define MALI_C55_RSZ_SCALER_FACTOR as a 64-bit constant so the multiplication is performed in 64-bit.
--- drivers/media/platform/arm/mali-c55/mali-c55-resizer.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/media/platform/arm/mali-c55/mali-c55-resizer.c +1 -1
@@ -15,7 +15,7 @@#include "mali-c55-registers.h" /* Scaling factor in Q4.20 format. */ -#define MALI_C55_RSZ_SCALER_FACTOR (1U << 20) +#define MALI_C55_RSZ_SCALER_FACTOR BIT_ULL(20)#define MALI_C55_RSZ_COEFS_BANKS 8#define MALI_C55_RSZ_COEFS_ENTRIES 64
Signature · 1 line
2.55.0
Greg Kroah-Hartman
maintainerPATCH 384/556 media: rc: sunxi-cir: Unregister rc device on probe failure
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Myeonghun Pak <[email protected]>
commit 479aa6fa8c50f1052f1451326ef7d4d586d340c3 upstream.
After rc_register_device() succeeds, later probe failures must undo the registration with rc_unregister_device(). The current error path jumps to the allocation cleanup label and only calls rc_free_device(), leaving the rc device registration and resources created by rc_register_device() behind.
Add a registered-device unwind label for the IRQ lookup, IRQ request, and hardware initialization failure paths. Keep rc_free_device() for failures before rc_register_device() succeeds.
--- drivers/media/rc/sunxi-cir.c | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-)
drivers/media/rc/sunxi-cir.c +6 -3
@@ -344,22 +344,25 @@ static int sunxi_ir_probe(struct platfor ir->irq =platform_get_irq (pdev,0 );if (ir->irq <0 ) { ret = ir->irq; - goto exit_free_dev; + goto exit_unregister_dev; } ret =devm_request_irq (dev, ir->irq, sunxi_ir_irq,0 ,SUNXI_IR_DEV , ir);if (ret) {dev_err (dev,"failed request irq\n" ); - goto exit_free_dev; + goto exit_unregister_dev; } ret =sunxi_ir_hw_init (dev);if (ret) - goto exit_free_dev; + goto exit_unregister_dev;dev_info (dev,"initialized sunXi IR driver\n" );return 0 ; +exit_unregister_dev: +rc_unregister_device (ir->rc); + exit_free_dev:rc_free_device (ir->rc);
Greg Kroah-Hartman
maintainerPATCH 385/556 media: rockchip: rga: dont change RGB quantization
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Sven Püschel <[email protected]>
commit 7acc334cf038b5ac1a7ee480d3ec59d288d2f5f3 upstream.
Don't change the quantization of an RGB format when converting between RGB and YUV with the RGA3. As the RGA3 only supports doing conversions to full range YUV with BT601, it wants to announce it through try_fmt/s_fmt.
As it is only relevant, when converting between RGB and YUV, it's guarded by a given condition. But the condition also causes the RGB format quantization to be adjusted to limited range, which is incorrect.
Therefore simplify the condition to only apply when the current format is a YUV format. Also document the reason for checking if the other format is an RGB format.
--- drivers/media/platform/rockchip/rga/rga3-hw.c | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-)
drivers/media/platform/rockchip/rga/rga3-hw.c +8 -4
@@ -450,10 +450,14 @@ static void *rga3_adjust_and_map_format(struct rga_ctx *ctx, other_format = is_output ? &ctx->out.pix : &ctx->in.pix; other_format_info =v4l2_format_info (other_format->pixelformat); -if ((v4l2_is_format_rgb (format_info) && -v4l2_is_format_yuv (other_format_info)) || - (v4l2_is_format_yuv (format_info) && -v4l2_is_format_rgb (other_format_info))) { +/* +* Only apply the quantization restrictions when we need to +* convert between RGB and YUV. Otherwise there is no point +* to limit the quantization for operations like scaling or +* rotations. +*/ +if (v4l2_is_format_yuv (format_info) && +v4l2_is_format_rgb (other_format_info)) {/* * The RGA3 only supports BT601, BT709 and BT2020 RGB<->YUV conversions * Additionally BT709 and BT2020 only support limited range YUV.
Signature · 1 line
2.55.0
Greg Kroah-Hartman
maintainerPATCH 386/556 media: rkvdec: Propagate platform_get_irq() errors
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Narasimharao Vadlamudi <[email protected]>
commit c37aca64206fafe938119e801a3fd10a537a051f upstream.
platform_get_irq() returns a positive IRQ number on success and a negative error code on failure. It no longer returns zero. The driver currently returns -ENXIO for all failures, which loses useful errors such as -EPROBE_DEFER.
Return the error from platform_get_irq() directly.
--- drivers/media/platform/rockchip/rkvdec/rkvdec.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
drivers/media/platform/rockchip/rkvdec/rkvdec.c +2 -2
@@ -1818,8 +1818,8 @@ static int rkvdec_probe(struct platform_vb2_dma_contig_set_max_seg_size (&pdev->dev,DMA_BIT_MASK (32 )); irq =platform_get_irq (pdev,0 ); -if (irq <=0 ) -return -ENXIO ; +if (irq <0 ) +return irq; ret = devm_request_threaded_irq(&pdev->dev, irq, NULL, rkvdec_irq_handler, IRQF_ONESHOT,
Greg Kroah-Hartman
maintainerPATCH 387/556 media: rkvdec: hevc: tighten EXT SPS RPS control dimensions
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Michael Bommarito <[email protected]>
commit f0b9d7e5be061b4858279d451f5a6ad0ed20b1be upstream.
The VDPU381 HEVC driver registers V4L2_CID_STATELESS_HEVC_EXT_SPS_ST_RPS and V4L2_CID_STATELESS_HEVC_EXT_SPS_LT_RPS with .cfg.dims = { 65 }, but the HEVC spec caps num_short_term_ref_pic_sets at 64 (ITU-T H.265 7.4.8) and num_long_term_ref_pics_sps at 32 (7.4.3.2.1). The hardware descriptor table (struct rkvdec_rps) sizes match those spec limits: refs[32] and short_term_ref_sets[64].
Reduce the dims to { 64 } and { 32 } respectively so the V4L2 control framework rejects oversized payloads before any driver code runs.
--- drivers/media/platform/rockchip/rkvdec/rkvdec.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
drivers/media/platform/rockchip/rkvdec/rkvdec.c +2 -2
@@ -278,12 +278,12 @@ static const struct rkvdec_ctrl_desc vdp { .cfg.id = V4L2_CID_STATELESS_HEVC_EXT_SPS_ST_RPS, .cfg.ops = &rkvdec_ctrl_ops, - .cfg.dims = { 65 }, + .cfg.dims = { 64 }, }, { .cfg.id = V4L2_CID_STATELESS_HEVC_EXT_SPS_LT_RPS, .cfg.ops = &rkvdec_ctrl_ops, - .cfg.dims = { 65 }, + .cfg.dims = { 32 }, }, };
Greg Kroah-Hartman
maintainerPATCH 388/556 media: rkvdec: hevc: guard INTER_REF_PIC_SET_PRED index underflow
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Michael Bommarito <[email protected]>
commit 052c5ed5a1d96a6b24fd50ccda16fc6841ee7ca3 upstream.
st_ref_pic_set_prediction() computes the reference RPS index as st_rps_idx - (delta_idx_minus1 + 1) per HEVC spec equation 7-59. Both operands are u8, so when delta_idx_minus1 + 1 exceeds the current index the subtraction wraps and the subsequent array access at calculated_rps_st_sets[ref_rps_idx] reads far out of bounds.
A userspace V4L2 client that can open the RKVDEC m2m decoder can submit an EXT_SPS_ST_RPS control with INTER_REF_PIC_SET_PRED set and delta_idx_minus1 crafted to trigger the underflow.
Reject the entry early when the reference index would underflow.
--- drivers/media/platform/rockchip/rkvdec/rkvdec-hevc-common.c | 3 +++ 1 file changed, 3 insertions(+)
drivers/media/platform/rockchip/rkvdec/rkvdec-hevc-common.c +3 -0
@@ -209,6 +209,9 @@ static void st_ref_pic_set_prediction(struct rkvdec_hevc_run *run, int idx,int i, j;int dPoc; +if ((unsigned int )rps_data->delta_idx_minus1 +1 > idx) +return ; + ref_rps_idx = st_rps_idx - (rps_data->delta_idx_minus1 +1 );/* 7-59 */ delta_rps = (1 -2 * rps_data->delta_rps_sign) * (rps_data->abs_delta_rps_minus1 +1 );/* 7-60 */
Signature · 1 line
2.55.0
Greg Kroah-Hartman
maintainerPATCH 389/556 media: rtl2832_sdr: use vb2_video_unregister_device() on remove to fix DMA leak
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Valery Borovsky <[email protected]>
commit dabb047c62668f280998e29117c55e41aabac336 upstream.
rtl2832_sdr_remove() runs on USB disconnect and clears dev->udev to NULL before any pending streaming teardown has run. When user space later closes its file descriptor, vb2 calls rtl2832_sdr_stop_streaming() which in turn calls rtl2832_sdr_free_stream_bufs(). That helper releases each coherent buffer with:
usb_free_coherent(dev->udev, dev->buf_size,
dev->buf_list[dev->buf_num],
dev->dma_addr[dev->buf_num]);usb_free_coherent() returns immediately when its dev argument is NULL, so every DMA stream buffer that was live at disconnect is silently leaked. The URBs allocated in rtl2832_sdr_alloc_urbs() outlive the device for the same reason.
The rtl2832_sdr driver uses vb2_fop_release() in its file_operations, so replace video_unregister_device(&dev->vdev) with vb2_video_unregister_device(&dev->vdev) and move it before clearing dev->udev. vb2_video_unregister_device() releases the vb2 queue, which synchronously runs rtl2832_sdr_stop_streaming() if streaming is active, so URBs and coherent DMA stream buffers are freed while dev->udev is still valid.
vb2_video_unregister_device() locks vdev->queue->lock (vb_queue_lock) internally, and stop_streaming() locks v4l2_lock, so the previous outer mutex_lock(&dev->vb_queue_lock) / mutex_lock(&dev->v4l2_lock) pair around the unregister sequence would self-deadlock and has been removed. A short v4l2_lock critical section around dev->udev = NULL remains so any ioctl path that still holds the file descriptor sees coherent state.
Issue identified by automated review of the INV-003 series at
https://sashiko.dev/
--- drivers/media/dvb-frontends/rtl2832_sdr.c | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-)
drivers/media/dvb-frontends/rtl2832_sdr.c +13 -5
@@ -1477,14 +1477,22 @@ static void rtl2832_sdr_remove(struct pldev_dbg (&pdev->dev,"\n" ); -mutex_lock (&dev->vb_queue_lock); +/* +* vb2_video_unregister_device() releases the vb2 queue, which +* triggers rtl2832_sdr_stop_streaming() if streaming is active. +* stop_streaming() uses dev->udev to free URBs and coherent DMA +* stream buffers via usb_free_coherent(), so it must run before +* dev->udev is cleared. vb2_video_unregister_device() locks +* vb_queue_lock internally and stop_streaming() locks v4l2_lock, +* so neither may be held by the caller. +*/ +v4l2_device_disconnect (&dev->v4l2_dev); +vb2_video_unregister_device (&dev->vdev); +mutex_lock (&dev->v4l2_lock); -/* No need to keep the urbs around after disconnection */ dev->udev =NULL ; -v4l2_device_disconnect (&dev->v4l2_dev); -video_unregister_device (&dev->vdev);mutex_unlock (&dev->v4l2_lock); -mutex_unlock (&dev->vb_queue_lock); +v4l2_device_put (&dev->v4l2_dev);module_put (pdev->dev.parent->driver->owner); }
Greg Kroah-Hartman
maintainerPATCH 390/556 media: rtl2832_sdr: release URBs and stream buffers on start_streaming() failure
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Valery Borovsky <[email protected]>
commit fe50cdaebf12cd32ff9a44d92bfd6fbc2300dbd4 upstream.
rtl2832_sdr_start_streaming() calls rtl2832_sdr_alloc_stream_bufs(), rtl2832_sdr_alloc_urbs() and rtl2832_sdr_submit_urbs() in sequence and shares a single err: label that only unlocks the mutex and returns. When alloc_urbs() succeeds but submit_urbs() fails, or when alloc_urbs() itself returns -ENOMEM after alloc_stream_bufs() has already succeeded, the URBs and/or the coherent DMA stream buffers stay allocated while streaming reports failure to vb2. Two latent defects follow on the next VIDIOC_STREAMON:
1) rtl2832_sdr_alloc_stream_bufs() unconditionally resets dev->buf_num to 0 and overwrites dev->buf_list[]/dev->dma_addr[], permanently leaking the coherent DMA memory allocated by the previous attempt.
2) rtl2832_sdr_alloc_urbs() never resets dev->urbs_initialized and only increments it. After a second successful pass urbs_initialized can exceed MAX_BULK_BUFS, so the subsequent rtl2832_sdr_free_urbs() walks from urbs_initialized - 1 down to 0 and reads past the end of dev->urb_list[], passing garbage pointers to usb_free_urb().
Mirror the teardown that stop_streaming() already performs: on the error path call rtl2832_sdr_free_urbs() and rtl2832_sdr_free_stream_bufs() before unlocking. Both helpers are idempotent (free_urbs kills and zeros urbs_initialized; free_stream_bufs is gated on URB_BUF and clears the buf_num counter), so partial-failure paths and the no-allocation paths remain safe.
Issue identified by automated review of the INV-003 series at
https://sashiko.dev/
--- drivers/media/dvb-frontends/rtl2832_sdr.c | 3 +++ 1 file changed, 3 insertions(+)
drivers/media/dvb-frontends/rtl2832_sdr.c +3 -0
@@ -906,9 +906,12 @@ static int rtl2832_sdr_start_streaming(s goto err;mutex_unlock (&dev->v4l2_lock); +return 0 ; err: +rtl2832_sdr_free_urbs (dev); +rtl2832_sdr_free_stream_bufs (dev);rtl2832_sdr_cleanup_queued_bufs (dev,VB2_BUF_STATE_QUEUED );mutex_unlock (&dev->v4l2_lock);
Greg Kroah-Hartman
maintainerPATCH 391/556 media: rzg2l-cru: Align bytesperline to hardware DMA stride requirement
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Tommaso Merciai <[email protected]>
commit 56c29fa3ee666197516a231e75aed789ae9c530d upstream.
The RZ/G3E CRU programs the line stride via the AMnIS register, whose IS field encodes the value in units of 128 bytes. If bytesperline is not a multiple of 128, the division truncates and the hardware uses a wrong stride, causing horizontal banding.
Commit ace92ccef0c9 ("media: platform: rzg2l-cru: Use v4l2_fill_pixfmt()") replaced the open-coded aligned calculation with v4l2_fill_pixfmt(), which sets no alignment, reintroducing the issue.
Round bytesperline up to RZG2L_CRU_STRIDE_ALIGN and recompute sizeimage when info->has_stride is set. RZ/G2L has no AMnIS register and keeps the values from v4l2_fill_pixfmt() unchanged.
--- drivers/media/platform/renesas/rzg2l-cru/rzg2l-video.c | 5 +++++ 1 file changed, 5 insertions(+)
drivers/media/platform/renesas/rzg2l-cru/rzg2l-video.c +5 -0
@@ -851,6 +851,11 @@ static void rzg2l_cru_format_align(strucv4l2_fill_pixfmt (pix, pix->pixelformat, pix->width, pix->height); +if (info->has_stride) { + pix->bytesperline =ALIGN (pix->bytesperline,RZG2L_CRU_STRIDE_ALIGN ); + pix->sizeimage = pix->bytesperline * pix->height; + } +dev_dbg (cru->dev,"Format %ux%u bpl: %u size: %u\n" , pix->width, pix->height, pix->bytesperline, pix->sizeimage); }
Greg Kroah-Hartman
maintainerPATCH 392/556 media: s2255: bound JPEG frame size before copying into the buffer
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: HyeongJun An <[email protected]>
commit e504cc888f42999dd76b6a43788c422610f2aad2 upstream.
s2255_fillbuff() memcpy()s vc->jpg_size bytes of a captured JPEG/MJPEG frame into the vb2 plane. vc->jpg_size is taken verbatim from the S2255_MARKER_FRAME header the device sends (pdword[4] in save_frame()) and, unlike the frame payload length just above it, is never bounded:
payload = le32_to_cpu(pdword[3]); if (payload > vc->req_image_size) /* payload is checked ... */ return -EINVAL; vc->pkt_size = payload; vc->jpg_size = le32_to_cpu(pdword[4]); /* ... jpg_size is not */
A malicious or malfunctioning device can therefore report a jpg_size larger than the destination vb2 plane, and the memcpy() writes past it. jpg_size is a signed int, so a value with the top bit set also turns into a huge length.
Reject a frame whose jpg_size is negative or exceeds the plane size before copying it.
--- drivers/media/usb/s2255/s2255drv.c | 6 ++++++ 1 file changed, 6 insertions(+)
drivers/media/usb/s2255/s2255drv.c +6 -0
@@ -617,6 +617,12 @@ static void s2255_fillbuff(struct s2255_break ;case V4L2_PIX_FMT_JPEG :case V4L2_PIX_FMT_MJPEG : +if (jpgsize <0 || + jpgsize >vb2_plane_size (&buf->vb.vb2_buf,0 )) { +dprintk (dev,1 ,"bad JPEG frame size %d\n" , + jpgsize); +break ; + }vb2_set_plane_payload (&buf->vb.vb2_buf,0 , jpgsize);memcpy (vbuf, tmpbuf, jpgsize);break ;
Greg Kroah-Hartman
maintainerPATCH 393/556 media: s2255: check firmware size before reading trailing marker
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Lei Huang <[email protected]>
commit 330f2936ab768c7215322a476f033143e8891d28 upstream.
s2255_probe() reads a 4-byte marker and version from the last 8 bytes of the firmware blob (fw->data[fw_size - 8] and [fw_size - 4]). If the firmware file is shorter than 8 bytes, fw_size - 8 underflows and the access reads out of bounds. Validate the firmware size before indexing.
--- drivers/media/usb/s2255/s2255drv.c | 5 +++++ 1 file changed, 5 insertions(+)
drivers/media/usb/s2255/s2255drv.c +5 -0
@@ -2283,6 +2283,11 @@ static int s2255_probe(struct usb_interf }/* check the firmware is valid */ fw_size = dev->fw_data->fw->size; +if (fw_size <8 ) { +dev_err (&interface->dev,"Firmware invalid: too small.\n" ); + retval = -ENODEV ; + goto errorFWMARKER; + } pdata = (__le32 *) &dev->fw_data->fw->data[fw_size -8 ];if (*pdata !=S2255_FW_MARKER ) {
Greg Kroah-Hartman
maintainerPATCH 394/556 media: saa7164: fix cleanup on resource allocation failure
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Guangshuo Li <[email protected]>
commit 28e84c6e2e6753ed238ea097b2842a32a6a6879b upstream.
saa7164_dev_setup() adds the device to the global saa7164_devlist before requesting the PCI BAR memory regions.
If get_resources() fails, saa7164_dev_setup() decrements the device count and returns an error, but leaves the device on saa7164_devlist. The probe error path then frees the device, leaving a dangling entry on the global list.
Reuse the existing MMIO mapping error path to remove the device from saa7164_devlist and decrement the device count before returning.
Also release BAR0 if it was successfully requested but the BAR2 request fails.
--- drivers/media/pci/saa7164/saa7164-core.c | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-)
drivers/media/pci/saa7164/saa7164-core.c +5 -3
@@ -878,6 +878,9 @@ static int get_resources(struct saa7164_if (request_mem_region (pci_resource_start (dev->pci,2 ),pci_resource_len (dev->pci,2 ), dev->name))return 0 ; + +release_mem_region (pci_resource_start (dev->pci,0 ), +pci_resource_len (dev->pci,0 )); } printk(KERN_ERR "%s: can't get MMIO memory @ 0x%llx or 0x%llx\n",
@@ -1000,8 +1003,7 @@ static int saa7164_dev_setup(struct saa7 dev->name, dev->pci->subsystem_vendor, dev->pci->subsystem_device); - saa7164_devcount--; -return -ENODEV ; + goto err_devlist; }/* PCI/e allocations */
@@ -1039,7 +1041,7 @@ err_ioremap_bar2:iounmap (dev->lmmio); err_ioremap_bar0:release_resources (dev); - +err_devlist: scoped_guard(mutex, &devlist) {list_del (&dev->devlist); }
Greg Kroah-Hartman
maintainerPATCH 395/556 media: tda18250: fix possible integer overflow
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Ilya Krutskih <[email protected]>
commit 6dd8e257f7cafda7fbf10d81b3c55c9bba4825f4 upstream.
Integer overflow may occur, when variable exp equals to zero. Result of shift 1 << (exp - 1) may then leads to undefined behavior.
--- drivers/media/tuners/tda18250.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
drivers/media/tuners/tda18250.c +2 -2
@@ -440,8 +440,8 @@ static int tda18250_pll_calc(struct dvb_ goto err; exp = (uval &0x70 ) >>4 ; -if (exp >5 ) - exp =0 ; +if (exp ==0 || exp >5 ) + exp =1 ; lopd =1 << (exp -1 ); scale = uval &0x0f ; fvco = lopd * scale * ((c->frequency /1000 ) + dev->if_frequency);
Greg Kroah-Hartman
maintainerPATCH 396/556 media: ti: vpe: quiesce overflow recovery before freeing streams
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Fan Wu <[email protected]>
commit aeaacc3001449d44b4ab7da56331121d1f3b137b upstream.
The VIP overflow recovery worker is armed from the hardirq handler when a FIFO overflow is detected, and the list-complete path looks the stream up through the VPDMA list private pointer. Both keep touching stream, port and device state; the recovery worker also resets the parser and VPDMA, repopulates the descriptor list, and re-enables the per-list IRQs.
vip_stop_streaming() masks and clears the per-list IRQs, but it neither synchronizes the hardirq handler nor disables recovery_work. An overflow IRQ that has already queued recovery_work, or a list-complete IRQ in flight when the stream is torn down, can therefore still dereference the stream after its resources are released: the descriptor list is freed by vip_release_stream() on file release, and the stream itself by free_stream() on unbind/remove.
Drain the recovery worker and the IRQ handler at both teardown points through a shared vip_quiesce_stream() helper, before any stream-owned resource is released. disable_work_sync() cancels pending recovery_work, drains a running instance, and raises its disable depth, so a subsequent schedule_work() issued by a racing IRQ handler is rejected at the workqueue scheduler: recovery_work cannot be requeued after disable_work_sync() takes effect. The worker may still re-enable the per-list IRQs before disable_work_sync() returns; disable_irqs() then masks those sources and synchronize_irq() waits for any in-flight handler that still dereferences stream state. In vip_stop_streaming() the helper runs before the parser is stopped, since a worker drained by disable_work_sync() may re-enable the parser before exiting and would otherwise undo the stop. recovery_work is created disabled and enabled in vip_start_streaming() before IRQs, pairing the enable with the teardown disable across the streaming lifecycle.
This issue was found by an in-house static analysis tool and confirmed by manual code review.
--- drivers/media/platform/ti/vpe/vip.c | 37 ++++++++++++++++++++++++++++++++---- 1 file changed, 33 insertions(+), 4 deletions(-)
drivers/media/platform/ti/vpe/vip.c +33 -4
@@ -815,6 +815,22 @@ static void clear_irqs(struct vip_dev *dvpdma_clear_list_stat (dev->shared->vpdma, irq_num, dev->slice_id); } +/* +* Quiesce recovery work and per-list IRQs before releasing stream resources. +* disable_work_sync() prevents the overflow handler from requeueing recovery +* work. Mask and synchronize IRQs afterwards because a running worker may +* have re-enabled them before exiting. +*/ +static void vip_quiesce_stream (struct vip_stream *stream) +{ +struct vip_dev *dev = stream->port->dev; + +disable_work_sync (&stream->recovery_work); +disable_irqs (dev, dev->slice_id, stream->list_num); +clear_irqs (dev, dev->slice_id, stream->list_num); +synchronize_irq (dev->irq); +} +static void populate_desc_list (struct vip_stream *stream) {struct vip_port *port = stream->port;
@@ -2429,6 +2445,7 @@ static int vip_start_streaming(struct vb goto err; stream->num_recovery =0 ; +enable_work (&stream->recovery_work);clear_irqs (dev, dev->slice_id, stream->list_num);enable_irqs (dev, dev->slice_id, stream->list_num);
@@ -2453,13 +2470,17 @@ static void vip_stop_streaming(struct vbstruct vip_dev *dev = port->dev;int ret; +/* +* A running recovery worker may re-enable the parser, so quiesce it +* and its IRQ handler before stopping the parser or releasing the +* descriptor list. +*/ +vip_quiesce_stream (stream); +vip_parser_stop_imm (port, true);vip_enable_parser (port, false);unset_fmt_params (stream); -disable_irqs (dev, dev->slice_id, stream->list_num); -clear_irqs (dev, dev->slice_id, stream->list_num); -if (port->subdev) { ret =v4l2_subdev_call (port->subdev, video, s_stream,0 );if (ret)
@@ -3075,6 +3096,8 @@ static int alloc_stream(struct vip_port goto do_free_hwlist;INIT_WORK (&stream->recovery_work, vip_overflow_recovery_work); +/* Start disabled; vip_start_streaming() enables it before IRQs. */ +disable_work (&stream->recovery_work);INIT_LIST_HEAD (&stream->vidq);
@@ -3140,6 +3163,13 @@ static void free_stream(struct vip_streareturn ; dev = stream->port->dev; +/* +* Quiesce the IRQ handler and recovery worker, then drop the stream +* from cap_streams[], before releasing stream-owned resources. +*/ +vip_quiesce_stream (stream); + stream->port->cap_streams[stream->stream_id] =NULL ; +/* Free up the Drop queue */ list_for_each_safe (pos, q, &stream->dropq) { buf = list_entry(pos,
@@ -3151,7 +3181,6 @@ static void free_stream(struct vip_streavideo_unregister_device (stream->vfd);vpdma_hwlist_release (dev->shared->vpdma, stream->list_num); - stream->port->cap_streams[stream->stream_id] =NULL ;kfree (stream); }
Greg Kroah-Hartman
maintainerPATCH 397/556 media: v4l2-async: avoid deleting unlinked ASC entry on link error
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Xu Rao <[email protected]>
commit 47d82b605351c0e04f6365e42c8ffe2fcfdba615 upstream.
v4l2_async_match_notify() creates ancillary media links before adding asc->asc_subdev_entry to sd->asc_list.
If ancillary link creation fails, the function jumps to err_call_unbind while asc_subdev_entry has not been linked yet. Async connections are zero-allocated, so the list entry still has NULL next and prev pointers on this path. Calling list_del() on it can therefore dereference NULL instead of returning the original link creation error.
Do not delete asc_subdev_entry from err_call_unbind. There is no list insertion to undo on this path; the bound callback and sub-device registration are the operations that need to be rolled back.
--- drivers/media/v4l2-core/v4l2-async.c | 1 - 1 file changed, 1 deletion(-)
drivers/media/v4l2-core/v4l2-async.c +0 -1
@@ -392,7 +392,6 @@ static int v4l2_async_match_notify(struc err_call_unbind:v4l2_async_nf_call_unbind (notifier, sd, asc); -list_del (&asc->asc_subdev_entry); err_unregister_subdev:if (registered)
Greg Kroah-Hartman
maintainerPATCH 398/556 media: v4l2-ctrls: validate HEVC EXT SPS RPS counts
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Michael Bommarito <[email protected]>
commit 796b5c6d4f1615d59d5d8fe5a38fae6bfdfe878e upstream.
The HEVC SPS control carries the short-term and long-term RPS counts that decoder drivers use to walk the matching EXT SPS dynamic arrays. Reject SPS values that exceed the HEVC limits of 64 short-term sets and 32 long-term references so drivers cannot later index beyond those controls.
Also reject EXT SPS ST RPS entries whose negative or positive picture counts exceed the 16-entry arrays, or whose combined delta-POC count exceeds the HEVC DPB maximum.
--- drivers/media/v4l2-core/v4l2-ctrls-core.c | 15 +++++++++++++++ 1 file changed, 15 insertions(+)
drivers/media/v4l2-core/v4l2-ctrls-core.c +15 -0
@@ -16,6 +16,9 @@static const union v4l2_ctrl_ptr ptr_null; +#define V4L2_HEVC_MAX_SHORT_TERM_REF_PIC_SETS 64 +#define V4L2_HEVC_MAX_LONG_TERM_REF_PICS_SPS 32 +static void fill_event (struct v4l2_event *ev,struct v4l2_ctrl *ctrl,u32 changes) {
@@ -1214,6 +1217,10 @@ static int std_validate_compound(const scase V4L2_CTRL_TYPE_HEVC_SPS : p_hevc_sps = p; +if (p_hevc_sps->num_short_term_ref_pic_sets > +V4L2_HEVC_MAX_SHORT_TERM_REF_PIC_SETS ) +return -EINVAL ; +if (!(p_hevc_sps->flags &V4L2_HEVC_SPS_FLAG_PCM_ENABLED )) { p_hevc_sps->pcm_sample_bit_depth_luma_minus1 =0 ; p_hevc_sps->pcm_sample_bit_depth_chroma_minus1 =0 ;
@@ -1224,6 +1231,9 @@ static int std_validate_compound(const sif (!(p_hevc_sps->flags &V4L2_HEVC_SPS_FLAG_LONG_TERM_REF_PICS_PRESENT )) p_hevc_sps->num_long_term_ref_pics_sps =0 ; +else if (p_hevc_sps->num_long_term_ref_pics_sps > +V4L2_HEVC_MAX_LONG_TERM_REF_PICS_SPS ) +return -EINVAL ;break ;case V4L2_CTRL_TYPE_HEVC_PPS :
@@ -1280,6 +1290,11 @@ static int std_validate_compound(const sif (p_hevc_st_rps->flags & ~V4L2_HEVC_EXT_SPS_ST_RPS_FLAG_INTER_REF_PIC_SET_PRED )return -EINVAL ; +if (p_hevc_st_rps->num_negative_pics >16 || + p_hevc_st_rps->num_positive_pics >16 || + p_hevc_st_rps->num_negative_pics + + p_hevc_st_rps->num_positive_pics >16 ) +return -EINVAL ;break ;case V4L2_CTRL_TYPE_HEVC_EXT_SPS_LT_RPS :
Greg Kroah-Hartman
maintainerPATCH 399/556 media: v4l2-ctrls: Allow unknown HDR10 white point and luminance
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Ming Qian <[email protected]>
commit 49af0c7cad889f7dabe5cf080b019392066122a3 upstream.
SMPTE ST 2086 defines the nominal ranges for mastering display chromaticity and luminance values. Its Annex A also documents that CTA 861-G uses zero maximum and minimum luminance values to signal that the corresponding values are unknown, and the xy chromaticity coordinate (0, 0) to signal that the white point chromaticity is unknown.
The V4L2 HDR10 mastering display compound control currently rejects these values. Consequently, an unknown white point or luminance value prevents the entire compound control from being updated, making the other valid mastering display metadata unavailable to userspace.
Accept (0, 0) as an unknown white point and zero as an unknown maximum or minimum mastering luminance. Continue to reject partially zero white point coordinates and non-zero values outside the nominal ranges. Display primary validation remains unchanged.
Document the newly accepted unknown values in the V4L2 userspace API.
--- Documentation/userspace-api/media/v4l/ext-ctrls-colorimetry.rst | 12 ++ drivers/media/v4l2-core/v4l2-ctrls-core.c | 49 ++++++---- 2 files changed, 44 insertions(+), 17 deletions(-)
Documentation/userspace-api/media/v4l/ext-ctrls-colorimetry.rst +11 -1
@@ -80,15 +80,25 @@ Colorimetry Control IDs - ``white_point_x`` - Specifies the normalized x chromaticity coordinate of the white point of the mastering display in increments of 0.00002. + When both ``white_point_x`` and ``white_point_y`` are zero, + the white point chromaticity is unknown. If either coordinate is + non-zero, both coordinates shall be within their valid ranges. * - __u16 - ``white_point_y`` - Specifies the normalized y chromaticity coordinate of the white point of the mastering display in increments of 0.00002. + When both ``white_point_x`` and ``white_point_y`` are zero, + the white point chromaticity is unknown. If either coordinate is + non-zero, both coordinates shall be within their valid ranges. * - __u32 - ``max_luminance`` - Specifies the nominal maximum display luminance of the mastering display in units of 0.0001 cd/m\ :sup:`2`. + A value of zero indicates that the nominal maximum display + luminance is unknown. * - __u32 - ``min_luminance`` - - specifies the nominal minimum display luminance of the mastering + - Specifies the nominal minimum display luminance of the mastering display in units of 0.0001 cd/m\ :sup:`2`. + A value of zero indicates that the nominal minimum display + luminance is unknown.
drivers/media/v4l2-core/v4l2-ctrls-core.c +33 -16
57 lines not on this page · raw message
Greg Kroah-Hartman
maintainerPATCH 400/556 media: v4l2-fwnode: Fix fwnode leak in v4l2_fwnode_parse_link
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Biren Pandya <[email protected]>
commit a6e86efd7f85e519bf48417f41923f8bd51f1597 upstream.
In v4l2_fwnode_parse_link(), the remote endpoint fwnode reference is acquired using fwnode_graph_get_remote_endpoint(). This reference is properly released in the error paths, but it is leaked on the success path.
Add the missing fwnode_handle_put() before returning 0 to prevent the reference leak.
--- drivers/media/v4l2-core/v4l2-fwnode.c | 2 ++ 1 file changed, 2 insertions(+)
drivers/media/v4l2-core/v4l2-fwnode.c +2 -0
@@ -633,6 +633,8 @@ int v4l2_fwnode_parse_link(struct fwnodeif (!link->remote_node) goto err_put_remote_endpoint; +fwnode_handle_put (fwnode); +return 0 ; err_put_remote_endpoint:
Greg Kroah-Hartman
maintainerPATCH 401/556 media: venus: fix payload size returned by parse_caps() and parse_alloc_mode()
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Mohammed EL Kadiri <[email protected]>
commit a51cea23e409278f6e2ea072280aba93cc1dd75e upstream.
parse_caps() and parse_alloc_mode() return only the size of their fixed header fields, excluding the flexible array payload. hfi_parser() uses this return value to advance through the firmware response buffer, so underreporting causes parser desynchronization.
Return the full consumed size (header + entries), matching the correct pattern used by parse_profile_level().
--- drivers/media/platform/qcom/venus/hfi_parser.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
drivers/media/platform/qcom/venus/hfi_parser.c +2 -2
@@ -85,7 +85,7 @@ parse_alloc_mode(struct venus_core *core type++; } -return sizeof (*mode); +return mode->num_entries *sizeof (u32) +sizeof (*mode); } static void fill_profile_level(struct hfi_plat_caps *cap, const void *data,
@@ -146,7 +146,7 @@ parse_caps(struct venus_core *core, u32for_each_codec (core->caps,ARRAY_SIZE (core->caps), codecs, domain, fill_caps, caps_arr, num_caps); -return sizeof (*caps); +return num_caps *sizeof (*cap) +sizeof (u32); } static void fill_raw_fmts(struct hfi_plat_caps *cap, const void *fmts,
Greg Kroah-Hartman
maintainerPATCH 402/556 media: venus: fix payload size calculation in parse_raw_formats()
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Mohammed EL Kadiri <[email protected]>
commit bd595b745eb770e80347c31ffc25351046935305 upstream.
The consumed size is computed after the loop using the num_planes value from the last iteration for all entries. When entries have different plane counts, this produces an incorrect total.
Accumulate the actual size during the loop instead.
--- drivers/media/platform/qcom/venus/hfi_parser.c | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-)
drivers/media/platform/qcom/venus/hfi_parser.c +2 -3
@@ -171,7 +171,7 @@ parse_raw_formats(struct venus_core *coru32 entries = fmt->format_entries;unsigned int i =0 ;u32 num_planes =0 ; -u32 size; +u32 size =2 *sizeof (u32);while (entries) { num_planes = pinfo->num_planes;
@@ -186,6 +186,7 @@ parse_raw_formats(struct venus_core *corif (pinfo->num_planes >MAX_PLANES )break ; + size +=sizeof (*constr) * num_planes +2 *sizeof (u32); pinfo = (void *)pinfo +sizeof (*constr) * num_planes +2 *sizeof (u32); entries--;
@@ -193,8 +194,6 @@ parse_raw_formats(struct venus_core *corfor_each_codec (core->caps,ARRAY_SIZE (core->caps), codecs, domain, fill_raw_fmts, rawfmts, i); - size = fmt->format_entries * (sizeof (*constr) * num_planes +2 *sizeof (u32)) - +2 *sizeof (u32);return size; }
Greg Kroah-Hartman
maintainerPATCH 403/556 media: video-i2c: fix kthread error pointer left in kthread_vid_cap on failure
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Uday Khare <[email protected]>
commit 76e379754ba618989f6215be608d5c04774a611d upstream.
kthread_run() returns an ERR_PTR on failure, not NULL. When start_streaming() fails, data->kthread_vid_cap is left holding this error pointer instead of being cleared.
This causes two subsequent bugs:
1. A future call to start_streaming() sees a non-NULL kthread_vid_cap and returns 0 (success) immediately, without actually starting the capture thread.
2. A call to stop_streaming() checks 'kthread_vid_cap == NULL' which is false for an error pointer, and proceeds to call kthread_stop() on the error pointer, leading to a kernel crash.
Fix this by resetting kthread_vid_cap to NULL on failure before jumping to the error path.
--- drivers/media/i2c/video-i2c.c | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-)
drivers/media/i2c/video-i2c.c +6 -2
@@ -522,8 +522,12 @@ static int start_streaming(struct vb2_qu data->kthread_vid_cap =kthread_run (video_i2c_thread_vid_cap, data,"%s-vid-cap" , data->v4l2_dev.name); ret =PTR_ERR_OR_ZERO (data->kthread_vid_cap); -if (!ret) -return 0 ; +if (ret) { + data->kthread_vid_cap =NULL ; + goto error_rpm_put; + } + +return 0 ; error_rpm_put:pm_runtime_put_autosuspend (dev);
Greg Kroah-Hartman
maintainerPATCH 404/556 media: vimc: fix pixel format lookup in enum_framesizes
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Arash Golgol <[email protected]>
commit ad4c65fa30cfb00e2e06adae9a8eb407086eaa66 upstream.
vimc_capture_enum_framesizes() looks up the requested format using vimc_pix_map_by_code(), which searches the pix map table by media bus code (MEDIA_BUS_FMT_*).
However, v4l2_frmsizeenum::pixel_format holds a V4L2 pixel format (V4L2_PIX_FMT_*), not a media bus code, so valid pixel formats end up being rejected with -EINVAL.
Fix this by using vimc_pix_map_by_pixelformat() instead, which performs the lookup by pixel format as the ioctl expects.
--- drivers/media/test-drivers/vimc/vimc-capture.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
drivers/media/test-drivers/vimc/vimc-capture.c +2 -2
@@ -175,8 +175,8 @@ static int vimc_capture_enum_framesizes(if (fsize->index)return -EINVAL ; -/* Only accept code in the pix map table */ - vpix =vimc_pix_map_by_code (fsize->pixel_format); +/* Only accept pixel_format in the pix map table */ + vpix =vimc_pix_map_by_pixelformat (fsize->pixel_format);if (!vpix)return -EINVAL ;
Greg Kroah-Hartman
maintainerPATCH 405/556 media: zoran: Avoid freeing a registered video_device twice
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Ruoyu Wang <[email protected]>
commit 0735e0b5a96761a9ce277a238e834008ad92a0a5 upstream.
zoran_init_video_device() installs zoran_vdev_release() as the video_device release callback through zoran_template. After video_register_device() succeeds, video_unregister_device() drops the registered video_device reference and the V4L2 core eventually invokes that release callback, which kfree()s the video_device.
zoran_exit_video_devices() called video_unregister_device() and then kfree(zr->video_dev), so device teardown could free the same video_device twice.
Remove the direct kfree() and clear the cached pointer after unregistering. The pre-registration failure path keeps its manual free because the video_device was not registered there.
This issue was found by a static analysis checker and confirmed by manual source review.
--- drivers/media/pci/zoran/zoran_card.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/media/pci/zoran/zoran_card.c +1 -1
@@ -885,7 +885,7 @@ static int zoran_init_video_device(strucstatic void zoran_exit_video_devices (struct zoran *zr) {video_unregister_device (zr->video_dev); -kfree (zr->video_dev); + zr->video_dev =NULL ; }static int zoran_init_video_devices (struct zoran *zr)
Greg Kroah-Hartman
maintainerPATCH 406/556 media: qcom: iris: fix state-change debug log printing stale value
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Dikshita Agarwal <[email protected]>
commit 460d3257a6dffc7f0bf58009daeb7e0b6eb2d9d3 upstream.
The state‑change debug log in iris_inst_change_state() always prints the same value for the old and new state, rendering it useless for debugging. This happens because the state is updated before the log is emitted.
Log the transition before updating the state so the previous value is preserved, consistent with the existing sub‑state handling.
--- drivers/media/platform/qcom/iris/iris_state.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/media/platform/qcom/iris/iris_state.c +1 -1
@@ -60,9 +60,9 @@ int iris_inst_change_state(struct iris_ireturn -EINVAL ; change_state: - inst->state = request_state;dev_dbg (inst->core->dev,"state changed from %x to %x\n" , inst->state, request_state); + inst->state = request_state;return 0 ; }
Greg Kroah-Hartman
maintainerPATCH 407/556 media: qcom: iris: use disable_irq() during power-off
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Hungyu Lin <[email protected]>
commit b9c2215bdedc9c532a7e9d57ec49ee1b6381f863 upstream.
The IRQ is registered as a threaded IRQ.
Using disable_irq_nosync() in iris_vpu_power_off() does not wait for an already queued threaded IRQ handler to complete before returning.
As a result, a threaded IRQ handler may still run after the VPU has been powered down and access hardware registers after power-off.
Replace disable_irq_nosync() with disable_irq() so the power-off path waits for any in-flight threaded IRQ handler to complete before returning.
--- drivers/media/platform/qcom/iris/iris_vpu_common.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/media/platform/qcom/iris/iris_vpu_common.c +1 -1
@@ -237,7 +237,7 @@ void iris_vpu_power_off(struct iris_coreiris_unset_icc_bw (core);if (!iris_vpu_watchdog (core, core->intr_status)) -disable_irq_nosync (core->irq); +disable_irq (core->irq); }int iris_vpu_power_on_controller (struct iris_core *core)
Greg Kroah-Hartman
maintainerPATCH 408/556 media: qcom: iris: fix missing hfi_id in gen1 GOP_SIZE cap
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Wangao Wang <[email protected]>
commit 5eebacbc9a38e1019854ea5f86e367a4d5116387 upstream.
Add hfi_id to gen1 encoder GOP_SIZE cap and replace the set function, remove the redundant INTRA_PERIOD cap.
--- drivers/media/platform/qcom/iris/iris_ctrls.c | 2 +- drivers/media/platform/qcom/iris/iris_hfi_gen1.c | 16 ++++------------ drivers/media/platform/qcom/iris/iris_platform_common.h | 1 - 3 files changed, 5 insertions(+), 14 deletions(-)
drivers/media/platform/qcom/iris/iris_ctrls.c +1 -1
@@ -1293,7 +1293,7 @@ int iris_set_use_and_mark_ltr(struct iriint iris_set_intra_period (struct iris_inst *inst,enum platform_inst_fw_cap_type cap_id) {const struct iris_hfi_session_ops *hfi_ops = inst->hfi_session_ops; -u32 gop_size = inst->fw_caps[GOP_SIZE ].value; +u32 gop_size = inst->fw_caps[cap_id].value;u32 b_frame = inst->fw_caps[B_FRAME ].value;u32 hfi_id = inst->fw_caps[cap_id].hfi_id;struct hfi_intra_period intra_period;
drivers/media/platform/qcom/iris/iris_hfi_gen1.c +4 -12
@@ -171,7 +171,9 @@ static const struct platform_inst_fw_cap .max = (1 << 16) - 1, .step_or_mask = 1, .value = 30, - .set = iris_set_u32 + .hfi_id = HFI_PROPERTY_CONFIG_VENC_INTRA_PERIOD, + .flags = CAP_FLAG_OUTPUT_PORT, + .set = iris_set_intra_period, }, { .cap_id = ENTROPY_MODE,
@@ -240,7 +242,7 @@ static const struct platform_inst_fw_cap .step_or_mask = 1, .value = 0, .hfi_id = HFI_PROPERTY_PARAM_VENC_INTRA_REFRESH, - .flags = CAP_FLAG_OUTPUT_PORT, + .flags = CAP_FLAG_OUTPUT_PORT | CAP_FLAG_DYNAMIC_ALLOWED, .set = iris_set_ir_period_gen1, }, {
@@ -282,16 +284,6 @@ static const struct platform_inst_fw_cap .flags = CAP_FLAG_OUTPUT_PORT, }, { - .cap_id = INTRA_PERIOD, - .min = 0, - .max = 1, - .step_or_mask = 1, - .value = 0, - .hfi_id = HFI_PROPERTY_CONFIG_VENC_INTRA_PERIOD, - .flags = CAP_FLAG_OUTPUT_PORT, - .set = iris_set_intra_period, - }, - { .cap_id = LAYER_ENABLE, .min = 0, .max = 1,
drivers/media/platform/qcom/iris/iris_platform_common.h +0 -1
@@ -165,7 +165,6 @@ enum platform_inst_fw_cap_type {USE_LTR ,MARK_LTR ,B_FRAME , -INTRA_PERIOD ,LAYER_ENABLE ,LAYER_TYPE_H264 , LAYER_TYPE_HEVC,
Greg Kroah-Hartman
maintainerPATCH 409/556 media: chips-media: wave5: Guard bit depth check with initial_info_obtained
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jackson Lee <[email protected]>
commit 1551386934ad43d934c3bb7317929207e1edcd6a upstream.
When CAPTURE STREAMON is called before the VPU has completed sequence initialization (initial_info_obtained == false), the initial_info fields contain uninitialized data. The driver checksluma_bitdepth and rejects anything other than 8-bit, so garbage values (e.g. 15) cause STREAMON to fail spuriously.
This is reproducible with the following multi-threaded test scenario:
1. Allocate 2 CAPTURE buffers.
2. Call STREAMON on the CAPTURE queue.
3. Call DQBUF, which blocks waiting for a decoded frame.
4. A second thread calls STREAMOFF on the CAPTURE queue.
5. The blocked DQBUF should be released, allowing graceful termination.
At step 2, STREAMON reads uninitialized luma_bitdepth and rejects the stream, causing the test to fail.
Fix this by checking initial_info_obtained before accessing the bit depth fields, so the validation is only performed when the sequence info has actually been parsed by the VPU.
--- drivers/media/platform/chips-media/wave5/wave5-vpu-dec.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/media/platform/chips-media/wave5/wave5-vpu-dec.c +2 -1
@@ -1403,6 +1403,7 @@ static int wave5_vpu_dec_start_streaming }else if (q->type ==V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE ) {struct dec_initial_info *initial_info = &inst->codec_info->dec_info.initial_info; +struct dec_info *p_dec_info = &inst->codec_info->dec_info;if (inst->state ==VPU_INST_STATE_STOP ) ret =switch_state (inst,VPU_INST_STATE_INIT_SEQ );
@@ -1410,6 +1411,7 @@ static int wave5_vpu_dec_start_streaming goto return_buffers;if (inst->state ==VPU_INST_STATE_INIT_SEQ && + p_dec_info->initial_info_obtained && inst->dev->product_code ==WAVE521C_CODE ) {if (initial_info->luma_bitdepth !=8 ) { dev_info(inst->dev->dev, "%s: no support for %d bit depth",
@@ -1418,7 +1420,6 @@ static int wave5_vpu_dec_start_streaming goto return_buffers; } } - }pm_runtime_put_autosuspend (inst->dev->dev);return ret;
Greg Kroah-Hartman
maintainerPATCH 410/556 media: chips-media: wave5: Set inst->std during default format initialization
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jackson Lee <[email protected]>
commit cfcefc5a996f6a00b310c963b5f811430f28a30a upstream.
When the encoder is opened, wave5_set_default_format() sets up the default capture format (e.g. H.264) but does not initialize inst->std. As a result, inst->std remains zero, which does not match any valid encoder codec.
If STREAMON is called before the user explicitly calls S_FMT on the capture queue — as v4l2-compliance does in testBlockingDQBuf — the codec/product check in wave5_vpu_enc_init_seq() fails with "Unsupported encoder-codec & product combination" because inst->std is neither W_HEVC_ENC nor W_AVC_ENC, returning -EOPNOTSUPP.
Fix this by setting inst->std via wave5_to_vpu_std() in wave5_set_default_format(), so that the codec type is always consistent with the default capture pixel format from the moment the instance is opened.
--- drivers/media/platform/chips-media/wave5/wave5-vpu-enc.c | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-)
drivers/media/platform/chips-media/wave5/wave5-vpu-enc.c +4 -2
@@ -1494,7 +1494,8 @@ static const struct vb2_ops wave5_vpu_en .stop_streaming = wave5_vpu_enc_stop_streaming, }; -static void wave5_set_default_format (struct v4l2_pix_format_mplane *src_fmt, +static void wave5_set_default_format (struct vpu_instance *inst, +struct v4l2_pix_format_mplane *src_fmt,struct v4l2_pix_format_mplane *dst_fmt) { src_fmt->pixelformat = enc_fmt_list[VPU_FMT_TYPE_RAW ][0 ].v4l2_pix_fmt;
@@ -1506,6 +1507,7 @@ static void wave5_set_default_format(strwave5_update_pix_fmt (dst_fmt,VPU_FMT_TYPE_CODEC ,W5_DEF_ENC_PIC_WIDTH ,W5_DEF_ENC_PIC_HEIGHT , &enc_frmsize[VPU_FMT_TYPE_CODEC ]); + inst->std =wave5_to_vpu_std (dst_fmt->pixelformat, inst->type); }static int wave5_vpu_enc_queue_init (void *priv,struct vb2_queue *src_vq,struct vb2_queue *dst_vq)
@@ -1770,7 +1772,7 @@ static int wave5_vpu_open_enc(struct fil inst->v4l2_fh.ctrl_handler = v4l2_ctrl_hdl;v4l2_ctrl_handler_setup (v4l2_ctrl_hdl); -wave5_set_default_format (&inst->src_fmt, &inst->dst_fmt); +wave5_set_default_format (inst, &inst->src_fmt, &inst->dst_fmt); inst->conf_win.width = inst->dst_fmt.width; inst->conf_win.height = inst->dst_fmt.height; inst->colorspace =V4L2_COLORSPACE_REC709 ;
Greg Kroah-Hartman
maintainerPATCH 411/556 media: chips-media: wave5: avoid skipping device_run while VPU has work
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jackson Lee <[email protected]>
commit 8c5a74a24cbbba9142e38c463c96435d316149ce upstream.
The decoder stalls because empty_queue is set to true even when the m2m context still has pending commands. As a result, device_run is never invoked, the m2m source queue fills up, and userspace (e.g. Chromium) can no longer queue new bitstream buffers to the V4L2 driver.
Fix this by querying the VPU queue status via DEC_GET_QUEUE_STATUS before deciding whether to skip device_run. Only skip when the VPU's instance_queue_count equals the number of ready source buffers in the v4l2-m2m context, which indicates that there is genuinely no new work to perform. Otherwise, proceed with issuing a decode command so that the VPU can continue draining its internal queue.
--- .../media/platform/chips-media/wave5/wave5-vpu-dec.c | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-)
drivers/media/platform/chips-media/wave5/wave5-vpu-dec.c +7 -3
@@ -1663,9 +1663,13 @@ static void wave5_vpu_dec_device_run(void *priv) }else if (!inst->eos && inst->queuing_num ==0 && inst->state ==VPU_INST_STATE_PIC_RUN ) { -dev_dbg (inst->dev->dev,"%s: no bitstream for feeding, so skip " , __func__); - inst->empty_queue = true; - goto finish_job_and_return; +wave5_vpu_dec_give_command (inst,DEC_GET_QUEUE_STATUS , &q_status); +if (q_status.instance_queue_count ==v4l2_m2m_num_src_bufs_ready (m2m_ctx)) { +dev_dbg (inst->dev->dev,"%s: no bitstream, skip\n" , + __func__); + inst->empty_queue = true; + goto finish_job_and_return; + } } }
Signature · 1 line
2.55.0
Greg Kroah-Hartman
maintainerPATCH 412/556 media: chips-media: wave5: Add timeout while stop_streaming
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jackson Lee <[email protected]>
commit 2ae7faed2e60d6d07d9efdd962d20dcb15330ced upstream.
When stop_streaming is called, an infinite loop may occur in some cases. Add a bounded poll of the queue status: loop until the queues drain, sleeping briefly between polls, and bail out once VPU_DEC_STOP_TIMEOUT elapses.
--- drivers/media/platform/chips-media/wave5/wave5-vpu-dec.c | 15 +++++++------ drivers/media/platform/chips-media/wave5/wave5-vpuconfig.h | 2 - 2 files changed, 10 insertions(+), 7 deletions(-)
drivers/media/platform/chips-media/wave5/wave5-vpu-dec.c +9 -6
@@ -5,6 +5,7 @@* Copyright (C) 2021-2023 CHIPS&MEDIA INC */ +#include <linux/delay.h> #include <linux/pm_runtime.h> #include "wave5-helper.h"
@@ -1537,15 +1538,15 @@ static void wave5_vpu_dec_stop_streaming {struct vpu_instance *inst =vb2_get_drv_priv (q);struct v4l2_m2m_ctx *m2m_ctx = inst->v4l2_fh.m2m_ctx; - -bool check_cmd = TRUE; +unsigned long timeout;dev_dbg (inst->dev->dev,"%s: type: %u\n" , __func__, q->type);pm_runtime_resume_and_get (inst->dev->dev); inst->empty_queue = true; -while (check_cmd) { + + timeout = jiffies +msecs_to_jiffies (VPU_DEC_STOP_TIMEOUT ); +while (true) {struct queue_status_info q_status; -struct dec_output_info dec_output_info;wave5_vpu_dec_give_command (inst,DEC_GET_QUEUE_STATUS , &q_status); if ((inst->state == VPU_INST_STATE_STOP ||
@@ -1554,8 +1555,10 @@ static void wave5_vpu_dec_stop_streaming q_status.report_queue_count == 0)break ; -if (wave5_vpu_dec_get_output_info (inst, &dec_output_info)) -dev_dbg (inst->dev->dev,"there is no output info\n" ); +if (time_after (jiffies, timeout)) +break ; + +usleep_range (1000 ,2000 ); }v4l2_m2m_update_stop_streaming_state (m2m_ctx, q);
drivers/media/platform/chips-media/wave5/wave5-vpuconfig.h +1 -1
@@ -59,7 +59,7 @@// application specific configuration #define VPU_ENC_TIMEOUT 60000#define VPU_DEC_TIMEOUT 60000 -#define VPU_DEC_STOP_TIMEOUT 10 +#define VPU_DEC_STOP_TIMEOUT 300// for WAVE encoder #define USE_SRC_PRP_AXI 0
Greg Kroah-Hartman
maintainerPATCH 413/556 media: chips-media: wave5: Defer job_finish() only when a DEC_PIC was queued
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jackson Lee <[email protected]>
commit b694ba0a5526a69f78a6924982b1553154ccfd73 upstream.
Decoder instances sharing a VPU also share one v4l2_m2m job slot, released when the running context calls v4l2_m2m_job_finish(). While draining, device_run() defers job_finish() once EOS is sent (sent_eos), expecting a later finish_decode() (from a DEC_PIC completion IRQ) to release the slot.
But the m2m core checks job_ready() only when a job is queued, not when it is dispatched. A job queued while draining can run after finish_decode() has already moved the instance to STOP and sent EOS. device_run() then runs in STOP, issues no DEC_PIC, yet still skips job_finish() - so no IRQ, no finish_decode(), and the shared slot is leaked, stalling every instance. With several v4l2h264dec instances in parallel, GStreamer hangs at EOS.
Track whether the run actually queued a DEC_PIC (cmd_issued) and defer job_finish() only then. Otherwise finish the job immediately
--- .../media/platform/chips-media/wave5/wave5-vpu-dec.c | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-)
drivers/media/platform/chips-media/wave5/wave5-vpu-dec.c +11 -1
@@ -1655,6 +1655,7 @@ static void wave5_vpu_dec_device_run(void *priv)struct queue_status_info q_status;u32 fail_res =0 ;int ret =0 ; +bool cmd_issued = false;dev_dbg (inst->dev->dev,"%s: Fill the ring buffer with new bitstream data" , __func__);pm_runtime_resume_and_get (inst->dev->dev);
@@ -1752,6 +1753,7 @@ static void wave5_vpu_dec_device_run(void *priv) inst->retry = false;if (!inst->eos) inst->queuing_num--; + cmd_issued = true; }break ;default :
@@ -1769,8 +1771,16 @@ static void wave5_vpu_dec_device_run(void *priv)* in power and CPU time. * If EOS is passed, device_run will not call job_finish no more, it is called * only if HW is idle status in order to reduce overhead. +* +* Deferring job_finish() is only safe when this run actually queued a +* DEC_PIC command (cmd_issued): that guarantees a completion IRQ, and +* thus a later finish_decode(), will release the shared job slot. When +* device_run() is entered with no command to issue (e.g. a job that was +* queued while draining but reached the STOP state by the time it ran), +* no IRQ follows, so finish the job here to avoid leaking the slot and +* stalling every instance sharing the VPU. */ -if (!inst->sent_eos) +if (!inst->sent_eos || !cmd_issued)v4l2_m2m_job_finish (inst->v4l2_m2m_dev, m2m_ctx); }
Signature · 1 line
2.55.0
Greg Kroah-Hartman
maintainerPATCH 414/556 media: chips-media: wave5: Fix pipeline stall when queuing fails
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jackson Lee <[email protected]>
commit e3a80073d99c376176d81013335cd355af576be2 upstream.
The Wave5 decoder calls v4l2_m2m_job_finish() immediately in device_run() after submitting frames to firmware. When the firmware completes those frames and the queue drains to zero, finish_decode() has no active M2M job to finish, so v4l2_m2m_schedule_next_job() is never called and the decoder stalls.
Call v4l2_m2m_try_schedule() in finish_decode() when the firmware queue empties to ensure the framework always schedules the next device_run().
--- drivers/media/platform/chips-media/wave5/wave5-vpu-dec.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-)
drivers/media/platform/chips-media/wave5/wave5-vpu-dec.c +4 -1
@@ -475,7 +475,10 @@ static void wave5_vpu_dec_finish_decode(struct vpu_instance *inst)v4l2_m2m_job_finish (inst->v4l2_m2m_dev, m2m_ctx); } - inst->queuing_fail = false; +if (inst->queuing_fail) { + inst->queuing_fail = false; +v4l2_m2m_try_schedule (m2m_ctx); + } }static int wave5_vpu_dec_querycap (struct file *file,void *fh,struct v4l2_capability *cap)
Signature · 1 line
2.55.0
Greg Kroah-Hartman
maintainerPATCH 415/556 media: chips-media: wave5: Resume device before setting EOS flag
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Jackson Lee <[email protected]>
commit a52e6f7923c17a672135b485ffd96fbd72f46267 upstream.
Setting the EOS flag talks to the firmware via send_firmware_command(), which accesses VPU registers. Both the STREAMOFF path (wave5_vpu_dec_job_abort()) and the V4L2_DEC_CMD_STOP path (wave5_vpu_dec_stop()) can run while the device is runtime suspended, so those register accesses hit powered-down hardware and the SoC raises an asynchronous SError, panicking the kernel:
SError Interrupt on CPU3, code 0x00000000bf000000 -- SError
send_firmware_command+0x2c/0x160 [wave5] wave5_vpu_dec_set_bitstream_flag+0x6c/0x80 [wave5] wave5_vpu_dec_update_bitstream_buffer+0x80/0xec [wave5] wave5_vpu_dec_job_abort+0x44/0xa0 [wave5] v4l2_m2m_cancel_job+0x110/0x19c [v4l2_mem2mem] v4l2_m2m_streamoff+0x24/0x140 [v4l2_mem2mem]
Resume the device with pm_runtime_resume_and_get() around the EOS firmware command and release it with pm_runtime_put_autosuspend(), matching the runtime PM handling already done in wave5_vpu_dec_device_run().
--- drivers/media/platform/chips-media/wave5/wave5-vpu-dec.c | 19 +++++++++++++++ 1 file changed, 19 insertions(+)
drivers/media/platform/chips-media/wave5/wave5-vpu-dec.c +19 -0
@@ -823,7 +823,15 @@ static int wave5_vpu_dec_stop(struct vpu* calls do not block on a mutex while inside this spinlock. */ spin_unlock_irqrestore (&inst->state_spinlock, flags); +/* +* V4L2_DEC_CMD_STOP can arrive while the device is runtime +* suspended (e.g. on pipeline teardown). Setting the EOS flag +* accesses VPU registers via send_firmware_command(), so the +* device must be resumed first to avoid an asynchronous SError. +*/ +pm_runtime_resume_and_get (inst->dev->dev); ret =wave5_vpu_dec_set_eos_on_firmware (inst); +pm_runtime_put_autosuspend (inst->dev->dev);if (ret)return ret;
@@ -1797,11 +1805,22 @@ static void wave5_vpu_dec_job_abort(voidif (ret)return ; +/* +* job_abort() runs from the STREAMOFF path and may be called while the +* device is runtime suspended. Setting the EOS flag talks to the +* firmware (send_firmware_command() accesses VPU registers), so the +* device must be resumed first; otherwise the register access faults +* with an asynchronous SError. +*/ +pm_runtime_resume_and_get (inst->dev->dev); + ret =wave5_vpu_dec_set_eos_on_firmware (inst);if (ret)dev_warn (inst->dev->dev,"Setting EOS for the bitstream, fail: %d\n" , ret); +pm_runtime_put_autosuspend (inst->dev->dev); +v4l2_m2m_job_finish (inst->v4l2_m2m_dev, m2m_ctx); }
Greg Kroah-Hartman
maintainerPATCH 416/556 scsi: qla2xxx: Zero SFP DMA buffer in FRU/I2C bsg handlers
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Nilesh Javali <[email protected]>
commit b47d4a1547d9ef21b2e9d1a739fe2204d4be05dc upstream.
The FRU and I2C bsg handlers stage their transfer in a DMA_POOL_SIZE (256-byte) bounce buffer obtained from dma_pool_alloc(), which does not zero the allocation. They initialize only a few leading bytes before handing the buffer to qla2x00_write_sfp().
qla2x00_write_sfp() can override the transfer length with a user-supplied value:
if (len == 1) opt |= BIT_0; if (opt & BIT_0) len = *sfp;
*sfp is the first byte of the (user-controlled) payload, so len can grow up to 255. The device then DMA-reads len bytes from the 256-byte pool buffer. Since only a small prefix was written
(e.g. MAX_FRU_SIZE == 36 bytes for a FRU version, one byte for a FRU status register), the hardware reads past the initialized region and writes up to ~219 bytes of stale DMA-pool heap memory to the device flash.
Allocate the buffer with dma_pool_zalloc() in all five FRU/I2C handlers so any bytes beyond the initialized data are zero rather than stale heap contents.
--- drivers/scsi/qla2xxx/qla_bsg.c | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-)
drivers/scsi/qla2xxx/qla_bsg.c +5 -5
@@ -1567,7 +1567,7 @@ qla2x00_update_fru_versions(struct bsg_jstruct qla_image_version *image;uint32_t count;dma_addr_t sfp_dma; -void *sfp =dma_pool_alloc (ha->s_dma_pool,GFP_KERNEL , &sfp_dma); +void *sfp =dma_pool_zalloc (ha->s_dma_pool,GFP_KERNEL , &sfp_dma);if (!sfp) { bsg_reply->reply_data.vendor_reply.vendor_rsp[0] =
@@ -1618,7 +1618,7 @@ qla2x00_read_fru_status(struct bsg_job *uint8_t bsg[DMA_POOL_SIZE ];struct qla_status_reg *sr = (void *)bsg;dma_addr_t sfp_dma; -uint8_t *sfp =dma_pool_alloc (ha->s_dma_pool,GFP_KERNEL , &sfp_dma); +uint8_t *sfp =dma_pool_zalloc (ha->s_dma_pool,GFP_KERNEL , &sfp_dma);if (!sfp) { bsg_reply->reply_data.vendor_reply.vendor_rsp[0] =
@@ -1669,7 +1669,7 @@ qla2x00_write_fru_status(struct bsg_jobuint8_t bsg[DMA_POOL_SIZE ];struct qla_status_reg *sr = (void *)bsg;dma_addr_t sfp_dma; -uint8_t *sfp =dma_pool_alloc (ha->s_dma_pool,GFP_KERNEL , &sfp_dma); +uint8_t *sfp =dma_pool_zalloc (ha->s_dma_pool,GFP_KERNEL , &sfp_dma);if (!sfp) { bsg_reply->reply_data.vendor_reply.vendor_rsp[0] =
@@ -1716,7 +1716,7 @@ qla2x00_write_i2c(struct bsg_job *bsg_jouint8_t bsg[DMA_POOL_SIZE ];struct qla_i2c_access *i2c = (void *)bsg;dma_addr_t sfp_dma; -uint8_t *sfp =dma_pool_alloc (ha->s_dma_pool,GFP_KERNEL , &sfp_dma); +uint8_t *sfp =dma_pool_zalloc (ha->s_dma_pool,GFP_KERNEL , &sfp_dma);if (!sfp) { bsg_reply->reply_data.vendor_reply.vendor_rsp[0] =
@@ -1762,7 +1762,7 @@ qla2x00_read_i2c(struct bsg_job *bsg_jobuint8_t bsg[DMA_POOL_SIZE ];struct qla_i2c_access *i2c = (void *)bsg;dma_addr_t sfp_dma; -uint8_t *sfp =dma_pool_alloc (ha->s_dma_pool,GFP_KERNEL , &sfp_dma); +uint8_t *sfp =dma_pool_zalloc (ha->s_dma_pool,GFP_KERNEL , &sfp_dma);if (!sfp) { bsg_reply->reply_data.vendor_reply.vendor_rsp[0] =
Greg Kroah-Hartman
maintainerPATCH 417/556 scsi: qla2xxx: Bound i2c->length in I2C bsg handlers
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Nilesh Javali <[email protected]>
commit 0918ee2c0eeb4d7f45b82b3dc11e65c2d9b7ad59 upstream.
struct qla_i2c_access carries a 16-bit length field alongside a fixed 64-byte buffer:
struct qla_i2c_access {
uint16_t device, offset, option, length;
uint8_t buffer[0x40];
} __packed;qla2x00_write_i2c() and qla2x00_read_i2c() use the user-supplied i2c->length without any bounds check. i2c is overlaid on a 256-byte on-stack buffer and sfp is a 256-byte DMA-pool buffer, so a length up to 65535 overruns both:
- write: memcpy(sfp, i2c->buffer, i2c->length) over-reads the stack and over-writes the sfp heap buffer, and qla2x00_write_sfp() then DMAs i2c->length bytes out of the 256-byte buffer.
- read: qla2x00_read_sfp() DMAs i2c->length bytes into the 256-byte sfp, then memcpy(i2c->buffer, sfp, i2c->length) overflows the 64-byte buffer inside the on-stack array.
A caller holding CAP_SYS_RAWIO can use this to corrupt the heap and the kernel stack. Reject requests whose length exceeds the buffer before any copy or DMA transfer in both handlers.
--- drivers/scsi/qla2xxx/qla_bsg.c | 12 ++++++++++++ 1 file changed, 12 insertions(+)
drivers/scsi/qla2xxx/qla_bsg.c +12 -0
@@ -1727,6 +1727,12 @@ qla2x00_write_i2c(struct bsg_job *bsg_josg_copy_to_buffer (bsg_job->request_payload.sg_list, bsg_job->request_payload.sg_cnt, i2c,sizeof (*i2c)); +if (i2c->length >sizeof (i2c->buffer)) { + bsg_reply->reply_data.vendor_reply.vendor_rsp[0 ] = +EXT_STATUS_INVALID_PARAM ; + goto dealloc; + } +memcpy (sfp, i2c->buffer, i2c->length); rval =qla2x00_write_sfp (vha, sfp_dma, sfp, i2c->device, i2c->offset, i2c->length, i2c->option);
@@ -1773,6 +1779,12 @@ qla2x00_read_i2c(struct bsg_job *bsg_jobsg_copy_to_buffer (bsg_job->request_payload.sg_list, bsg_job->request_payload.sg_cnt, i2c,sizeof (*i2c)); +if (i2c->length >sizeof (i2c->buffer)) { + bsg_reply->reply_data.vendor_reply.vendor_rsp[0 ] = +EXT_STATUS_INVALID_PARAM ; + goto dealloc; + } + rval =qla2x00_read_sfp (vha, sfp_dma, sfp, i2c->device, i2c->offset, i2c->length, i2c->option);
Greg Kroah-Hartman
maintainerPATCH 418/556 scsi: qla2xxx: edif: Fix NULL pointer deref in RX SA delete check
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Nilesh Javali <[email protected]>
commit c20ee380ca59c5a8646750c4849969a815924e2e upstream.
qla_chk_edif_rx_sa_delete_pending() obtains the SCSI command via GET_CMD_SP(sp) and immediately dereferences cmd->sc_data_direction. That command pointer can be NULL: the firmware may post a status completion for a command that has already been returned or aborted. The caller qla2x00_status_entry() acknowledges this on the very same status path, re-fetching GET_CMD_SP(sp) and bailing out with the "Command already returned" message when it is NULL -- but that check runs only after qla_chk_edif_rx_sa_delete_pending() has already dereferenced the pointer, so a NULL cmd crashes the kernel in interrupt context.
Return early when cmd is NULL, before touching cmd->sc_data_direction.
--- drivers/scsi/qla2xxx/qla_edif.c | 3 +++ 1 file changed, 3 insertions(+)
drivers/scsi/qla2xxx/qla_edif.c +3 -0
@@ -3492,6 +3492,9 @@ void qla_chk_edif_rx_sa_delete_pending(sstruct scsi_cmnd *cmd =GET_CMD_SP (sp);uint32_t handle; +if (!cmd) +return ; + handle = (uint32_t )LSW (sts24->handle);/* find out if this status iosb is for a scsi read */
Greg Kroah-Hartman
maintainerPATCH 419/556 scsi: qla2xxx: Fix Name Server logout detection on FWI2 adapters
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Nilesh Javali <[email protected]>
commit eb137255fd7aa834c4d639ae7b5e9e8ecf3a4fb2 upstream.
In the CS_PORT_LOGGED_OUT case of qla2x00_chk_ms_status(), the FWI2-capable branch compared ms_pkt->loop_id.extended against NPH_SNS to decide whether the Name Server had logged out. On FWI2 and later adapters the response is a ct_entry_24xx / ct_entry_24xx_ext, where loop_id.extended (via the legacy ms_iocb_entry_t view) aliases offset 8, which is comp_status, not nport_handle (offset 10). As this code runs under CS_PORT_LOGGED_OUT, the field read back 0x29 (CS_PORT_LOGGED_OUT) and the comparison against NPH_SNS (0x7fc) was always false.
As a result the driver never recognized a Name Server logout on FWI2/ 29xx adapters: it returned the generic QLA_FUNCTION_FAILED instead of QLA_NOT_LOGGED_IN and skipped setting LOOP_RESYNC_NEEDED / LOCAL_LOOP_UPDATE, so the fabric rediscovery triggered by an SNS logout did not happen.
Read nport_handle from the ct_entry_24xx layout (offset 10) instead. nport_handle is at the same offset in ct_entry_24xx and ct_entry_24xx_ext, so a single cast covers 24xx-class and 29xx. The non-FWI2 branch keeps using loop_id.extended, which is correct for the ms_iocb_entry_t response on those adapters.
--- drivers/scsi/qla2xxx/qla_gs.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
drivers/scsi/qla2xxx/qla_gs.c +2 -2
@@ -157,8 +157,8 @@ qla2x00_chk_ms_status(scsi_qla_host_t *vbreak ;case CS_PORT_LOGGED_OUT :if (IS_FWI2_CAPABLE (ha)) { -if (le16_to_cpu (ms_pkt->loop_id.extended) == -NPH_SNS ) +if (le16_to_cpu (((struct ct_entry_24xx *) + ms_pkt)->nport_handle) ==NPH_SNS ) lid_is_sns = true; }else { if (le16_to_cpu(ms_pkt->loop_id.extended) ==
Greg Kroah-Hartman
maintainerPATCH 420/556 scsi: qla2xxx: Fix BSG job leak on validate flash image error path
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Nilesh Javali <[email protected]>
commit 0fb52cc632464b0cd07f970341330466d772efe1 upstream.
qla28xx_validate_flash_image() returns QLA_SUCCESS (0) unconditionally, telling the FC BSG transport (fc_bsg_host_dispatch()) that the driver owns and will complete the request. But bsg_job_done() is guarded by "if (!rval)", so on the error path (rval == -EINVAL) neither the driver nor the transport completes the job. The request dangles until it times out, leaking block layer resources.
Commit c2c68225b145 ("scsi: qla2xxx: Fix bsg_done() causing double free") added the "if (!rval)" guard to a batch of BSG handlers. That is correct for handlers that also return the error code (the transport then completes the job once via fail_host_msg), but this function returns QLA_SUCCESS unconditionally, so the guard turned a correct single completion into a leak.
Always call bsg_job_done(): bsg_reply->result is DID_OK and the error is reported in vendor_rsp[0], and since the function returns 0 the transport will not complete the job a second time.
--- drivers/scsi/qla2xxx/qla_bsg.c | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-)
drivers/scsi/qla2xxx/qla_bsg.c +2 -3
@@ -3377,9 +3377,8 @@ static int qla28xx_validate_flash_image( bsg_reply->result =DID_OK <<16 ; bsg_reply->reply_payload_rcv_len =0 ; bsg_job->reply_len =sizeof (struct fc_bsg_reply ); -if (!rval) -bsg_job_done (bsg_job, bsg_reply->result, - bsg_reply->reply_payload_rcv_len); +bsg_job_done (bsg_job, bsg_reply->result, + bsg_reply->reply_payload_rcv_len);return QLA_SUCCESS ; }
Greg Kroah-Hartman
maintainerPATCH 421/556 scsi: qla2xxx: Hold vport reference in qla24xx_report_id_acquisition()
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Nilesh Javali <[email protected]>
commit 793cedee296fd819bfadc2a7ec4d52faf9c09a0a upstream.
In the format 1 path, the virtual port is located on ha->vp_list while holding vport_slock, but the lock is dropped before vp is used:qla_update_host_map() is called and VP_IDX_ACQUIRED/REGISTER_FC4_NEEDED/ REGISTER_FDMI_NEEDED are set on vp. No reference is taken across that window, so a concurrent qla24xx_deallocate_vp_id() can tear the vport down and free it, leading to a use-after-free.
Take a vport reference (vref_count) under vport_slock when the matching vp is found, and drop it after the last use of
vp. qla24xx_deallocate_vp_id() waits for vref_count to reach zero before unlinking and freeing the vport, so the pointer stays valid. This matches the reference idiom already used by the other ha->vp_list traversals.
--- drivers/scsi/qla2xxx/qla_mbx.c | 3 +++ 1 file changed, 3 insertions(+)
drivers/scsi/qla2xxx/qla_mbx.c +3 -0
@@ -4203,6 +4203,7 @@ qla24xx_report_id_acquisition(scsi_qla_hlist_for_each_entry (vp, &ha->vp_list, list) {if (rptid_entry->vp_idx == vp->vp_idx) { found =1 ; +atomic_inc (&vp->vref_count);break ; } }
@@ -4220,6 +4221,8 @@ qla24xx_report_id_acquisition(scsi_qla_hset_bit (VP_IDX_ACQUIRED , &vp->vp_flags);set_bit (REGISTER_FC4_NEEDED , &vp->dpc_flags);set_bit (REGISTER_FDMI_NEEDED , &vp->dpc_flags); + +atomic_dec (&vp->vref_count); }set_bit (VP_DPC_NEEDED , &vha->dpc_flags);qla2xxx_wake_dpc (vha);
Greg Kroah-Hartman
maintainerPATCH 422/556 scsi: qla2xxx: Initialize NVMe abort_work once at submission
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Nilesh Javali <[email protected]>
commit 7e85f6dbc85616de2172bce8eaf84b387a723cd1 upstream.
qla_nvme_fcp_abort() and qla_nvme_ls_abort() ran INIT_WORK() on priv->abort_work immediately before schedule_work(). INIT_WORK() reinitializes the work_struct, resetting its list head and clearing the pending bit. If an abort is issued more than once for the same command (for example, concurrent transport teardown and a timeout-driven abort), the second INIT_WORK() reinitializes a work item that is already queued, which can corrupt the workqueue list and lead to crashes or a looping worker.
Initialize priv->abort_work once at command submission, next to the existing per-command spin_lock_init(&priv->cmd_lock), and leave only schedule_work() in the abort paths. schedule_work() already does nothing when the work item is still pending, so a repeated abort no longer disturbs an in-flight work item. The command is not returned to the transport until the final kref_put()/release callback runs after abort_work has completed, so the work item is idle before priv is reused and the single submission-time INIT_WORK() is safe.
--- drivers/scsi/qla2xxx/qla_nvme.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
drivers/scsi/qla2xxx/qla_nvme.c +2 -2
@@ -463,7 +463,6 @@ static void qla_nvme_ls_abort(struct nvm }spin_unlock_irqrestore (&priv->cmd_lock, flags); -INIT_WORK (&priv->abort_work, qla_nvme_abort_work);schedule_work (&priv->abort_work); }
@@ -501,6 +500,7 @@ static int qla_nvme_ls_req(struct nvme_f priv->sp = sp;kref_init (&sp->cmd_kref);spin_lock_init (&priv->cmd_lock); +INIT_WORK (&priv->abort_work, qla_nvme_abort_work); nvme = &sp->u.iocb_cmd; priv->fd = fd; nvme->u.nvme.desc = fd;
@@ -545,7 +545,6 @@ static void qla_nvme_fcp_abort(struct nv }spin_unlock_irqrestore (&priv->cmd_lock, flags); -INIT_WORK (&priv->abort_work, qla_nvme_abort_work);schedule_work (&priv->abort_work); }
@@ -811,6 +810,7 @@ static int qla_nvme_post_cmd(struct nvmekref_init (&sp->cmd_kref);spin_lock_init (&priv->cmd_lock); +INIT_WORK (&priv->abort_work, qla_nvme_abort_work); sp->priv = priv; priv->sp = sp; sp->type =SRB_NVME_CMD ;
Greg Kroah-Hartman
maintainerPATCH 423/556 scsi: qla2xxx: Check entry_status in qla24xx_modify_vp_config()
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Nilesh Javali <[email protected]>
commit 9101c51649f5b6773a97bf5271785c948589ea1d upstream.
The Modify VP Config completion handler labelled its first error branch "error status" but tested vpmod->comp_status instead of vpmod->entry_status. Because CS_COMPLETE is 0, the following "comp_status != CS_COMPLETE" branch duplicated that test and was dead code, and entry_status was never examined at all.
When firmware rejects the IOCB early it sets entry_status while leaving comp_status zero. As the IOCB is allocated with dma_pool_zalloc(), both comp_status branches evaluate false and the handler falls through to the success path, calling fc_vport_set_state(FC_VPORT_INITIALIZING) for a configuration the firmware never accepted. This can leave the virtual port enabled on top of an invalid config and surface later as login timeouts or follow-on firmware errors.
Test entry_status in the first branch, matching qla_ctrlvp_completed() and the login/logout/abort/reset IOCB handlers; the comp_status branch then becomes the live completion-status check.
--- drivers/scsi/qla2xxx/qla_mbx.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
drivers/scsi/qla2xxx/qla_mbx.c +2 -2
@@ -4333,10 +4333,10 @@ qla24xx_modify_vp_config(scsi_qla_host_tif (rval !=QLA_SUCCESS ) {ql_dbg (ql_dbg_mbx, vha,0x10bd ,"Failed to issue VP config IOCB (%x).\n" , rval); - }else if (vpmod->comp_status !=0 ) { + }else if (vpmod->entry_status !=0 ) {ql_dbg (ql_dbg_mbx, vha,0x10be ,"Failed to complete IOCB -- error status (%x).\n" , - vpmod->comp_status); + vpmod->entry_status); rval =QLA_FUNCTION_FAILED ; }else if (vpmod->comp_status !=cpu_to_le16 (CS_COMPLETE )) { ql_dbg(ql_dbg_mbx, vha, 0x10bf,
Greg Kroah-Hartman
maintainerPATCH 424/556 scsi: qla2xxx: Zero dport diagnostics buffer to avoid info leak
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Nilesh Javali <[email protected]>
commit a152edab3854f01dd2daf3eaf8f32cbabdb3834e upstream.
qla2x00_do_dport_diagnostics() allocates the qla_dport_diag response buffer with kmalloc_obj() (non-zeroing) and, on success, copies the full sizeof(*dd) back to user space via sg_copy_from_buffer(). The inbound sg_copy_to_buffer() only fills as many bytes as the user request payload provides, and qla26xx_dport_diagnostics() zeroes only dd->buf. The options and unused[] fields are therefore copied out uninitialized, leaking kernel heap contents to user space.
Allocate with kzalloc_obj(), matching qla2x00_do_dport_diagnostics_v2().
--- drivers/scsi/qla2xxx/qla_bsg.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/scsi/qla2xxx/qla_bsg.c +1 -1
@@ -2407,7 +2407,7 @@ qla2x00_do_dport_diagnostics(struct bsg_ !IS_QLA28XX(vha->hw))return -EPERM ; - dd =kmalloc_obj (*dd); + dd =kzalloc_obj (*dd);if (!dd) {ql_log (ql_log_warn, vha,0x70db ,"Failed to allocate memory for dport.\n" );
Greg Kroah-Hartman
maintainerPATCH 425/556 scsi: qla2xxx: Bound image count in qla2x00_update_fru_versions()
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Nilesh Javali <[email protected]>
commit de62cf265dbe309f34f144a6cdbca9240317727e upstream.
qla2x00_update_fru_versions() copies the user-supplied BSG request into a fixed 256-byte stack buffer (bsg[DMA_POOL_SIZE]) and then iterates list->count times over the qla_image_version array embedded in that buffer, advancing the image pointer each iteration. count is taken directly from user input with no upper bound, while only (DMA_POOL_SIZE
- sizeof(list->count)) / sizeof(struct qla_image_version) = 6 entries actually fit. A larger count walks the image pointer off the end of the stack buffer, reading adjacent kernel stack memory and sending it to the device via qla2x00_write_sfp().
Reject requests whose declared count does not fit in the buffer.
--- drivers/scsi/qla2xxx/qla_bsg.c | 7 +++++++ 1 file changed, 7 insertions(+)
drivers/scsi/qla2xxx/qla_bsg.c +7 -0
@@ -1580,6 +1580,13 @@ qla2x00_update_fru_versions(struct bsg_j image = list->version; count = list->count; + +if (struct_size (list, version, count) >sizeof (bsg)) { + bsg_reply->reply_data.vendor_reply.vendor_rsp[0 ] = +EXT_STATUS_INVALID_PARAM ; + goto dealloc; + } +while (count--) {memcpy (sfp, &image->field_info,sizeof (image->field_info)); rval = qla2x00_write_sfp(vha, sfp_dma, sfp,
Greg Kroah-Hartman
maintainerPATCH 426/556 scsi: qla2xxx: Hold qpair lock when sending NVMe LS reject
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Nilesh Javali <[email protected]>
commit f743488e4a203049f27ec5d8cd0caccc483af01e upstream.
qla_nvme_ls_reject_iocb() allocates from and advances the request ring through __qla2x00_alloc_iocbs() (which assumes the hardware_lock is held) and qla2x00_start_iocbs() (which advances the ring and rings the request-in doorbell), but takes no lock itself. Two of its callers invoke it without the producer lock held:
- qla_nvme_xmt_ls_rsp(), the NVMe-FC .xmt_ls_rsp transport callback, on its error path, and
- qla2xxx_process_purls_pkt(), run from the purex work/DPC context.
Both use ha->base_qpair, whose qp_lock_ptr is hardware_lock, so they can run concurrently with normal I/O submission on the base ring and corrupt the ring producer state, leading to duplicated or dropped commands. The third caller, qla2xxx_process_purls_iocb(), runs inside qla24xx_process_response_queue() with the qpair lock already held and is safe; that is also why the lock cannot be taken inside the helper itself (it would recursively re-acquire hardware_lock on the response path).
Take qp_lock_ptr around the two unlocked callers and document the helper as caller-locked. Both run in process context, so spin_lock_irqsave() is used and nothing in the locked region sleeps.
--- drivers/scsi/qla2xxx/qla_nvme.c | 10 ++++++++++ 1 file changed, 10 insertions(+)
drivers/scsi/qla2xxx/qla_nvme.c +10 -0
@@ -374,6 +374,7 @@ static int qla_nvme_xmt_ls_rsp(struct nvsrb_t *sp;int rval =QLA_FUNCTION_FAILED ;uint8_t cnt =0 ; +unsigned long flags;if (!fcport || fcport->deleted) goto out;
@@ -440,7 +441,9 @@ out: a.vp_idx = vha->vp_idx; a.nport_handle = uctx->nport_handle; a.xchg_address = uctx->exchange_address; +spin_lock_irqsave (ha->base_qpair->qp_lock_ptr, flags);qla_nvme_ls_reject_iocb (vha, ha->base_qpair, &a, true); +spin_unlock_irqrestore (ha->base_qpair->qp_lock_ptr, flags);kfree (uctx);return rval; }
@@ -1127,6 +1130,10 @@ static void qla_nvme_lsrjt_pt_iocb(struc lsrjt_iocb->rx_byte_count =0 ; } +/* +* Allocates from and advances the request ring, so the caller must hold +* qp->qp_lock_ptr (the response-queue caller already holds it). +*/ static int qla_nvme_ls_reject_iocb (struct scsi_qla_host *vha,struct qla_qpair *qp,struct qla_nvme_lsrjt_pt_arg *a,bool is_xchg_terminate)
@@ -1183,6 +1190,7 @@ qla2xxx_process_purls_pkt(struct scsi_ql {struct qla_nvme_unsol_ctx *uctx = item->purls_context;struct qla_nvme_lsrjt_pt_arg a; +unsigned long flags;int ret =1 ;#if (IS_ENABLED (CONFIG_NVME_FC ))
@@ -1195,7 +1203,9 @@ qla2xxx_process_purls_pkt(struct scsi_ql a.vp_idx = vha->vp_idx; a.nport_handle = uctx->nport_handle; a.xchg_address = uctx->exchange_address; +spin_lock_irqsave (vha->hw->base_qpair->qp_lock_ptr, flags);qla_nvme_ls_reject_iocb (vha, vha->hw->base_qpair, &a, true); +spin_unlock_irqrestore (vha->hw->base_qpair->qp_lock_ptr, flags);list_del (&uctx->elem);kfree (uctx); }
Greg Kroah-Hartman
maintainerPATCH 427/556 scsi: qla2xxx: Clamp MSI-X derived queue counts to avoid truncation
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Nilesh Javali <[email protected]>
commit ebfd35c64433821bd5619a6d07ccc2df8b5b1de3 upstream.
ha->msix_count is u16, but ha->max_req_queues, ha->max_rsp_queues and ha->max_qpairs are u8. Deriving the queue count as "ha->max_req_queues = ha->msix_count - 1" therefore truncates: a board (or a misconfigured/malicious hot-plugged device) advertising 257 MSI-X vectors yields msix_count - 1 == 256, which truncates to 0. An MSI-X count of 1 zeroes it as well, and in target mode the subsequent "ha->max_req_queues--" then underflows 0 to 255.
When the count is 0, qla2x00_alloc_queues() calls kzalloc_objs(struct req_que *, 0), which returns ZERO_SIZE_PTR. That is not NULL, so the allocation check passes and the following "ha->req_q_map[0] = req" dereferences ZERO_SIZE_PTR, corrupting memory or crashing the kernel.
Add qla_calc_queue_count() to clamp the derived value into [1, QLA_MAX_QUEUES - 1] so it always fits in u8 and is never zero, and use it at all three derivation sites (qla25xx_iospace_config(), qla83xx_iospace_config() and qla24xx_enable_msix()). Also guard the target-mode decrement so it cannot reintroduce a zero (which would in turn underflow max_qpairs).
--- drivers/scsi/qla2xxx/qla_inline.h | 13 +++++++++++++ drivers/scsi/qla2xxx/qla_isr.c | 4 ++-- drivers/scsi/qla2xxx/qla_os.c | 6 +++--- 3 files changed, 18 insertions(+), 5 deletions(-)
drivers/scsi/qla2xxx/qla_inline.h +13 -0
@@ -54,6 +54,19 @@ qla2x00_debounce_register(volatile __le1return (first); } +static inline u8 +qla_calc_queue_count (u16 msix_count) +{ +/* +* Request/response queues are bounded by the MSI-X vector count less +* the mailbox vector. These counters are u8, so a board advertising +* e.g. 257 vectors would truncate msix_count - 1 (256) to 0 and hand +* kzalloc_objs() a zero count (ZERO_SIZE_PTR), faulting on the first +* ha->req_q_map[0] store. Clamp into [1, QLA_MAX_QUEUES - 1]. +*/ +return clamp_t (u16, msix_count -1 ,1 ,QLA_MAX_QUEUES -1 ); +} +static inline void qla2x00_poll (struct rsp_que *rsp) {
drivers/scsi/qla2xxx/qla_isr.c +2 -2
@@ -4548,10 +4548,10 @@ qla24xx_enable_msix(struct qla_hw_data * ha->msix_count = ret;/* Recalculate queue values */ if (ha->mqiobase && (ql2xmqsupport || ql2xnvmeenable)) { - ha->max_req_queues = ha->msix_count -1 ; + ha->max_req_queues =qla_calc_queue_count (ha->msix_count);/* ATIOQ needs 1 vector. That's 1 less QPair */ -if (QLA_TGT_MODE_ENABLED ()) +if (QLA_TGT_MODE_ENABLED () && ha->max_req_queues >1 ) ha->max_req_queues--; ha->max_rsp_queues = ha->max_req_queues;
drivers/scsi/qla2xxx/qla_os.c +3 -3
@@ -2127,7 +2127,7 @@ skip_pio: ha->msix_count = msix +1 ;/* Max queues are bounded by available msix vectors */ /* MB interrupt uses 1 vector */ - ha->max_req_queues = ha->msix_count -1 ; + ha->max_req_queues =qla_calc_queue_count (ha->msix_count); ha->max_rsp_queues = ha->max_req_queues;/* Queue pairs is the max value minus the base queue pair */ ha->max_qpairs = ha->max_rsp_queues -1 ;
@@ -2213,10 +2213,10 @@ qla83xx_iospace_config(struct qla_hw_dat*/ if (ql2xmqsupport || ql2xnvmeenable) {/* MB interrupt uses 1 vector */ - ha->max_req_queues = ha->msix_count -1 ; + ha->max_req_queues =qla_calc_queue_count (ha->msix_count);/* ATIOQ needs 1 vector. That's 1 less QPair */ -if (QLA_TGT_MODE_ENABLED ()) +if (QLA_TGT_MODE_ENABLED () && ha->max_req_queues >1 ) ha->max_req_queues--; ha->max_rsp_queues = ha->max_req_queues;
Greg Kroah-Hartman
maintainerPATCH 428/556 scsi: qla2xxx: Serialize flash version read in reset handler
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Nilesh Javali <[email protected]>
commit f606ed93de0c4f1e7e3618779e9fad731455314a upstream.
The "update cache versions without reset" sysfs reset operation (0x20261) calls get_flash_version(), which reads hardware flash registers, without holding ha->optrom_mutex. The VPD update path serializes the same call under optrom_mutex, so this reset path can interleave its flash register accesses with a concurrent VPD or optrom flash operation and corrupt the reads.
Hold ha->optrom_mutex across the get_flash_version() call to match the VPD update path.
--- drivers/scsi/qla2xxx/qla_attr.c | 2 ++ 1 file changed, 2 insertions(+)
drivers/scsi/qla2xxx/qla_attr.c +2 -0
@@ -816,7 +816,9 @@ qla2x00_sysfs_write_reset(struct file *f "Unable to allocate memory for VPD information update.\n");return -ENOMEM ; } +mutex_lock (&ha->optrom_mutex); ha->isp_ops->get_flash_version (vha, tmp_data); +mutex_unlock (&ha->optrom_mutex);vfree (tmp_data);break ; }
Greg Kroah-Hartman
maintainerPATCH 429/556 scsi: qla2xxx: Fix cs84xx use-after-free on host teardown
In reply to Greg Kroah-Hartman7.2-stable review patch. If anyone has any objections, please let me know.
------------------
From: Nilesh Javali <[email protected]>
commit 33d102102d925357c5fd172dd6672a27d74b3215 upstream.
qla84xx_put_chip() drops the last reference to ha->cs84xx and frees it via __qla84xx_chip_release() without clearing ha->cs84xx. During teardown it ran before scsi_remove_host(), which is what removes the 84xx_fw_version host sysfs attribute. A concurrent read of that attribute in the window between the two calls executes qla24xx_84xx_fw_version_show(), which dereferences the freed ha->cs84xx, resulting in a use-after-free.
Move qla84xx_put_chip() to after scsi_remove_host() in both qla2x00_remove_one() and qla2x00_disable_board_on_pci_error(). Once scsi_remove_host() returns, the sysfs attribute is gone and kernfs has drained any in-flight show(), so no reader can touch cs84xx; the put still runs before the host and ha are freed.
--- drivers/scsi/qla2xxx/qla_os.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-)
drivers/scsi/qla2xxx/qla_os.c +4 -4
@@ -3933,8 +3933,6 @@ qla2x00_remove_one(struct pci_dev *pdev)qla2x00_dfs_remove (base_vha); -qla84xx_put_chip (base_vha); -/* Disable timer */ if (base_vha->timer_active)qla2x00_stop_timer (base_vha);
@@ -3959,6 +3957,8 @@ qla2x00_remove_one(struct pci_dev *pdev)scsi_remove_host (base_vha->host); +qla84xx_put_chip (base_vha); +qla2x00_free_device (base_vha);qla2x00_clear_drv_active (ha);
@@ -6828,8 +6828,6 @@ qla2x00_disable_board_on_pci_error(strucqla2x00_dfs_remove (base_vha); -qla84xx_put_chip (base_vha); -if (base_vha->timer_active)qla2x00_stop_timer (base_vha);
@@ -6847,6 +6845,8 @@ qla2x00_disable_board_on_pci_error(strucscsi_remove_host (base_vha->host); +qla84xx_put_chip (base_vha); + base_vha->flags.init_done =0 ;qla25xx_delete_queues (base_vha);qla2x00_free_fcports (base_vha);