summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorW GTO <[email protected]>2026-09-22 16:28:39 +0800
committerRbb666 <[email protected]>2026-11-24 15:11:28 +0800
commit209ea55c3210f69bf772cc80e22371d6057e63a1 (patch)
tree7044672e4f7e841b42efffc1fb510a2abed27e3d
parent9586ba568a04058edb545491a4230039cc4a39f0 (diff)
[drivers][i2c] Serialize bus control with transfers
Hold the bus mutex while dispatching control commands and changing max_hz. Use a common unlock path and propagate mutex errors as in rt_i2c_transfer. Document the thread-context requirement. Fixes #11524
-rw-r--r--components/drivers/i2c/dev_i2c_core.c25
-rw-r--r--components/drivers/include/drivers/dev_i2c.h3
2 files changed, 22 insertions, 6 deletions
diff --git a/components/drivers/i2c/dev_i2c_core.c b/components/drivers/i2c/dev_i2c_core.c
index fd7774e034..87434df851 100644
--- a/components/drivers/i2c/dev_i2c_core.c
+++ b/components/drivers/i2c/dev_i2c_core.c
@@ -100,7 +100,15 @@ rt_err_t rt_i2c_control(struct rt_i2c_bus_device *bus,
int cmd,
void *args)
{
- rt_err_t ret;
+ rt_err_t ret = RT_EOK;
+ rt_err_t err;
+
+ /* Serialize configuration changes with transfers on this bus. */
+ err = rt_mutex_take(&bus->lock, RT_WAITING_FOREVER);
+ if (err != RT_EOK)
+ {
+ return err;
+ }
switch (cmd)
{
@@ -108,7 +116,8 @@ rt_err_t rt_i2c_control(struct rt_i2c_bus_device *bus,
{
if (args == RT_NULL)
{
- return -RT_ERROR;
+ ret = -RT_ERROR;
+ break;
}
rt_uint32_t max_hz = *(rt_uint32_t *)args;
@@ -118,7 +127,7 @@ rt_err_t rt_i2c_control(struct rt_i2c_bus_device *bus,
}
else
{
- return -RT_ERROR;
+ ret = -RT_ERROR;
}
break;
}
@@ -127,17 +136,21 @@ rt_err_t rt_i2c_control(struct rt_i2c_bus_device *bus,
if(bus->ops->i2c_bus_control)
{
ret = bus->ops->i2c_bus_control(bus, cmd, args);
- return ret;
}
else
{
LOG_E("I2C bus operation not supported");
- return -RT_EINVAL;
+ ret = -RT_EINVAL;
}
break;
}
}
- return RT_EOK;
+ err = rt_mutex_release(&bus->lock);
+ if (err != RT_EOK)
+ {
+ return err;
+ }
+ return ret;
}
rt_ssize_t rt_i2c_master_send(struct rt_i2c_bus_device *bus,
diff --git a/components/drivers/include/drivers/dev_i2c.h b/components/drivers/include/drivers/dev_i2c.h
index 869917855e..969528780f 100644
--- a/components/drivers/include/drivers/dev_i2c.h
+++ b/components/drivers/include/drivers/dev_i2c.h
@@ -369,6 +369,9 @@ rt_ssize_t rt_i2c_transfer(struct rt_i2c_bus_device *bus,
/**
* @brief I2C Control
*
+ * @note This function takes the bus mutex and must be called from thread context.
+ * Configuration changes are serialized with transfers on the same bus.
+ *
* @param bus the I2C bus device
* @param cmd the I2C control command
* @param args the I2C control arguments