Like the PM subsystem routine pm_runtime_irq_safe() and flag 'irq_safe' add a similar function i2c_adapter_irq_safe() to the I2C core. A driver should be able to announce whether his transfer implementations are safe to be called in IRQ disabled or atomic contexts, also called polling mode or sleep free operation. Making I2C transfers in atomic context is sometimes needed, e.g. for reboot handlers. Every driver should be able to declare explicitly whether IRQ disabled operation is supported or not. When you try make a I2C transfer in atomic contexts, it's already hard enough to ensure that every code path through the kernel is sleep-free. So give the curious developer a strong hint whether a driver supports atomic operation or not. Fail early instead of hoping that the LOCKDEP framework noticed the programming error. TODOs: - checkpatch complains hat in_atomic() should not be used in driver code Signed-off-by: Stefan Lengfeld <contact@xxxxxxxxxxxxxxx> --- drivers/i2c/i2c-core-base.c | 8 ++++++++ include/linux/i2c.h | 16 ++++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/drivers/i2c/i2c-core-base.c b/drivers/i2c/i2c-core-base.c index 15c95aaa484c..d4a76c8cd777 100644 --- a/drivers/i2c/i2c-core-base.c +++ b/drivers/i2c/i2c-core-base.c @@ -1858,6 +1858,14 @@ int __i2c_transfer(struct i2c_adapter *adap, struct i2c_msg *msgs, int num) if (adap->quirks && i2c_check_for_quirks(adap, msgs, num)) return -EOPNOTSUPP; + if (in_atomic() || irqs_disabled()) { + if (!adap->irq_safe) { + dev_err(&adap->dev, + "IRQ disabled transfers not supported by the driver\n"); + return -EOPNOTSUPP; + } + } + /* * i2c_trace_msg_key gets enabled when tracepoint i2c_transfer gets * enabled. This is an efficient way of keeping the for-loop from diff --git a/include/linux/i2c.h b/include/linux/i2c.h index 254cd34eeae2..f2d31ba09afe 100644 --- a/include/linux/i2c.h +++ b/include/linux/i2c.h @@ -664,6 +664,13 @@ struct i2c_adapter { const struct i2c_algorithm *algo; /* the algorithm to access the bus */ void *algo_data; + /* + * implementations in i2c_algorithm like 'master_xfer' are safe to be + * use in IRQ disabled contexts. A driver should set the flag with + * i2c_adapter_irq_safe() in it's probe function. + */ + bool irq_safe; + /* data fields that are valid for all devices */ const struct i2c_lock_operations *lock_ops; struct rt_mutex bus_lock; @@ -710,6 +717,15 @@ i2c_parent_is_i2c_adapter(const struct i2c_adapter *adapter) return NULL; } +/** + * i2c_adapter_irq_safe - driver is safe to be used in IRQ disabled context + * @adapter: Target I2C bus segment + */ +static inline void i2c_adapter_irq_safe(struct i2c_adapter *adapter) +{ + adapter->irq_safe = true; +} + int i2c_for_each_dev(void *data, int (*fn)(struct device *, void *)); /* Adapter locking functions, exported for shared pin cases */ -- 2.16.4